Skip to content

Truly independent web browser

Meta+LibWeb: Define constants and setters in the Rust bindings

Aliaksandr Kalenikbb27f068308e
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 3e42934f9a9..9a4d064777c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -20,6 +20,7 @@ use core::ffi::c_void;
use core::ops::Deref;
use core::ptr::NonNull;
+use ak::Utf16FlyString;
use libjs_rust::api::{
Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject, Gc, HostObject,
JSHostClass, Object, PrimitiveString, PropertyAttributes, PropertyKey, RawNativeFunctionPointer, Realm, Throw,
@@ -359,6 +360,31 @@ pub(crate) fn define_operation(
);
}
+/// Records a regular attribute or operation that the interface does not implement on the interface prototype object,
+/// so that a read of it is reported, without the property being there for script.
+pub(crate) fn define_unimplemented_property(vm: &Vm, prototype: Gc<Object>, name: &str) {
+ prototype.define_unimplemented_property(vm, Utf16FlyString::from_utf8(name));
+}
+
+/// Defines the constants of an interface on its interface object or its interface prototype object,
+/// https://webidl.spec.whatwg.org/#define-the-constants
+pub(crate) fn define_constants(vm: &Vm, target: Gc<Object>, constants: &[(&str, f64)]) {
+ // 1. For each constant const that is a member of definition:
+ for (identifier, value) in constants {
+ // 2. Let value be the result of converting const's IDL value to a JavaScript value.
+ // 3. Let desc be the PropertyDescriptor{[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false,
+ // [[Value]]: value}.
+ // 4. Let id be const's identifier.
+ // 5. Perform ! DefinePropertyOrThrow(target, id, desc).
+ target.define_direct_property(
+ vm,
+ &PropertyKey::from_utf8(identifier),
+ Value::from_f64(*value),
+ PropertyAttributes::new(Attribute::ENUMERABLE),
+ );
+ }
+}
+
/// Defines @@toStringTag on the interface prototype object, https://webidl.spec.whatwg.org/#es-interface-prototype-object
pub(crate) fn define_to_string_tag(vm: &Vm, prototype: Gc<Object>, name: &str) {
prototype.define_direct_property(
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index fdd68f5a6e2..6041f8b479d 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -23,6 +23,7 @@ from typing import TextIO
from Generators.libweb_bindings.context import GenerationContext
from Generators.libweb_bindings.includes import GeneratedIncludes
+from Generators.libweb_bindings.rust_members import RustAttribute
from Generators.libweb_bindings.rust_members import RustConstructor
from Generators.libweb_bindings.rust_members import RustMembers
from Generators.libweb_bindings.rust_members import RustOperation
@@ -52,7 +53,14 @@ from Utils.webidl_parser import Module
from Utils.webidl_parser import OperationParameter
# The extended attributes of an interface that the Rust bindings handle.
-SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {"Exposed", "ImplementedIn", "SecureContext", "Experimental"}
+SUPPORTED_INTERFACE_EXTENDED_ATTRIBUTES = {
+ "Experimental",
+ "Exposed",
+ "ImplementedIn",
+ # NB: The C++ bindings only leave the interface object of such an interface off the global object.
+ "LegacyNoInterfaceObject",
+ "SecureContext",
+}
def rust_module_name(interface: Interface) -> str:
@@ -324,10 +332,15 @@ def implementation_method_signatures(
signatures.append(f"fn {constructor.method}(cx: &mut CallContext{parameters}) -> WebIdlResult<Self>")
for attribute in members.attributes:
what = f"{interface.name}.{attribute.attribute.name}"
+ attribute_type = rust_type(attribute.attribute.type, context, what)
signatures.append(
- f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> "
- f"WebIdlResult<{rust_type(attribute.attribute.type, context, what)}>"
+ f"fn {attribute.getter_method}(&self, cx: &mut CallContext) -> WebIdlResult<{attribute_type}>"
)
+ if attribute.setter_method is not None:
+ signatures.append(
+ f"fn {attribute.setter_method}(&self, cx: &mut CallContext, value: {attribute_type}) -> "
+ "WebIdlResult<()>"
+ )
for operation_set in members.operation_sets:
for overload in operation_set.overloads:
what = f"{interface.name}.{operation_set.name}()"
@@ -368,10 +381,10 @@ def write_rust_interface(
to_unsigned_long_long, to_usv_string,
}};
use crate::bindings::interface::{{
- Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute,
- define_interface_object_properties, define_operation, define_to_string_tag, entry_point_arguments,
- implementation_of, prototype_from_new_target, rejected_promise, set_interface_prototype_object_prototype,
- this_object, to_interface,
+ Interface, Ref, Wrapped, construct_arguments, construct_wrapper, define_attribute, define_constants,
+ define_interface_object_properties, define_operation, define_to_string_tag, define_unimplemented_property,
+ entry_point_arguments, implementation_of, prototype_from_new_target, rejected_promise,
+ set_interface_prototype_object_prototype, this_object, to_interface,
}};
use crate::bindings::{{CallContext, WebIdlResult}};
@@ -407,6 +420,17 @@ def write_rust_interface(
)
defined_property_names: List[str] = []
+ recorded_unimplemented_names: List[str] = []
+
+ if members.constants:
+ constants = "".join(f' ("{constant.name}", {constant.value}.0),\n' for constant in members.constants)
+ out.write(
+ f"""
+ /// The constants of the interface, which its interface object and its interface prototype object both have.
+ static CONSTANTS: [(&str, f64); {len(members.constants)}] = [
+{constants} ];
+"""
+ )
for attribute in members.attributes:
name = attribute.attribute.name
@@ -421,6 +445,8 @@ def write_rust_interface(
}}
"""
)
+ if attribute.setter_method is not None:
+ write_rust_attribute_setter(out, context, interface, attribute)
for operation_set in members.operation_sets:
write_rust_operation(
@@ -445,10 +471,17 @@ def write_rust_interface(
set_interface_prototype_object_prototype(vm, realm, prototype);
"""
)
- for attribute in members.attributes:
+ # NB: The properties are defined in the order of the C++ bindings: the attributes, the operations, the operations
+ # that are not implemented, then the constants.
+ for attribute in members.attributes_in_order:
+ if isinstance(attribute, str):
+ out.write(f' define_unimplemented_property(vm, prototype, "{attribute}");\n')
+ recorded_unimplemented_names.append(attribute)
+ continue
name = attribute.attribute.name
- getter = attribute.getter_function
- out.write(f' define_attribute(vm, realm, prototype, "{name}", raw_native!({getter}), None);\n')
+ getter = f"raw_native!({attribute.getter_function})"
+ setter = "None" if attribute.setter_method is None else f"raw_native!({attribute.setter_function})"
+ out.write(f' define_attribute(vm, realm, prototype, "{name}", {getter}, {setter});\n')
defined_property_names.append(name)
for operation_set in members.operation_sets:
name = operation_set.name
@@ -456,11 +489,18 @@ def write_rust_interface(
length = operation_set.length
out.write(f' define_operation(vm, realm, prototype, "{name}", raw_native!({function}), {length});\n')
defined_property_names.append(name)
+ for name in members.unimplemented_operation_names:
+ out.write(f' define_unimplemented_property(vm, prototype, "{name}");\n')
+ recorded_unimplemented_names.append(name)
+ if members.constants:
+ out.write(" define_constants(vm, prototype, &CONSTANTS);\n")
+ defined_property_names.extend(constant.name for constant in members.constants)
# NB: A member that rust_members() accepts and nothing above defines would be missing from the prototype without
# any error, so the two are compared.
assert defined_property_names == members.property_names(), (
f"{interface.name}: the bindings define {defined_property_names}, its members are {members.property_names()}"
)
+ assert recorded_unimplemented_names == members.unimplemented_property_names()
out.write(
f""" define_to_string_tag(vm, prototype, "{interface.namespaced_name}");
}}
@@ -479,9 +519,11 @@ def write_rust_interface(
// SAFETY: The caller passes live pointers.
let (vm, realm, constructor) = unsafe {{ entry_point_arguments(vm, realm, constructor) }};
define_interface_object_properties(vm, realm, constructor, "{interface.name}", {members.constructor_length}, INTERFACE_NAME);
- }}
"""
)
+ if members.constants:
+ out.write(" define_constants(vm, constructor, &CONSTANTS);\n")
+ out.write(" }\n")
for constructor in members.constructors:
write_rust_constructor(out, context, interface, constructor)
@@ -511,6 +553,32 @@ def write_rust_interface(
out.write("}\n")
+def write_rust_attribute_setter(
+ out: TextIO, context: GenerationContext, interface: Interface, attribute: RustAttribute
+) -> None:
+ """The native function of the setter of an attribute, in the order of the C++ bindings: the value is read before
+ the this value is checked, and a missing value is undefined instead of an error."""
+ name = attribute.attribute.name
+ what = f"{interface.name}.{name}"
+ conversion = rust_to_idl_value(
+ attribute.attribute.type, attribute.attribute.extended_attributes, "value", name, context, what
+ )
+ out.write(
+ f"""
+ fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{
+ let value = vm.argument(0);
+ let (implementation, mut cx) = this_implementation(vm)?;
+ let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());
+ let idl_value = {conversion}?;
+ drop(type_error_realm_scope);
+ Implementation::{attribute.setter_method}(&implementation, &mut cx, idl_value)
+ .map_err(|exception| exception.throw(vm))?;
+ Ok(Value::UNDEFINED)
+ }}
+"""
+ )
+
+
def write_rust_operation(
out: TextIO, context: GenerationContext, interface: Interface, name: str, function: str, overload: RustOperation
) -> None:
diff --git a/Meta/Generators/libweb_bindings/rust_members.py b/Meta/Generators/libweb_bindings/rust_members.py
index 1935025e572..a0db833e69c 100644
--- a/Meta/Generators/libweb_bindings/rust_members.py
+++ b/Meta/Generators/libweb_bindings/rust_members.py
@@ -12,12 +12,16 @@ import re
from dataclasses import dataclass
from dataclasses import field
from typing import List
+from typing import Optional
+from typing import Union
from Generators.libweb_bindings.overload_resolution import operation_length
from Generators.libweb_bindings.overload_resolution import operation_overload_sets
from Generators.libweb_bindings.overload_resolution import parameter_list_length
from Generators.libweb_bindings.rust_names import rust_identifier
+from Generators.libweb_bindings.rust_types import INTEGER_TYPES
from Generators.libweb_bindings.rust_types import UnsupportedByRustBindings
+from Generators.libweb_bindings.rust_types import idl_integer_value
from Utils.webidl_parser import Attribute
from Utils.webidl_parser import Constructor
from Utils.webidl_parser import Interface
@@ -26,8 +30,8 @@ from Utils.webidl_parser import Operation
RUST_METHOD_NAME = re.compile(r"[a-z][a-z0-9_]*")
# The extended attributes of the members of an interface that the Rust bindings handle.
-SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}
-SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"NewObject", "SameObject"}
+SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES = {"FIXME", "ImplementedAs", "NewObject", "SameObject"}
+SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES = {"FIXME", "ImplementedAs", "NewObject", "SameObject"}
def generated_function_stem(method: str) -> str:
@@ -41,12 +45,19 @@ class RustAttribute:
attribute: Attribute
# The method of the implementation that the getter calls.
getter_method: str
+ # The method of the implementation that the setter calls, for an attribute that is not read only.
+ setter_method: Optional[str]
@property
def getter_function(self) -> str:
"""The generated native function of the getter."""
return f"{generated_function_stem(self.getter_method)}_getter"
+ @property
+ def setter_function(self) -> str:
+ """The generated native function of the setter."""
+ return f"{generated_function_stem(self.getter_method)}_setter"
+
@dataclass
class RustOperation:
@@ -76,6 +87,12 @@ class RustOperationSet:
return min(overload.length for overload in self.overloads)
+@dataclass
+class RustConstant:
+ name: str
+ value: int
+
+
@dataclass
class RustConstructor:
constructor: Constructor
@@ -93,9 +110,16 @@ class RustConstructor:
@dataclass
class RustMembers:
+ # The attributes and the operations that the implementation has methods for.
attributes: List[RustAttribute] = field(default_factory=list)
operation_sets: List[RustOperationSet] = field(default_factory=list)
constructors: List[RustConstructor] = field(default_factory=list)
+ constants: List[RustConstant] = field(default_factory=list)
+ # The regular attributes in the order of the IDL, as the prototype defines them: an attribute of `attributes`, or
+ # the identifier of one marked [FIXME].
+ attributes_in_order: List[Union[RustAttribute, str]] = field(default_factory=list)
+ # The identifiers of the operations marked [FIXME] that have no implemented overload, each once.
+ unimplemented_operation_names: List[str] = field(default_factory=list)
@property
def constructor_length(self) -> int:
@@ -104,9 +128,17 @@ class RustMembers:
return min(constructor.length for constructor in self.constructors)
def property_names(self) -> List[str]:
- """The identifiers of the members that the interface prototype object has a property for."""
+ """The identifiers of the members that the interface prototype object has a property for, in the order of
+ their definition."""
names = [attribute.attribute.name for attribute in self.attributes]
names.extend(operation_set.name for operation_set in self.operation_sets)
+ names.extend(constant.name for constant in self.constants)
+ return names
+
+ def unimplemented_property_names(self) -> List[str]:
+ """The identifiers of the members that the interface prototype object records as not implemented."""
+ names = [attribute for attribute in self.attributes_in_order if isinstance(attribute, str)]
+ names.extend(self.unimplemented_operation_names)
return names
@@ -121,6 +153,15 @@ def rust_members(interface: Interface) -> RustMembers:
if unsupported:
fail(f"the Rust bindings do not handle the extended attributes {sorted(unsupported)} of {member_name}")
+ def method_of(member_name: str, extended_attributes: dict) -> str:
+ """The method of the implementation for a member, which the IDL can name with [ImplementedAs]."""
+ method = extended_attributes.get("ImplementedAs")
+ if method is None:
+ 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
+
special_operations = [
interface.named_property_getter,
interface.indexed_property_getter,
@@ -132,8 +173,8 @@ def rust_members(interface: Interface) -> RustMembers:
fail("it has special operations")
if interface.iterable or interface.async_iterable or interface.maplike or interface.setlike:
fail("it is iterable or a maplike or setlike")
- if interface.static_attributes or interface.static_operations or interface.constants:
- fail("it has static members or constants")
+ if interface.static_attributes or interface.static_operations:
+ fail("it has static members")
members = RustMembers()
@@ -160,24 +201,52 @@ def rust_members(interface: Interface) -> RustMembers:
for constructor in interface.constructors:
members.constructors.append(RustConstructor(constructor, "construct", "construct"))
- # NB: operation_overload_sets() leaves out the operations marked [FIXME], which C++ defines as unimplemented.
- for operation in interface.regular_operations:
+ for attribute in interface.regular_attributes:
check_extended_attributes(
- operation.name, operation.extended_attributes, SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES
+ attribute.name, attribute.extended_attributes, SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES
)
+ if "FIXME" in attribute.extended_attributes:
+ members.attributes_in_order.append(attribute.name)
+ continue
+ getter_method = method_of(attribute.name, attribute.extended_attributes)
+ setter_method = None if attribute.readonly else f"set_{generated_function_stem(getter_method)}"
+ rust_attribute = RustAttribute(attribute, getter_method, setter_method)
+ members.attributes.append(rust_attribute)
+ members.attributes_in_order.append(rust_attribute)
- for attribute in interface.regular_attributes:
+ for operation in interface.regular_operations:
check_extended_attributes(
- attribute.name, attribute.extended_attributes, SUPPORTED_ATTRIBUTE_EXTENDED_ATTRIBUTES
+ operation.name, operation.extended_attributes, SUPPORTED_OPERATION_EXTENDED_ATTRIBUTES
)
- if not attribute.readonly:
- fail(f"its attribute {attribute.name} is not readonly")
- members.attributes.append(RustAttribute(attribute, rust_identifier(attribute.name)))
- for name, operations in operation_overload_sets(interface).items():
+ # NB: operation_overload_sets() leaves out the operations marked [FIXME], which the prototype records as not
+ # implemented unless another overload of theirs is.
+ overload_sets = operation_overload_sets(interface)
+ for name, operations in overload_sets.items():
if len(operations) > 1:
fail(f"its operation {name} is overloaded")
- overloads = [RustOperation(operation, rust_identifier(name)) for operation in operations]
+ overloads = [
+ RustOperation(operation, method_of(name, operation.extended_attributes)) for operation in operations
+ ]
members.operation_sets.append(RustOperationSet(name, overloads))
+ for operation in interface.regular_operations:
+ is_unimplemented = "FIXME" in operation.extended_attributes and operation.name not in overload_sets
+ if is_unimplemented and operation.name not in members.unimplemented_operation_names:
+ members.unimplemented_operation_names.append(operation.name)
+
+ for constant in interface.constants:
+ value = idl_integer_value(constant.value, constant.type.name) if constant.type.name in INTEGER_TYPES else None
+ if value is None:
+ fail(f"its constant {constant.name} is not an integer of the type {constant.type}")
+ else:
+ members.constants.append(RustConstant(constant.name, value))
+
+ methods = [attribute.getter_method for attribute in members.attributes]
+ methods.extend(attribute.setter_method for attribute in members.attributes if attribute.setter_method is not None)
+ methods.extend(overload.method for operation_set in members.operation_sets for overload in operation_set.overloads)
+ methods.extend(constructor.method for constructor in members.constructors)
+ repeated_methods = sorted({method for method in methods if methods.count(method) > 1})
+ if repeated_methods:
+ fail(f"more than one of its members has the Rust method {repeated_methods}")
return members
diff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.py
index fad96b54f9b..9f5f9852691 100644
--- a/Meta/Generators/libweb_bindings/rust_types.py
+++ b/Meta/Generators/libweb_bindings/rust_types.py
@@ -57,9 +57,9 @@ class UnsupportedByRustBindings(Exception):
pass
-def rust_integer_literal(literal: Optional[str], idl_type_name: str) -> Optional[str]:
- """The Rust literal of the value of an integer token of the IDL, or None if the token is not one or its value is
- not one of the integer type."""
+def idl_integer_value(literal: Optional[str], idl_type_name: str) -> Optional[int]:
+ """The value of an integer token of the IDL, or None if the token is not one or its value is not one of the
+ integer type."""
if literal is None or not INTEGER_LITERAL.fullmatch(literal):
return None
digits = literal.removeprefix("-")
@@ -78,7 +78,13 @@ def rust_integer_literal(literal: Optional[str], idl_type_name: str) -> Optional
lowest, highest = -(2 ** (bits - 1)), 2 ** (bits - 1) - 1
if not lowest <= integer <= highest:
return None
- return f"{integer}_{rust_integer_type}"
+ return integer
+
+
+def rust_integer_literal(literal: Optional[str], idl_type_name: str) -> Optional[str]:
+ """The Rust literal of the value of an integer token of the IDL, if it is a value of the integer type."""
+ integer = idl_integer_value(literal, idl_type_name)
+ return None if integer is None else f"{integer}_{INTEGER_TYPES[idl_type_name]}"
def is_implemented_in_rust(interface: Optional[Interface]) -> bool:
diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.py
index 7779c524116..8a8d28c3072 100644
--- a/Meta/Generators/libweb_bindings/rust_usage.py
+++ b/Meta/Generators/libweb_bindings/rust_usage.py
@@ -91,7 +91,8 @@ class DefinitionUsage:
continue
members = rust_members(interface)
for attribute in members.attributes:
- self._name_for_rust(attribute.attribute.type, from_js=False, to_js=True)
+ has_setter = attribute.setter_method is not None
+ self._name_for_rust(attribute.attribute.type, from_js=has_setter, to_js=True)
for operation_set in members.operation_sets:
for overload in operation_set.overloads:
self._name_for_rust(overload.operation.return_type, from_js=False, to_js=True)