Skip to content

Truly independent web browser

LibWeb+Meta: Implement the CSS namespace in Rust

Andreas Kling8c5e0a37bb5a
diff --git a/Libraries/LibWeb/Bindings/Rust/build.rs b/Libraries/LibWeb/Bindings/Rust/build.rs
index 81d36180bc1..3ec0e388120 100644
--- a/Libraries/LibWeb/Bindings/Rust/build.rs
+++ b/Libraries/LibWeb/Bindings/Rust/build.rs
@@ -93,6 +93,7 @@ fn main() {
.expect("the crate is in Libraries/LibWeb/Bindings/Rust");
generate_webgl_command_recording(libraries, &out_dir);
generate_webgl_constants(libraries, &out_dir);
+ generate_css_numeric_factories(libraries, &out_dir);
println!("cargo:rustc-check-cfg=cfg(web_idl_bindings)");
println!("cargo:rerun-if-env-changed=LIBWEB_RUST_BINDINGS");
@@ -109,3 +110,28 @@ fn main() {
println!("cargo:rustc-cfg=web_idl_bindings");
println!("cargo:rustc-env=LIBWEB_RUST_BINDINGS={}", bindings.display());
}
+
+/// The functions of the CSS namespace that make a CSSUnitValue of a unit, one for each unit of CSS/Units.json,
+/// https://drafts.css-houdini.org/css-typed-om-1/#numeric-factory
+fn generate_css_numeric_factories(libraries: &Path, out_dir: &Path) {
+ let units_path = libraries.join("LibWeb/CSS/Units.json");
+ println!("cargo:rerun-if-changed={}", units_path.display());
+ let units = fs::read_to_string(&units_path).expect("CSS/Units.json is readable");
+ let dimensions: serde_json::Value = serde_json::from_str(&units).expect("CSS/Units.json is JSON");
+
+ let mut names = vec!["number".to_string(), "percent".to_string()];
+ for units in dimensions.as_object().expect("CSS/Units.json is an object").values() {
+ names.extend(units.as_object().expect("a dimension is an object").keys().cloned());
+ }
+
+ let mut output = String::from("impl CSS {\n");
+ for name in names {
+ let function = name.to_lowercase();
+ let identifier = if function == "in" { "r#in".to_string() } else { function };
+ output.push_str(&format!(
+ " pub(crate) fn {identifier}(cx: &mut CallContext, value: f64) -> WebIdlResult<Ref<CSSUnitValue>> {{\n Self::numeric_factory(cx, value, \"{name}\")\n }}\n\n"
+ ));
+ }
+ output.push_str("}\n");
+ fs::write(out_dir.join("css_numeric_factories.rs"), output).expect("the output directory is writable");
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css.rs
new file mode 100644
index 00000000000..4a0a5a8f631
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css.rs
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2021-2025, Sam Atkins <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The CSS namespace, https://www.w3.org/TR/cssom-1/#namespacedef-css
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libweb_rust::typed_om::{self, RegisteredSyntax, RetainedStyleValue};
+
+use super::css_unit_value::CSSUnitValue;
+use super::highlight_registry::HighlightRegistry;
+use crate::bindings::interface::{Ref, cell_from_abi};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_realm_document(realm: *mut c_void) -> *mut c_void;
+ fn web_css_namespace_highlight_registry(document: *mut c_void) -> *mut c_void;
+ fn web_css_namespace_is_registered(document: *mut c_void, name: usize) -> bool;
+ fn web_css_namespace_parse_initial_value_descriptor(document: *mut c_void, value: usize) -> *const c_void;
+ fn web_css_namespace_parse_with_a_syntax(
+ document: *mut c_void,
+ value: usize,
+ syntax: *const c_void,
+ ) -> *const c_void;
+ fn web_css_namespace_register(
+ document: *mut c_void,
+ name: usize,
+ syntax: *const c_void,
+ inherits: bool,
+ initial_value: *const c_void,
+ );
+}
+
+// https://drafts.css-houdini.org/css-properties-values-api-1/#dictdef-propertydefinition
+pub(crate) struct PropertyDefinition {
+ pub(crate) name: Utf16String,
+ pub(crate) syntax: Utf16String,
+ pub(crate) inherits: bool,
+ pub(crate) initial_value: Option<Utf16String>,
+}
+
+fn syntax_error(message: &str) -> Exception {
+ Exception::Dom("SyntaxError", Utf16String::from_utf8(message))
+}
+
+fn optional_style_value(pointer: *const c_void) -> Option<RetainedStyleValue> {
+ // SAFETY: C++ hands over a strong reference to a style value.
+ (!pointer.is_null()).then(|| unsafe { RetainedStyleValue::from_raw(pointer) })
+}
+
+// https://www.w3.org/TR/cssom-1/#namespacedef-css
+#[allow(clippy::upper_case_acronyms)]
+pub(crate) struct CSS;
+
+impl CSS {
+ fn document(cx: &CallContext) -> *mut c_void {
+ // SAFETY: The realm is live.
+ unsafe { web_css_realm_document(cx.realm().as_ptr().cast()) }
+ }
+
+ // https://www.w3.org/TR/cssom-1/#dom-css-escape
+ pub(crate) fn escape(_: &mut CallContext, ident: Utf16String) -> WebIdlResult<Utf16String> {
+ // The escape(ident) operation must return the result of invoking serialize an identifier of ident.
+ Ok(typed_om::serialize_an_identifier(&ident))
+ }
+
+ // https://www.w3.org/TR/css-conditional-3/#dom-css-supports
+ pub(crate) fn supports_property(
+ _: &mut CallContext,
+ property: Utf16String,
+ value: Utf16String,
+ ) -> WebIdlResult<bool> {
+ // 1. If property is an ASCII case-insensitive match for any defined CSS property that the UA supports, or is a
+ // custom property name string, and value successfully parses according to that property’s grammar, return
+ // true.
+ // 2. Otherwise, return false.
+ let Some((_, property_id)) = typed_om::property_from_name(&property) else {
+ return Ok(false);
+ };
+ Ok(typed_om::parse_value_for_property(property_id, &value).is_some())
+ }
+
+ // https://www.w3.org/TR/css-conditional-3/#dom-css-supports
+ pub(crate) fn supports_condition(_: &mut CallContext, condition_text: Utf16String) -> WebIdlResult<bool> {
+ // 1. If conditionText, parsed and evaluated as a <supports-condition>, would return true, return true.
+ if typed_om::supports_condition_matches(&condition_text) {
+ return Ok(true);
+ }
+
+ // 2. Otherwise, If conditionText, wrapped in parentheses and then parsed and evaluated as a
+ // <supports-condition>, would return true, return true.
+ let mut wrapped_condition_text = vec![u16::from(b'(')];
+ wrapped_condition_text.extend_from_slice(condition_text.to_utf16().as_ref());
+ wrapped_condition_text.push(u16::from(b')'));
+ if typed_om::supports_condition_matches(&Utf16String::from_utf16(&wrapped_condition_text)) {
+ return Ok(true);
+ }
+
+ // 3. Otherwise, return false.
+ Ok(false)
+ }
+
+ // https://www.w3.org/TR/css-properties-values-api-1/#the-registerproperty-function
+ pub(crate) fn register_property(cx: &mut CallContext, definition: PropertyDefinition) -> WebIdlResult<()> {
+ // 1. Let property set be the value of the current global object’s associated Document’s
+ // [[registeredPropertySet]] slot.
+ let document = Self::document(cx);
+
+ // 2. If name is not a custom property name string, throw a SyntaxError and exit this algorithm.
+ if !typed_om::is_a_custom_property_name_string(&definition.name) {
+ return Err(syntax_error("Invalid property name"));
+ }
+
+ // If property set already contains an entry with name as its property name (compared codepoint-wise),
+ // throw an InvalidModificationError and exit this algorithm.
+ // SAFETY: The document is live, and this hands over a reference to the string.
+ if unsafe { web_css_namespace_is_registered(document, definition.name.clone().into_raw()) } {
+ return Err(Exception::Dom(
+ "InvalidModificationError",
+ Utf16String::from_ascii(b"Property already registered"),
+ ));
+ }
+
+ // 3. Attempt to consume a syntax definition from syntax. If it returns failure, throw a SyntaxError.
+ // Otherwise, let syntax definition be the returned syntax definition.
+ let Some(syntax_definition) = RegisteredSyntax::parse(&definition.syntax) else {
+ return Err(syntax_error("Invalid syntax definition"));
+ };
+
+ // 4. If syntax definition is the universal syntax definition, and initialValue is not present,
+ let parsed_initial_value = match (syntax_definition.is_universal(), definition.initial_value) {
+ // let parsed initial value be empty.
+ // This must be treated identically to the "default" initial value of custom properties, as defined in
+ // [css-variables].
+ (true, None) => None,
+ // Otherwise, if syntax definition is the universal syntax definition,
+ // parse initialValue as a <declaration-value>
+ (true, Some(initial_value)) => {
+ // AD-HOC: Parse this as the equivalent descriptor value in order to disallow arbitrary substitution
+ // functions.
+ // SAFETY: The document is live, and this hands over a reference to the string.
+ let parsed = optional_style_value(unsafe {
+ web_css_namespace_parse_initial_value_descriptor(document, initial_value.into_raw())
+ });
+
+ // If this fails, throw a SyntaxError and exit this algorithm.
+ // Otherwise, let parsed initial value be the parsed result.
+ Some(parsed.ok_or_else(|| syntax_error("Invalid initial value"))?)
+ }
+ // Otherwise, if initialValue is not present, throw a SyntaxError and exit this algorithm.
+ (false, None) => {
+ return Err(syntax_error("Initial value must be provided for non-universal syntax"));
+ }
+ // Otherwise, parse initialValue according to syntax definition.
+ (false, Some(initial_value)) => {
+ // NB: We don't need to worry about explicitly rejecting arbitrary substitution functions here since all
+ // supported syntaxes implicitly reject them
+ // SAFETY: The document and the syntax are live, and this hands over a reference to the string.
+ let parsed = optional_style_value(unsafe {
+ web_css_namespace_parse_with_a_syntax(
+ document,
+ initial_value.into_raw(),
+ syntax_definition.as_ptr(),
+ )
+ });
+
+ // If this fails, throw a SyntaxError and exit this algorithm.
+ // Otherwise, let parsed initial value be the parsed result.
+ let parsed = parsed
+ .filter(|value| !value.is_guaranteed_invalid())
+ .ok_or_else(|| syntax_error("Invalid initial value"))?;
+
+ // If parsed initial value is not computationally independent, throw a SyntaxError and exit this
+ // algorithm.
+ if !parsed.is_computationally_independent() {
+ return Err(syntax_error("Initial value must be computationally independent"));
+ }
+ Some(parsed)
+ }
+ };
+
+ // 5. Set inherit flag to the value of inherits.
+ // 6. Let registered property be a struct with a property name of name, a syntax of syntax definition,
+ // an initial value of parsed initial value, and an inherit flag of inherit flag.
+ // Append registered property to property set.
+ // SAFETY: The document is live, and this hands over references to the string, the syntax and the value.
+ unsafe {
+ web_css_namespace_register(
+ document,
+ definition.name.into_raw(),
+ syntax_definition.into_raw(),
+ definition.inherits,
+ parsed_initial_value.map_or(core::ptr::null(), RetainedStyleValue::into_raw),
+ );
+ }
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-highlight-api-1/#dom-css-highlights
+ pub(crate) fn highlights(cx: &mut CallContext) -> WebIdlResult<Ref<HighlightRegistry>> {
+ // The highlight registry is accessed via the highlights attribute of the CSS namespace, and represents all the
+ // custom highlights registered for the current global object’s associated Document.
+ // SAFETY: The document is live, and it returns its live registry.
+ Ok(unsafe { cell_from_abi::<HighlightRegistry>(web_css_namespace_highlight_registry(Self::document(cx))) })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#numeric-factory
+ fn numeric_factory(cx: &CallContext, value: f64, unit: &str) -> WebIdlResult<Ref<CSSUnitValue>> {
+ // All of the above methods must, when called with a double value, return a new CSSUnitValue whose value
+ // internal slot is set to value and whose unit internal slot is set to the name of the method as defined here.
+ Ok(CSSUnitValue::create(cx.vm(), value, unit))
+ }
+}
+
+// NB: The numeric factories of the units in CSS/Units.json.
+include!(concat!(env!("OUT_DIR"), "/css_numeric_factories.rs"));
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index faa53bea0af..c4b6302efdd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -7,6 +7,8 @@
//! The CSS Object Model, https://drafts.csswg.org/cssom/
pub(crate) mod animation_event;
+#[allow(clippy::module_inception)]
+pub(crate) mod css;
pub(crate) mod css_condition_rule;
pub(crate) mod css_container_rule;
pub(crate) mod css_counter_style_rule;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8907d7be3f2..9947ac310c7 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1072,7 +1072,6 @@ set(GENERATED_SOURCES
CSS/DefaultStyleSheetSource.cpp
CSS/DescriptorID.cpp
CSS/Enums.cpp
- CSS/GeneratedCSSNumericFactoryMethods.cpp
CSS/GeneratedCSSNumericFactoryMethods.idl
CSS/Keyword.cpp
CSS/MediaFeatureID.h
diff --git a/Libraries/LibWeb/CSS/BindingsGlue.h b/Libraries/LibWeb/CSS/BindingsGlue.h
index 55c92bf4ead..c45ff5e7bfd 100644
--- a/Libraries/LibWeb/CSS/BindingsGlue.h
+++ b/Libraries/LibWeb/CSS/BindingsGlue.h
@@ -15,7 +15,6 @@
#include <LibJS/Forward.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/Value.h>
-#include <LibWeb/CSS/CSS.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/Scripting/Environments.h>
@@ -33,12 +32,6 @@ class FontFaceSet;
namespace Web::Bindings {
-inline WebIDL::ExceptionOr<void> register_property(JS::Realm& realm, CSS::PropertyDefinition const& definition)
-{
- auto& window = HTML::relevant_window(realm.global_object());
- return CSS::register_property(window.associated_document(), definition);
-}
-
WEB_API void resolve_font_face_list_promise(JS::Realm&, WebIDL::Promise const&, Vector<NonnullRefPtr<CSS::FontFaceState>> const&);
WEB_API void resolve_font_face_set_promise(JS::Realm&, WebIDL::Promise const&, CSS::FontFaceSet&);
WEB_API GC::Ref<JS::Set> setlike_entries(JS::Realm&, WrapperWorld const&, CSS::FontFaceSet const&);
diff --git a/Libraries/LibWeb/CSS/CSS.cpp b/Libraries/LibWeb/CSS/CSS.cpp
index b8efd6267af..9a8153df8a9 100644
--- a/Libraries/LibWeb/CSS/CSS.cpp
+++ b/Libraries/LibWeb/CSS/CSS.cpp
@@ -5,161 +5,74 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Utf16StringBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/CSS/CSS.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
#include <LibWeb/CSS/CustomPropertyRegistration.h>
#include <LibWeb/CSS/HighlightRegistry.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/Parser/SyntaxParsing.h>
-#include <LibWeb/CSS/PropertyID.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/Serialize.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Window.h>
+
+// What the Rust implementation of the CSS namespace (Libraries/LibWeb/Bindings/Rust/src/css/css.rs) asks of the
+// document it works on.
namespace Web::CSS {
-// https://www.w3.org/TR/cssom-1/#dom-css-escape
-WebIDL::ExceptionOr<Utf16String> escape(JS::VM&, Utf16View identifier)
-{
- // The escape(ident) operation must return the result of invoking serialize an identifier of ident.
- return serialize_an_identifier_to_utf16(identifier);
-}
+using StyleValueData = StyleValueFFI::StyleValueData;
-// https://www.w3.org/TR/css-conditional-3/#dom-css-supports
-bool supports(JS::VM&, Utf16FlyString const& property_name, Utf16View value)
-{
- // 1. If property is an ASCII case-insensitive match for any defined CSS property that the UA supports, or is a
- // custom property name string, and value successfully parses according to that property’s grammar, return true.
- if (auto property = PropertyNameAndID::from_name(property_name); property.has_value()) {
- if (parse_css_value(Parser::ParsingParams {}, value, property->id()))
- return true;
- }
+extern "C" {
- // 2. Otherwise, return false.
- return false;
+// Declared in Bindings/Rust/src/css/css.rs.
+void* web_css_namespace_highlight_registry(void* document);
+bool web_css_namespace_is_registered(void* document, FlatPtr name);
+StyleValueData const* web_css_namespace_parse_initial_value_descriptor(void* document, FlatPtr value);
+StyleValueData const* web_css_namespace_parse_with_a_syntax(void* document, FlatPtr value, void const* syntax);
+void web_css_namespace_register(void* document, FlatPtr name, void const* syntax, bool inherits, StyleValueData const* initial_value);
}
-// https://www.w3.org/TR/css-conditional-3/#dom-css-supports
-WebIDL::ExceptionOr<bool> supports(JS::VM& vm, Utf16View condition_text)
+static DOM::Document& document_from_abi(void* document)
{
- (void)vm;
- // 1. If conditionText, parsed and evaluated as a <supports-condition>, would return true, return true.
- if (auto supports = parse_css_supports(Parser::ParsingParams {}, condition_text); supports.has_value() && supports_condition_matches(*supports))
- return true;
-
- // 2. Otherwise, If conditionText, wrapped in parentheses and then parsed and evaluated as a <supports-condition>, would return true, return true.
- Utf16StringBuilder wrapped_condition_text_builder;
- wrapped_condition_text_builder.append_code_unit(u'(');
- wrapped_condition_text_builder.append(condition_text);
- wrapped_condition_text_builder.append_code_unit(u')');
- auto wrapped_condition_text = wrapped_condition_text_builder.to_string();
-
- if (auto supports = parse_css_supports(Parser::ParsingParams {}, wrapped_condition_text); supports.has_value() && supports_condition_matches(*supports))
- return true;
-
- // 3. Otherwise, return false.
- return false;
+ return *static_cast<DOM::Document*>(static_cast<GC::Cell*>(document));
}
-// https://www.w3.org/TR/css-properties-values-api-1/#the-registerproperty-function
-WebIDL::ExceptionOr<void> register_property(DOM::Document& document, PropertyDefinition const& definition)
+static StyleValueData const* into_rust(RefPtr<StyleValue const> const& value)
{
- // 1. Let property set be the value of the current global object’s associated Document’s [[registeredPropertySet]] slot.
- auto& property_set = document.registered_property_set();
-
- // 2. If name is not a custom property name string, throw a SyntaxError and exit this algorithm.
- if (!is_a_custom_property_name_string(definition.name))
- return WebIDL::SyntaxError::create("Invalid property name"_utf16);
-
- // If property set already contains an entry with name as its property name (compared codepoint-wise),
- // throw an InvalidModificationError and exit this algorithm.
- auto property_name = Utf16FlyString { definition.name };
- if (property_set.contains(property_name))
- return WebIDL::InvalidModificationError::create("Property already registered"_utf16);
-
- auto parsing_params = CSS::Parser::ParsingParams { document };
-
- // 3. Attempt to consume a syntax definition from syntax. If it returns failure, throw a SyntaxError.
- // Otherwise, let syntax definition be the returned syntax definition.
- auto maybe_syntax = parse_as_syntax(definition.syntax, Parser::LimitSingleComponentIdentToCustomIdent::Yes);
- if (!maybe_syntax.has_value()) {
- return WebIDL::SyntaxError::create("Invalid syntax definition"_utf16);
- }
-
- RefPtr<StyleValue const> initial_value_maybe;
-
- // 4. If syntax definition is the universal syntax definition, and initialValue is not present,
- if (maybe_syntax->is_universal()) {
- if (!definition.initial_value.has_value()) {
- // let parsed initial value be empty.
- // This must be treated identically to the "default" initial value of custom properties, as defined in [css-variables].
- initial_value_maybe = nullptr;
- } else {
- // Otherwise, if syntax definition is the universal syntax definition,
- // parse initialValue as a <declaration-value>
-
- // AD-HOC: Parse this as the equivalent descriptor value in order to disallow arbitrary substitution functions.
- initial_value_maybe = parse_css_descriptor(parsing_params, AtRuleID::Property, DescriptorNameAndID::from_id(DescriptorID::InitialValue), definition.initial_value.value());
+ return value ? StyleValueFFI::rust_style_value_retain(value->rust_style_value_data()) : nullptr;
+}
- // If this fails, throw a SyntaxError and exit this algorithm.
- // Otherwise, let parsed initial value be the parsed result.
- if (!initial_value_maybe) {
- return WebIDL::SyntaxError::create("Invalid initial value"_utf16);
- }
- }
- } else if (!definition.initial_value.has_value()) {
- // Otherwise, if initialValue is not present, throw a SyntaxError and exit this algorithm.
- return WebIDL::SyntaxError::create("Initial value must be provided for non-universal syntax"_utf16);
- } else {
- // Otherwise, parse initialValue according to syntax definition.
- // NB: We don't need to worry about explicitly rejecting arbitrary substitution functions here since all
- // supported syntaxes implicitly reject them
- initial_value_maybe = Parser::parse_with_a_syntax(
- parsing_params,
- definition.initial_value.value(),
- *maybe_syntax);
+void* web_css_namespace_highlight_registry(void* document)
+{
+ return document_from_abi(document).highlight_registry().ptr();
+}
- // If this fails, throw a SyntaxError and exit this algorithm.
- if (!initial_value_maybe || initial_value_maybe->is_guaranteed_invalid()) {
- return WebIDL::SyntaxError::create("Invalid initial value"_utf16);
- }
- // Otherwise, let parsed initial value be the parsed result.
- // NB: Already done
+bool web_css_namespace_is_registered(void* document, FlatPtr name)
+{
+ return document_from_abi(document).registered_property_set().contains(Utf16FlyString { Utf16String::from_raw(name) });
+}
- // If parsed initial value is not computationally independent, throw a SyntaxError and exit this algorithm.
- if (!initial_value_maybe->is_computationally_independent())
- return WebIDL::SyntaxError::create("Initial value must be computationally independent"_utf16);
- }
+StyleValueData const* web_css_namespace_parse_initial_value_descriptor(void* document, FlatPtr value)
+{
+ Parser::ParsingParams parsing_params { document_from_abi(document) };
+ return into_rust(parse_css_descriptor(parsing_params, AtRuleID::Property, DescriptorNameAndID::from_id(DescriptorID::InitialValue), Utf16String::from_raw(value)));
+}
- // 5. Set inherit flag to the value of inherits.
- // NB: Combined with 6.
+StyleValueData const* web_css_namespace_parse_with_a_syntax(void* document, FlatPtr value, void const* syntax)
+{
+ Parser::ParsingParams parsing_params { document_from_abi(document) };
+ Parser::RustSyntaxHandle handle { Parser::ValueParserFFI::rust_syntax_retain(syntax) };
+ return into_rust(Parser::parse_with_a_syntax(parsing_params, Utf16String::from_raw(value), handle));
+}
- // 6. Let registered property be a struct with a property name of name, a syntax of syntax definition,
- // an initial value of parsed initial value, and an inherit flag of inherit flag.
+void web_css_namespace_register(void* raw_document, FlatPtr name, void const* syntax, bool inherits, StyleValueData const* initial_value)
+{
+ auto& document = document_from_abi(raw_document);
+ auto property_name = Utf16FlyString { Utf16String::from_raw(name) };
CustomPropertyRegistration registered_property {
.property_name = property_name,
- .syntax = maybe_syntax.release_value(),
- .inherit = definition.inherits,
- .initial_value = initial_value_maybe,
+ .syntax = Parser::RustSyntaxHandle { syntax },
+ .inherit = inherits,
+ .initial_value = initial_value ? RefPtr<StyleValue const> { StyleValue::adopt_rust_style_value_data(initial_value) } : nullptr,
};
- // Append registered property to property set.
- property_set.set(registered_property.property_name, move(registered_property));
+ document.registered_property_set().set(registered_property.property_name, move(registered_property));
document.did_change_custom_property_registrations(property_name);
-
- return {};
-}
-
-// https://drafts.csswg.org/css-highlight-api-1/#dom-css-highlights
-GC::Ref<HighlightRegistry> highlights(JS::VM&)
-{
- // The highlight registry is accessed via the highlights attribute of the CSS namespace, and represents all the
- // custom highlights registered for the current global object’s associated Document.
- auto& window = HTML::relevant_window(HTML::current_global_object());
- return window.associated_document().highlight_registry();
}
}
diff --git a/Libraries/LibWeb/CSS/CSS.h b/Libraries/LibWeb/CSS/CSS.h
deleted file mode 100644
index b7fa1c0b6ca..00000000000
--- a/Libraries/LibWeb/CSS/CSS.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2021-2025, Sam Atkins <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/CSS.h>
-#include <LibWeb/CSS/GeneratedCSSNumericFactoryMethods.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-// https://www.w3.org/TR/cssom-1/#namespacedef-css
-namespace Web::CSS {
-
-using PropertyDefinition = Bindings::PropertyDefinition;
-
-WEB_API WebIDL::ExceptionOr<Utf16String> escape(JS::VM&, Utf16View identifier);
-
-WEB_API bool supports(JS::VM&, Utf16FlyString const& property, Utf16View value);
-WEB_API WebIDL::ExceptionOr<bool> supports(JS::VM&, Utf16View condition_text);
-
-WEB_API WebIDL::ExceptionOr<void> register_property(DOM::Document&, PropertyDefinition const&);
-
-WEB_API GC::Ref<HighlightRegistry> highlights(JS::VM&);
-
-// NB: Numeric factory functions (https://drafts.css-houdini.org/css-typed-om-1/#numeric-factory) are generated,
-// see GenerateCSSNumericFactoryMethods.cpp
-
-}
diff --git a/Libraries/LibWeb/CSS/CSS.idl b/Libraries/LibWeb/CSS/CSS.idl
index aaf87e01878..505168e9a03 100644
--- a/Libraries/LibWeb/CSS/CSS.idl
+++ b/Libraries/LibWeb/CSS/CSS.idl
@@ -1,13 +1,13 @@
// https://drafts.csswg.org/cssom-1/#namespacedef-css
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
namespace CSS {
CSSOMString escape(CSSOMString ident);
};
// https://drafts.csswg.org/css-conditional-3/#dom-css-supports
partial namespace CSS {
- boolean supports(CSSOMString property, CSSOMString value);
- boolean supports(CSSOMString conditionText);
+ [ImplementedAs=supports_property] boolean supports(CSSOMString property, CSSOMString value);
+ [ImplementedAs=supports_condition] boolean supports(CSSOMString conditionText);
};
// https://drafts.css-houdini.org/css-properties-values-api-1/#registering-custom-properties
@@ -21,7 +21,7 @@ dictionary PropertyDefinition {
};
partial namespace CSS {
- [ImplementedInBindings] undefined registerProperty(PropertyDefinition definition);
+ undefined registerProperty(PropertyDefinition definition);
};
// https://drafts.csswg.org/css-highlight-api-1/#registration
diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rs
index 635e0bd14b6..04f3ba60c53 100644
--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs
@@ -23,6 +23,8 @@ use crate::css::dimension_units::{
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::query_parser::{css_query_evaluate_supports, rust_parse_supports_condition};
+use crate::css::parser::syntax::{SyntaxNode, rust_parse_syntax, rust_syntax_is_universal};
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,
@@ -34,7 +36,9 @@ use crate::css::property_metadata::{
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_compute::{
+ LENGTH_UNIT_CANONICAL_PX_RATIOS, LENGTH_UNIT_NAMES, rust_style_value_is_computationally_independent,
+};
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::{
@@ -1007,7 +1011,11 @@ pub fn parse_a_numeric_value(css_text: &ak::Utf16String) -> Option<RetainedStyle
if units.is_empty() {
return None;
}
- let context = ParseContext::default();
+ let random_function_index = RandomFunctionIndex::new(0);
+ let context = ParseContext {
+ random_function_index: Some(&random_function_index),
+ ..Default::default()
+ };
[
VALUE_TYPE_NUMBER,
VALUE_TYPE_PERCENTAGE,
@@ -1059,3 +1067,68 @@ pub fn zero_is_a_length(property: &ak::Utf16String, is_integer: bool) -> bool {
|| (!property_accepts_value_type(property_id, VALUE_TYPE_NUMBER)
&& !property_accepts_value_type(property_id, VALUE_TYPE_INTEGER))
}
+
+/// A syntax definition, https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings
+pub struct RegisteredSyntax(*const core::ffi::c_void);
+
+impl RegisteredSyntax {
+ /// https://drafts.css-houdini.org/css-properties-values-api/#consume-syntax-definition
+ pub fn parse(syntax: &ak::Utf16String) -> Option<Self> {
+ let units = syntax.to_utf16();
+ let parsed = rust_parse_syntax(FfiUtf16View::from_utf16(units.as_ref()), true);
+ (!parsed.is_null()).then(|| Self(parsed))
+ }
+
+ pub fn is_universal(&self) -> bool {
+ // SAFETY: The syntax tree is live.
+ rust_syntax_is_universal(unsafe { &*self.0.cast() })
+ }
+
+ pub fn as_ptr(&self) -> *const core::ffi::c_void {
+ self.0
+ }
+
+ /// Gives up the strong reference, which the caller hands over to C++.
+ pub fn into_raw(self) -> *const core::ffi::c_void {
+ let pointer = self.0;
+ core::mem::forget(self);
+ pointer
+ }
+}
+
+impl Drop for RegisteredSyntax {
+ fn drop(&mut self) {
+ // SAFETY: This owns one strong reference to the syntax tree.
+ drop(unsafe { Arc::from_raw(self.0.cast::<SyntaxNode>()) });
+ }
+}
+
+impl RetainedStyleValue {
+ /// https://drafts.css-houdini.org/css-properties-values-api/#computationally-independent
+ pub fn is_computationally_independent(&self) -> bool {
+ rust_style_value_is_computationally_independent(self.data())
+ }
+}
+
+/// Whether the text matches as a <supports-condition>, with no document to parse it for.
+pub fn supports_condition_matches(condition_text: &ak::Utf16String) -> bool {
+ let units = condition_text.to_utf16();
+ if units.is_empty() {
+ return false;
+ }
+ let random_function_index = RandomFunctionIndex::new(0);
+ let context = ParseContext {
+ random_function_index: Some(&random_function_index),
+ ..Default::default()
+ };
+ // SAFETY: The context and the text are live through the call.
+ let handle = unsafe { rust_parse_supports_condition(FfiUtf16View::from_utf16(units.as_ref()), Some(&context)) };
+ if handle.is_null() {
+ return false;
+ }
+ // SAFETY: Parsing handed over a strong reference to a live handle.
+ let handle = unsafe { Arc::from_raw(handle) };
+ // NB: This is the C++ enumerator MatchResult::True.
+ const MATCH_RESULT_TRUE: u8 = 1;
+ css_query_evaluate_supports(Some(&handle)) == MATCH_RESULT_TRUE
+}
diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmake
index 6b76c2b023b..4c110563d27 100644
--- a/Meta/CMake/libweb_generators.cmake
+++ b/Meta/CMake/libweb_generators.cmake
@@ -86,12 +86,9 @@ function (generate_css_implementation)
)
invoke_py_idl_generator(
- "GeneratedCSSNumericFactoryMethods.cpp"
"GeneratedCSSNumericFactoryMethods.idl"
"generate_libweb_css_numeric_factory_methods.py"
"${LIBWEB_INPUT_FOLDER}/CSS/Units.json"
- "CSS/GeneratedCSSNumericFactoryMethods.h"
- "CSS/GeneratedCSSNumericFactoryMethods.cpp"
"CSS/GeneratedCSSNumericFactoryMethods.idl"
arguments -j "${LIBWEB_INPUT_FOLDER}/CSS/Units.json"
)
@@ -130,7 +127,6 @@ function (generate_css_implementation)
set(CSS_GENERATED_HEADERS
"CSS/Enums.h"
- "CSS/GeneratedCSSNumericFactoryMethods.h"
"CSS/Keyword.h"
"CSS/MediaFeatureID.h"
"CSS/PropertyID.h"
diff --git a/Meta/CMake/utils.cmake b/Meta/CMake/utils.cmake
index b631e12d00e..23bbbc57863 100644
--- a/Meta/CMake/utils.cmake
+++ b/Meta/CMake/utils.cmake
@@ -172,26 +172,22 @@ function(invoke_idl_generator cpp_name idl_name generator primary_source header
set(CURRENT_LIB_GENERATED ${CURRENT_LIB_GENERATED} PARENT_SCOPE)
endfunction()
-function(invoke_py_idl_generator cpp_name idl_name script primary_source header implementation idl)
+function(invoke_py_idl_generator idl_name script primary_source idl)
cmake_parse_arguments(invoke_py_idl_generator "" "" "arguments;dependencies" ${ARGN})
set(script_path "${LADYBIRD_SOURCE_DIR}/Meta/Generators/${script}")
add_custom_command(
- OUTPUT "${header}" "${implementation}" "${idl}"
- COMMAND ${Python3_EXECUTABLE} "${script_path}" -h "${header}.tmp" -c "${implementation}.tmp" -i "${idl}.tmp" ${invoke_py_idl_generator_arguments}
- COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${header}.tmp" "${header}"
- COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${implementation}.tmp" "${implementation}"
+ OUTPUT "${idl}"
+ COMMAND ${Python3_EXECUTABLE} "${script_path}" -i "${idl}.tmp" ${invoke_py_idl_generator_arguments}
COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${idl}.tmp" "${idl}"
- COMMAND "${CMAKE_COMMAND}" -E remove "${header}.tmp" "${implementation}.tmp" "${idl}.tmp"
+ COMMAND "${CMAKE_COMMAND}" -E remove "${idl}.tmp"
VERBATIM
DEPENDS "${script_path}" ${invoke_py_idl_generator_dependencies} "${primary_source}"
)
- add_custom_target("generate_${cpp_name}" DEPENDS "${header}" "${implementation}" "${idl}")
- add_custom_target("generate_${idl_name}" DEPENDS "generate_${cpp_name}")
- add_dependencies(ladybird_codegen_accumulator "generate_${cpp_name}")
+ add_custom_target("generate_${idl_name}" DEPENDS "${idl}")
add_dependencies(ladybird_codegen_accumulator "generate_${idl_name}")
- list(APPEND CURRENT_LIB_GENERATED "${name}")
+ list(APPEND CURRENT_LIB_GENERATED "${idl_name}")
set(CURRENT_LIB_GENERATED ${CURRENT_LIB_GENERATED} PARENT_SCOPE)
endfunction()
diff --git a/Meta/Generators/generate_libweb_css_numeric_factory_methods.py b/Meta/Generators/generate_libweb_css_numeric_factory_methods.py
index 2e8fd780861..65bc990deb4 100644
--- a/Meta/Generators/generate_libweb_css_numeric_factory_methods.py
+++ b/Meta/Generators/generate_libweb_css_numeric_factory_methods.py
@@ -19,80 +19,6 @@ from Utils.utils import make_name_acceptable_cpp
from Utils.utils import snake_casify
-def write_header_file(out: TextIO, units_data: dict) -> None:
- out.write("""
-#pragma once
-
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Forward.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-// https://drafts.css-houdini.org/css-typed-om-1/#numeric-factory
-namespace Web::CSS {
-
-GC::Ref<CSSUnitValue> number(JS::VM&, WebIDL::Double value);
-GC::Ref<CSSUnitValue> percent(JS::VM&, WebIDL::Double value);
-""")
-
- for dimension_name, units in units_data.items():
- dimension_acceptable_cpp = make_name_acceptable_cpp(snake_casify(dimension_name, trim_leading_underscores=True))
- out.write(f"\n// <{dimension_acceptable_cpp}>\n")
- for unit_name in units:
- unit_acceptable_cpp = make_name_acceptable_cpp(unit_name.lower())
- out.write(f"GC::Ref<CSSUnitValue> {unit_acceptable_cpp}(JS::VM&, WebIDL::Double value);\n")
-
- out.write("""
-}
-""")
-
-
-def write_implementation_file(out: TextIO, units_data: dict) -> None:
- out.write("""
-#include <AK/Utf16FlyString.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/GeneratedCSSNumericFactoryMethods.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#numeric-factory
-inline GC::Ref<CSSUnitValue> numeric_factory(JS::VM&, WebIDL::Double value, Utf16FlyString unit)
-{
- // All of the above methods must, when called with a double value, return a new CSSUnitValue whose value internal
- // slot is set to value and whose unit internal slot is set to the name of the method as defined here.
- return CSSUnitValue::create(value, move(unit));
-}
-
-GC::Ref<CSSUnitValue> number(JS::VM& vm, WebIDL::Double value)
-{
- return numeric_factory(vm, value, "number"_utf16_fly_string);
-}
-
-GC::Ref<CSSUnitValue> percent(JS::VM& vm, WebIDL::Double value)
-{
- return numeric_factory(vm, value, "percent"_utf16_fly_string);
-}
-
-""")
-
- for dimension_name, units in units_data.items():
- dimension_acceptable_cpp = make_name_acceptable_cpp(snake_casify(dimension_name, trim_leading_underscores=True))
- out.write(f"\n// <{dimension_acceptable_cpp}>\n")
- for unit_name in units:
- unit_acceptable_cpp = make_name_acceptable_cpp(unit_name.lower())
- out.write(f"""
-GC::Ref<CSSUnitValue> {unit_acceptable_cpp}(JS::VM& vm, WebIDL::Double value)
-{{
- return numeric_factory(vm, value, "{unit_name}"_utf16_fly_string);
-}}
-""")
-
- out.write("""
-}
-""")
-
-
def write_idl_file(out: TextIO, units_data: dict) -> None:
out.write("""
partial namespace CSS {
@@ -118,15 +44,6 @@ partial namespace CSS {
def main():
parser = argparse.ArgumentParser(description="Generate CSS NumericFactoryMethods", 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 CSSNumericFactoryMethods header file to generate"
- )
- parser.add_argument(
- "-c",
- "--implementation",
- required=True,
- help="Path to the CSSNumericFactoryMethods implementation file to generate",
- )
parser.add_argument("-i", "--idl", required=True, help="Path to the CSSNumericFactoryMethods IDL file to generate")
parser.add_argument("-j", "--json", required=True, help="Path to the JSON file to read from")
args = parser.parse_args()
@@ -134,12 +51,6 @@ def main():
load_css_dimensions(args.json)
units_data = get_css_dimensions()
- with open(args.header, "w", encoding="utf-8") as output_file:
- write_header_file(output_file, units_data)
-
- with open(args.implementation, "w", encoding="utf-8") as output_file:
- write_implementation_file(output_file, units_data)
-
with open(args.idl, "w", encoding="utf-8") as output_file:
write_idl_file(output_file, units_data)
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index 4961bbc8318..7895f3db489 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -353,7 +353,7 @@ def rust_members(interface: Interface) -> RustMembers:
return rust_identifier(member_name)
if not RUST_METHOD_NAME.fullmatch(method):
fail(f"[ImplementedAs={method}] of {member_name} does not name a Rust method")
- return method
+ return rust_identifier(method)
def event_handler_attribute(attribute: Attribute) -> RustAttribute:
"""An event handler IDL attribute, which the bindings get and set on the EventTarget that the object owns. The