Skip to content

Truly independent web browser

LibWeb: Lend strings to nullable, optional and union arguments

Andreas Kling2a875adeecab
diff --git a/Libraries/LibWeb/WebIDL/AbstractOperations.h b/Libraries/LibWeb/WebIDL/AbstractOperations.h
index 0c583938a70..ddeadaec660 100644
--- a/Libraries/LibWeb/WebIDL/AbstractOperations.h
+++ b/Libraries/LibWeb/WebIDL/AbstractOperations.h
@@ -72,6 +72,63 @@ ALWAYS_INLINE JS::ThrowCompletionOr<StringArgument> to_string_argument(JS::VM& v
JS::ThrowCompletionOr<StringArgument> to_usv_string_argument(JS::VM&, JS::Value);
+// An argument of a type that has a string in it: a nullable string, or a union with a string member.
+// OPTIMIZATION: A String value lends the string it holds, as it does to a StringArgument. The argument then has that
+// string in it without a reference of its own to it, and this takes the string back out of the argument
+// before the argument is destroyed. Nothing may move the string out in between, so the argument is only
+// ever read.
+template<typename T>
+class ArgumentWithString {
+ AK_MAKE_NONCOPYABLE(ArgumentWithString);
+
+public:
+ static ArgumentWithString lending(Utf16String const& string)
+ {
+ return ArgumentWithString { T { Utf16String::adopt_raw(string.raw_identity()) }, true };
+ }
+ static ArgumentWithString lending(Utf16String const&&) = delete;
+
+ // https://webidl.spec.whatwg.org/#js-USVString
+ static ArgumentWithString lending_well_formed(Utf16String const& string)
+ {
+ if (string.utf16_view().validate()) [[likely]]
+ return lending(string);
+ return owning(T { string.to_well_formed() });
+ }
+ static ArgumentWithString lending_well_formed(Utf16String const&&) = delete;
+
+ static ArgumentWithString owning(T value) { return ArgumentWithString { move(value), false }; }
+
+ ArgumentWithString(ArgumentWithString&& other)
+ : m_value(move(other.m_value))
+ , m_lent(exchange(other.m_lent, false))
+ {
+ }
+
+ ~ArgumentWithString()
+ {
+ if (m_lent)
+ (void)move(lent_string(m_value)).into_raw();
+ }
+
+ T const& value() const { return m_value; }
+
+private:
+ ArgumentWithString(T value, bool lent)
+ : m_value(move(value))
+ , m_lent(lent)
+ {
+ }
+
+ static Utf16String& lent_string(Optional<Utf16String>& value) { return value.value(); }
+
+ template<typename... Ts>
+ static Utf16String& lent_string(Variant<Ts...>& value) { return value.template get<Utf16String>(); }
+
+ T m_value;
+ bool m_lent { false };
+};
+
template<typename T>
GC::Ref<JS::PrimitiveString> primitive_string_from_string(JS::VM& vm, T&& value)
{
diff --git a/Meta/Generators/libweb_bindings/arguments.py b/Meta/Generators/libweb_bindings/arguments.py
index 46e868a0ed8..54d1d0d2bd2 100644
--- a/Meta/Generators/libweb_bindings/arguments.py
+++ b/Meta/Generators/libweb_bindings/arguments.py
@@ -13,6 +13,7 @@ from Generators.libweb_bindings.cpp_types import cpp_value_type
from Generators.libweb_bindings.cpp_types import idl_identifier_cpp_name
from Generators.libweb_bindings.default_values import cpp_default_value_conversion
from Generators.libweb_bindings.includes import GeneratedIncludes
+from Generators.libweb_bindings.to_idl_value import argument_with_string_to_idl_value
from Generators.libweb_bindings.to_idl_value import string_argument_to_idl_value
from Generators.libweb_bindings.to_idl_value import to_idl_value
from Utils.webidl_parser import OperationParameter
@@ -57,6 +58,9 @@ def write_operation_parameter_conversions(
out.write(f" auto {argument_value_name} = vm.argument({index});\n")
+ if write_string_lending_parameter_conversion(out, parameter, argument_value_name, includes, context):
+ continue
+
if parameter.optional and parameter.default_value is None:
out.write(
f""" {operation_parameter_cpp_type(parameter, context)} {parameter_name} {{}};
@@ -77,21 +81,66 @@ def write_operation_parameter_conversions(
)
continue
- string_argument = string_argument_to_idl_value(parameter, argument_value_name, includes)
- if string_argument is not None:
- out.write(
- f""" auto {argument_value_name}_string = {string_argument};
- auto const& {parameter_name} = {argument_value_name}_string.string();
+ out.write(
+ f""" auto {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));
"""
- )
- continue
+ )
+
+def write_string_lending_parameter_conversion(
+ out: TextIO,
+ parameter: OperationParameter,
+ argument_value_name: str,
+ includes: GeneratedIncludes,
+ context: GenerationContext,
+) -> bool:
+ """Writes the conversion of a parameter that reads the string of a String value where the value holds it, and
+ returns whether the parameter is one: a string, a nullable string or a union with a string member."""
+ parameter_name = idl_identifier_cpp_name(parameter)
+ is_undefined = f"{argument_value_name}.is_undefined()"
+ has_default = parameter.optional and parameter.default_value is not None
+ is_optional_without_default = parameter.optional and parameter.default_value is None
+
+ string_argument = string_argument_to_idl_value(parameter, argument_value_name, includes)
+ if string_argument is not None and not is_optional_without_default:
+ if has_default:
+ default_value = cpp_default_value_conversion(parameter, context)
+ string_argument = f"{is_undefined} ? WebIDL::StringArgument::owned({default_value}) : {string_argument}"
out.write(
- f""" auto {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));
+ f""" auto {argument_value_name}_string = {string_argument};
+ auto const& {parameter_name} = {argument_value_name}_string.string();
"""
)
+ return True
+
+ if is_optional_without_default:
+ cpp_type_name = operation_parameter_cpp_type(parameter, context)
+ else:
+ cpp_type_name = cpp_value_type(parameter, context)
+
+ def owned_value() -> str:
+ value = f"TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}))"
+ if is_optional_without_default:
+ return f"{is_undefined} ? {cpp_type_name} {{}} : {cpp_type_name} {{ {value} }}"
+ if has_default:
+ default_value = cpp_default_value_conversion(parameter, context)
+ return f"{is_undefined} ? {cpp_type_name} {{ {default_value} }} : {cpp_type_name} {{ {value} }}"
+ return value
+
+ argument = argument_with_string_to_idl_value(
+ parameter, cpp_type_name, argument_value_name, owned_value, includes, context
+ )
+ if argument is None:
+ return False
+ out.write(
+ f""" auto {argument_value_name}_argument = {argument};
+ auto const& {parameter_name} = {argument_value_name}_argument.value();
+
+"""
+ )
+ return True
def write_variadic_operation_parameter_conversion(
diff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.py
index be532fc5179..03029e20d43 100644
--- a/Meta/Generators/libweb_bindings/attributes.py
+++ b/Meta/Generators/libweb_bindings/attributes.py
@@ -8,6 +8,7 @@ from io import StringIO
from typing import TextIO
from Generators.libweb_bindings.context import GenerationContext
+from Generators.libweb_bindings.cpp_types import cpp_type
from Generators.libweb_bindings.cpp_types import cpp_type_for_idl_type_details
from Generators.libweb_bindings.cpp_types import fully_qualified_name_for_interface
from Generators.libweb_bindings.cpp_types import idl_identifier_cpp_name
@@ -24,6 +25,7 @@ from Generators.libweb_bindings.security_checks import on_the_window
from Generators.libweb_bindings.security_checks import perform_a_security_check
from Generators.libweb_bindings.security_checks import the_remote_window
from Generators.libweb_bindings.security_checks import window_member_is_cross_origin_accessible
+from Generators.libweb_bindings.to_idl_value import argument_with_string_to_idl_value
from Generators.libweb_bindings.to_idl_value import string_argument_to_idl_value
from Generators.libweb_bindings.to_idl_value import to_idl_value
from Generators.libweb_bindings.to_js_value import to_javascript_value
@@ -917,6 +919,24 @@ def write_attribute_setter(
f""" auto V_string = {string_argument};
auto const& idl_value = V_string.string();
+"""
+ )
+ elif (
+ argument := argument_with_string_to_idl_value(
+ attribute,
+ cpp_type(attribute, context),
+ "V",
+ lambda: (
+ f"TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {to_idl_value(attribute, 'V', includes, context)}; }}))"
+ ),
+ includes,
+ context,
+ )
+ ) is not None:
+ out.write(
+ f""" auto V_argument = {argument};
+ auto const& idl_value = V_argument.value();
+
"""
)
else:
diff --git a/Meta/Generators/libweb_bindings/to_idl_value.py b/Meta/Generators/libweb_bindings/to_idl_value.py
index e92d0fad06c..7071d5150e1 100644
--- a/Meta/Generators/libweb_bindings/to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/to_idl_value.py
@@ -4,6 +4,7 @@
from dataclasses import dataclass
from dataclasses import field
+from typing import Callable
from typing import List
from typing import NoReturn
from typing import Optional
@@ -1607,6 +1608,57 @@ def string_argument_to_idl_value(
return f"TRY({conversion})"
+def argument_with_string_to_idl_value(
+ member: DictionaryMemberOrAttribute,
+ cpp_type_name: str,
+ value_name: str,
+ owned_value: Callable[[], str],
+ includes: GeneratedIncludes,
+ context: GenerationContext,
+) -> Optional[str]:
+ """The conversion of a value to a WebIDL::ArgumentWithString of cpp_type_name, which lends the string of a String
+ value rather than taking a reference to it, and holds what owned_value returns for any other value. None, without
+ calling owned_value, where a String value does not convert to the string it holds: where the member is not a
+ nullable string or a union with a string member."""
+ idl_type = member.type
+ if isinstance(idl_type, IDLParameterizedType):
+ return None
+
+ if isinstance(idl_type, IDLUnionType):
+ # https://webidl.spec.whatwg.org/#es-union
+ # NB: None of the steps before the one that converts to the string type of the union takes a String value,
+ # except for the one that matches it against the values of an enumeration.
+ types = collect_union_types(idl_type.flattened_member_types(), context)
+ if types.string_type is None or types.enumeration_types:
+ return None
+ string_type = types.string_type
+ if cpp_type_name != union_type_to_variant(idl_type, context):
+ return None
+ if cpp_type_for_idl_type(string_type, context) != "Utf16String":
+ return None
+ else:
+ string_type = idl_type
+ extended_attributes = {**idl_type.extended_attributes, **getattr(member, "extended_attributes", {})}
+ if not is_string_type(idl_type.name) or cpp_type_name != "Optional<Utf16String>":
+ return None
+ if cpp_type_name_for_string(idl_type.name, extended_attributes) != "Utf16String":
+ return None
+
+ if string_type.name in ("CSSOMString", "DOMString"):
+ lending = "lending"
+ elif string_type.name == "USVString":
+ lending = "lending_well_formed"
+ else:
+ return None
+
+ includes.add("LibJS/Runtime/Value.h")
+ includes.add("LibWeb/WebIDL/AbstractOperations.h")
+ holder = f"WebIDL::ArgumentWithString<{cpp_type_name}>"
+ return f"""{value_name}.is_string()
+ ? {holder}::{lending}({value_name}.as_string().utf16_string())
+ : {holder}::owning({owned_value()})"""
+
+
def type_check_idl_value(
idl_type: IDLType,
value_name: str,
diff --git a/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt b/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt
index cfba9576ff5..cd34fa87bbe 100644
--- a/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt
+++ b/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt
@@ -9,4 +9,18 @@ id: id-5
well-formed-6=value-7&lone-surrogate-%EF%BF%BD-8=%EF%BF%BD-9
color: red
color after null: ""
+textContent: text-content-content-10
+textContent of a number: 7
+textContent of null: ""
+data-observed: null -> attribute-value-value-11
+data-observed: attribute-value-value-11 -> 8
+innerHTML: <b>inner-html-html-12</b>
+innerHTML of null: ""
+comment: "", "comment-13", "9"
+URL: https://example.com/base/path-14
+URL of a lone surrogate: https://example.com/%EF%BF%BD-16
+has: true, true, false
+RangeError: thrown by toString of a nullable string
RangeError: thrown by toString
+RangeError: thrown by toString of an optional string
+RangeError: thrown by toString of a union
diff --git a/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html b/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html
index fbc1e3d6d5d..85af1745ec5 100644
--- a/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html
+++ b/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html
@@ -69,10 +69,53 @@
element.style.setProperty("color", null);
println(`color after null: "${element.style.color}"`);
+ // Nullable strings, optional strings and unions with a string member read the string the same way.
+ element.textContent = "text" + "-content".repeat(2) + suffix();
+ println(`textContent: ${element.textContent}`);
+ element.textContent = 7;
+ println(`textContent of a number: ${element.textContent}`);
+ element.textContent = null;
+ println(`textContent of null: "${element.textContent}"`);
+
+ customElements.define("string-argument-observer", class extends HTMLElement {
+ static observedAttributes = ["data-observed"];
+ attributeChangedCallback(name, oldValue, newValue) {
+ internals.gc();
+ println(`${name}: ${oldValue} -> ${newValue}`);
+ }
+ });
+ const observer = document.createElement("string-argument-observer");
+ observer.setAttribute("data-observed", "attribute" + "-value".repeat(2) + suffix());
+ observer.setAttribute("data-observed", 8);
+ observer.innerHTML = "<b>inner" + "-html".repeat(2) + suffix() + "</b>";
+ println(`innerHTML: ${observer.innerHTML}`);
+ observer.innerHTML = null;
+ println(`innerHTML of null: "${observer.innerHTML}"`);
+
+ println(`comment: "${new Comment().data}", "${new Comment("comment" + suffix()).data}", "${new Comment(9).data}"`);
+ println(`URL: ${new URL("path" + suffix(), "https://example.com/base/" + suffix())}`);
+ println(`URL of a lone surrogate: ${new URL("https://example.com/\ud800" + suffix())}`);
+ println(`has: ${parameters.has("well-formed-6")}, ${parameters.has("well-formed-6", "value" + "-7")}, ${parameters.has("well-formed-6", "other" + suffix())}`);
+
+ try {
+ element.textContent = { toString() { throw new RangeError("thrown by toString of a nullable string"); } };
+ } catch (error) {
+ println(`${error.name}: ${error.message}`);
+ }
try {
element.id = { toString() { throw new RangeError("thrown by toString"); } };
} catch (error) {
println(`${error.name}: ${error.message}`);
}
+ try {
+ new Comment({ toString() { throw new RangeError("thrown by toString of an optional string"); } });
+ } catch (error) {
+ println(`${error.name}: ${error.message}`);
+ }
+ try {
+ element.innerHTML = { toString() { throw new RangeError("thrown by toString of a union"); } };
+ } catch (error) {
+ println(`${error.name}: ${error.message}`);
+ }
});
</script>