Truly independent web browser
LibWeb: Evaluate XPath expressions on the DOM
Andreas Klingd36b5bf6e3ee
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 6d5f43b1fc6..563bd03f39b 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -1001,7 +1001,7 @@ target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)-target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibWebRTCClient LibXml2::LibXml2)+target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibWebRTCClient)# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but# the actual GL entry points live in the Compositor. Copy only ANGLE's compilediff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex bfcc4c34b78..64e43e562f0 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -11791,7 +11791,7 @@ WebIDL::ExceptionOr<GC::Ref<XPath::XPathExpression>> Document::create_expressionWebIDL::ExceptionOr<GC::Ref<XPath::XPathResult>> Document::evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPath::XPathNSResolver> resolver, WebIDL::UnsignedShort type, GC::Ptr<XPath::XPathResult> result){- return XPath::throw_evaluation_error_if_needed(XPath::evaluate(expression, context_node, resolver, type, result));+ return XPath::evaluate(expression, context_node, resolver, type, result);}GC::Ref<DOM::Node> Document::create_ns_resolver(GC::Ref<DOM::Node> node_resolver)diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 364bef2440a..b7e04504252 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -76,7 +76,6 @@#include <LibWeb/SVG/SVGUseElement.h>#include <LibWeb/TrustedTypes/TrustedHTML.h>#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/XPath/EvaluateResult.h>#include <LibWebCommon/CSS/PreferredColorScheme.h>#include <LibWebCommon/Fullscreen/FullscreenRequestType.h>#include <LibWebCommon/HTML/CrossOrigin/OpenerPolicy.h>diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cppindex 4dd86401a1f..bd58cb281c9 100644--- a/Libraries/LibWeb/DOM/Node.cpp+++ b/Libraries/LibWeb/DOM/Node.cpp@@ -2749,6 +2749,11 @@ void Node::removed_from(IsSubtreeRoot, Node* old_parent, Node&)m_is_connected = false;m_in_editable_subtree = false;+ // The nodes of a shadow tree count the versions of their tree on the document while they are connected, and on+ // their shadow root otherwise. The shadow root has missed every change made in the meantime, so it starts over.+ if (auto* shadow_root = as_if<ShadowRoot>(*this))+ shadow_root->m_dom_tree_version = shadow_root->m_character_data_version = ++s_last_tree_version;+// https://html.spec.whatwg.org/multipage/infrastructure.html#dom-trees:concept-node-remove-ext// 1. Let document be removedNode's node document.auto& document = this->document();diff --git a/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp b/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cppindex b06544a629a..b6ede0d9f39 100644--- a/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp@@ -97,21 +97,23 @@ static ErrorOr<void, Error> locate_nodes_using_xpath(NodeList const& context_nod// DOMException, return error with error code invalid selector; otherwise, if this throws any other exception// return error with error code unknown error.auto evaluate_result = XPath::evaluate(Utf16String::from_utf8(selector), context_node, nullptr, XPath::XPathResult::ORDERED_NODE_SNAPSHOT_TYPE, nullptr);- if (evaluate_result.has<XPath::EvaluationError>()) {- if (evaluate_result.get<XPath::EvaluationError>() == XPath::EvaluationError::InvalidExpression)+ if (evaluate_result.is_exception()) {+ auto exception = evaluate_result.exception();+ if (auto* dom_exception = exception.get_pointer<GC::Ref<WebIDL::DOMException>>(); dom_exception && (*dom_exception)->name() == "SyntaxError"sv)return invalid_selector("The selector is not a valid XPath expression"sv);return Error::from_code(ErrorCode::UnknownError, "Unable to evaluate the XPath expression"sv);}- auto result = evaluate_result.get<GC::Ref<XPath::XPathResult>>();+ auto result = evaluate_result.release_value();// 2. Let index be 0.// 3. Let length be the result of getting the snapshotLength property from evaluate result.- auto length = result->snapshot_length();+ auto nodes = result->nodes();+ auto length = nodes.size();// 4. Repeat, while index is less than length:- for (u32 index = 0; index < length; ++index) {+ for (size_t index = 0; index < length; ++index) {// 1. Let node be the result of calling snapshotItem with evaluate result as this and index as the argument.- auto node = result->snapshot_item(static_cast<int>(index));+ auto node = nodes[index];if (!node)continue;diff --git a/Libraries/LibWeb/XPath/EvaluateResult.h b/Libraries/LibWeb/XPath/EvaluateResult.hdeleted file mode 100644index 53ee22b341f..00000000000--- a/Libraries/LibWeb/XPath/EvaluateResult.h+++ /dev/null@@ -1,23 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Variant.h>-#include <LibGC/Forward.h>--namespace Web::XPath {--class XPathResult;--enum class EvaluationError {- InvalidExpression,- EvaluationFailed,-};--using EvaluateResult = Variant<GC::Ref<XPathResult>, EvaluationError>;--}diff --git a/Libraries/LibWeb/XPath/XPath.cpp b/Libraries/LibWeb/XPath/XPath.cppindex bdf89f6b448..ed976e1bbec 100644--- a/Libraries/LibWeb/XPath/XPath.cpp+++ b/Libraries/LibWeb/XPath/XPath.cpp@@ -1,235 +1,1125 @@/** Copyright (c) 2025, Johannes Gustafsson <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Format.h>+#include <AK/HashTable.h>+#include <AK/QuickSort.h>+#include <AK/StringConversions.h>+#include <AK/Utf16StringBuilder.h>#include <LibGC/Heap.h>+#include <LibGC/RootHashTable.h>+#include <LibGC/RootVector.h>+#include <LibJS/Runtime/PrimitiveString.h>+#include <LibJS/Runtime/Value.h>#include <LibWeb/DOM/Attr.h>-#include <LibWeb/DOM/CDATASection.h>-#include <LibWeb/DOM/Comment.h>+#include <LibWeb/DOM/CharacterData.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/DocumentFragment.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/DOM/NamedNodeMap.h>#include <LibWeb/DOM/Node.h>+#include <LibWeb/DOM/ParentNode.h>#include <LibWeb/DOM/ProcessingInstruction.h>-#include <LibWeb/DOM/Text.h>+#include <LibWeb/HTML/AttributeNames.h>+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>+#include <LibWeb/Namespace.h>+#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/DOMException.h>-#include <LibWebCommon/DOM/NodeType.h>--#include <libxml/parser.h>-#include <libxml/tree.h>-#include <libxml/valid.h>-#include <libxml/xmlstring.h>-#include <libxml/xpath.h>+#include <LibXML/XPath/Program.h>+#include <math.h>#include "XPath.h"+#include "XPathExpression.h"+#include "XPathNSResolver.h"+#include "XPathResult.h"namespace Web::XPath {-static xmlNodePtr mirror_node(xmlDocPtr doc, DOM::Node const& node)+namespace FFI = XML::FFI;++// A set of nodes without duplicates. If it isn't sorted, its order means nothing.+struct NodeSet {+ GC::RootVector<GC::Ref<DOM::Node>> nodes;+ bool is_in_document_order { true };+};++using Value = Variant<bool, double, Utf16String, NodeSet>;++struct Context {+ GC::Ref<DOM::Node> node;+ size_t position { 1 };+ size_t size { 1 };+};++// https://www.w3.org/TR/xml/#NT-S+// Not ASCII whitespace as HTML has it: a form feed is no white space in XML.+static constexpr auto XML_WHITESPACE = u" \t\n\r"sv;++// An attribute isn't a child of its element, but its element is its parent.+static DOM::Node* parent_of(DOM::Node& node){- switch (node.type()) {- case DOM::NodeType::INVALID: {- return nullptr;+ if (auto* attribute = as_if<DOM::Attr>(node))+ return attribute->owner_element();+ return node.parent();+}++static DOM::Node& root_of(DOM::Node& node)+{+ auto* parent = parent_of(node);+ return parent ? parent->root() : node;+}++// Whether `a` comes before `b` in document order, where an element's attributes come after it and before its children.+static bool is_before(DOM::Node& a, DOM::Node& b)+{+ return b.compare_document_position(a) & DOM::Node::DOCUMENT_POSITION_PRECEDING;+}++static void sort_in_document_order(NodeSet& set)+{+ if (set.is_in_document_order)+ return;+ set.is_in_document_order = true;++ // Comparing two nodes costs their depth plus the width of the tree where their paths part, so sorting by+ // comparison is only for sets small enough that walking the tree would cost more.+ static constexpr size_t LARGEST_SET_TO_SORT_BY_COMPARING = 16;+ if (set.nodes.size() <= LARGEST_SET_TO_SORT_BY_COMPARING) {+ quick_sort(set.nodes, [](auto& a, auto& b) { return is_before(a, b); });+ return;}- case DOM::NodeType::ELEMENT_NODE: {- auto const& element = static_cast<DOM::Element const&>(node);- auto name = element.local_name().view().to_utf8_but_should_be_ported_to_utf16().to_byte_string();- auto* xml_element = xmlNewDocNode(doc, nullptr, bit_cast<xmlChar const*>(name.characters()), nullptr);- xml_element->_private = bit_cast<void*>(&node);- for (size_t i = 0; i < element.attribute_list_size(); ++i) {- auto const& attribute = *element.attributes()->item(i);- auto attr_name_utf8 = attribute.name().view().to_utf8_but_should_be_ported_to_utf16();- ByteString attr_name = attr_name_utf8.bytes_as_string_view();- auto attr_value_utf8 = attribute.value().to_utf8();- ByteString attr_value = attr_value_utf8.bytes_as_string_view();- auto* attr = xmlSetProp(xml_element, bit_cast<xmlChar const*>(attr_name.characters()), bit_cast<xmlChar const*>(attr_value.characters()));- attr->_private = bit_cast<void*>(&attribute);-- if (attribute.name() == "id"sv) {- xmlAddIDSafe(attr, bit_cast<xmlChar const*>(attr_value.characters()));++ // OPTIMIZATION: Walk the trees the nodes are in once, and pick the set's nodes out as they come by.+ GC::RootHashTable<DOM::Node*> members;+ GC::RootVector<DOM::Node*> roots;+ bool has_attributes = false;+ for (auto& node : set.nodes) {+ members.set(node.ptr());+ has_attributes |= node->is_attribute();+ auto* root = &root_of(node);+ if (!roots.contains_slow(root))+ roots.append(root);+ }+ quick_sort(roots);++ auto remaining = set.nodes.size();+ set.nodes.clear_with_capacity();+ auto visit = [&](DOM::Node& node) {+ if (members.contains(&node)) {+ set.nodes.unchecked_append(node);+ --remaining;+ }+ };+ for (auto* root : roots) {+ for (auto* node = root; node && remaining > 0; node = node->next_in_pre_order()) {+ visit(*node);+ if (!has_attributes)+ continue;+ if (auto* element = as_if<DOM::Element>(*node)) {+ for (size_t i = 0; i < element->attribute_list_size(); ++i)+ visit(*element->attributes()->item(i));}}- auto children = element.children_as_vector();- for (auto& child : children) {- xmlAddChild(xml_element, mirror_node(doc, *child));+ }+ VERIFY(remaining == 0);+}++static GC::Ptr<DOM::Node> first_in_document_order(NodeSet const& set)+{+ if (set.nodes.is_empty())+ return nullptr;+ auto first = set.nodes[0];+ if (!set.is_in_document_order) {+ for (auto& node : set.nodes) {+ if (is_before(node, first))+ first = node;}+ }+ return first;+}++// https://www.w3.org/TR/1999/REC-xpath-19991116/#data-model+static Utf16String string_value(DOM::Node& node)+{+ // A document's text content is null, but the string-value of a root node is all the text in it.+ if (node.is_document())+ return node.descendant_text_content();+ return node.text_content().value_or({});+}- return xml_element;+// https://www.w3.org/TR/1999/REC-xpath-19991116/#function-number+static double string_to_number(Utf16View string)+{+ // Number ::= Digits ('.' Digits?)? | '.' Digits, with an optional minus sign before it and white space around it.+ // That is what a number is to parse_number() too, once exponents and plus signs are out of the way.+ string = string.trim(XML_WHITESPACE);+ for (size_t i = 0; i < string.length_in_code_units(); ++i) {+ auto code_unit = string.code_unit_at(i);+ if (!is_ascii_digit(code_unit) && code_unit != '.' && code_unit != '-')+ return NAN;}- case DOM::NodeType::ATTRIBUTE_NODE: {- return nullptr; // Attributes are handled in the elements children above. If this happens, then the attribute is the top node in the document and therefore invalid+ return parse_number<double>(string, TrimWhitespace::No).value_or(NAN);+}++// https://www.w3.org/TR/1999/REC-xpath-19991116/#function-normalize-space+static Utf16String normalize_space(Utf16View string)+{+ Utf16StringBuilder builder;+ bool pending_space = false;+ for (size_t i = 0; i < string.length_in_code_units(); ++i) {+ auto code_unit = string.code_unit_at(i);+ if (XML_WHITESPACE.contains(code_unit)) {+ pending_space = !builder.is_empty();+ continue;+ }+ if (pending_space)+ builder.append_code_unit(' ');+ pending_space = false;+ builder.append_code_unit(code_unit);}- case DOM::NodeType::TEXT_NODE: {- auto const& text = static_cast<DOM::Text const&>(node);- auto* xml_text = xmlNewDocText(doc, bit_cast<xmlChar const*>(text.data().to_byte_string().characters()));- xml_text->_private = bit_cast<void*>(&node);- return xml_text;+ return builder.to_string();+}++static bool to_boolean(Value const& value)+{+ return value.visit(+ [](bool boolean) { return boolean; },+ [](double number) { return number != 0 && !isnan(number); },+ [](Utf16String const& string) { return !string.is_empty(); },+ [](NodeSet const& set) { return !set.nodes.is_empty(); });+}++static Utf16String to_string(Value const& value)+{+ return value.visit(+ [](bool boolean) { return boolean ? "true"_utf16 : "false"_utf16; },+ // A number is written the way script writes one, except that it never has an exponent.+ [](double number) { return JS::number_to_utf16_string(number, JS::NumberToStringMode::WithoutExponent); },+ [](Utf16String const& string) { return string; },+ [](NodeSet const& set) {+ auto first = first_in_document_order(set);+ return first ? string_value(*first) : Utf16String {};+ });+}++static double to_number(Value const& value)+{+ return value.visit(+ [](bool boolean) { return boolean ? 1.0 : 0.0; },+ [](double number) { return number; },+ [](Utf16String const& string) { return string_to_number(string); },+ [&](NodeSet const&) { return string_to_number(to_string(value)); });+}++// https://www.w3.org/TR/1999/REC-xpath-19991116/#function-round+static double round_number(double number)+{+ if (!isfinite(number))+ return number;+ if (signbit(number) && number >= -0.5)+ return -0.0;+ // Not floor(number + 0.5): the sum is rounded itself, which takes the number just below a half up to one and an+ // odd integer too large to have a fraction up to the next even one.+ auto rounded = floor(number);+ return number - rounded >= 0.5 ? rounded + 1 : rounded;+}++static bool compare_numbers(FFI::XPathKind kind, double left, double right)+{+ switch (kind) {+ case FFI::XPathKind::Equal:+ return left == right;+ case FFI::XPathKind::NotEqual:+ return left != right;+ case FFI::XPathKind::Less:+ return left < right;+ case FFI::XPathKind::LessOrEqual:+ return left <= right;+ case FFI::XPathKind::Greater:+ return left > right;+ case FFI::XPathKind::GreaterOrEqual:+ return left >= right;+ default:+ VERIFY_NOT_REACHED();}- case DOM::NodeType::CDATA_SECTION_NODE: {- auto const& cdata = static_cast<DOM::CDATASection const&>(node);- ByteString data = cdata.data().to_byte_string();- auto* xml_cdata = xmlNewCDataBlock(doc, bit_cast<xmlChar const*>(data.characters()), data.length());- xml_cdata->_private = bit_cast<void*>(&node);- return xml_cdata;+}++static bool is_equality(FFI::XPathKind kind)+{+ return kind == FFI::XPathKind::Equal || kind == FFI::XPathKind::NotEqual;+}++// Compares two values of which neither is a node-set.+static bool compare_simple_values(FFI::XPathKind kind, Value const& left, Value const& right)+{+ if (is_equality(kind)) {+ bool equal;+ if (left.has<bool>() || right.has<bool>())+ equal = to_boolean(left) == to_boolean(right);+ else if (left.has<double>() || right.has<double>())+ equal = to_number(left) == to_number(right);+ else+ equal = left.get<Utf16String>() == right.get<Utf16String>();+ return equal == (kind == FFI::XPathKind::Equal);}- case DOM::NodeType::ENTITY_REFERENCE_NODE: // Does not seem to be used at all in ladybird- case DOM::NodeType::ENTITY_NODE: // Entity nodes are unused in libxml2- {- return nullptr;+ return compare_numbers(kind, to_number(left), to_number(right));+}++// The comparison with its operands the other way around: a < b is b > a.+static FFI::XPathKind mirrored(FFI::XPathKind kind)+{+ switch (kind) {+ case FFI::XPathKind::Less:+ return FFI::XPathKind::Greater;+ case FFI::XPathKind::LessOrEqual:+ return FFI::XPathKind::GreaterOrEqual;+ case FFI::XPathKind::Greater:+ return FFI::XPathKind::Less;+ case FFI::XPathKind::GreaterOrEqual:+ return FFI::XPathKind::LessOrEqual;+ default:+ return kind;}- case DOM::NodeType::PROCESSING_INSTRUCTION_NODE: {- auto const& processing_instruction = static_cast<DOM::ProcessingInstruction const&>(node);- auto target = processing_instruction.target().view().to_utf8_but_should_be_ported_to_utf16().to_byte_string();- auto* xml_pi = xmlNewDocPI(doc, bit_cast<xmlChar const*>(target.characters()), bit_cast<xmlChar const*>(processing_instruction.data().to_byte_string().characters()));- xml_pi->_private = bit_cast<void*>(&node);- return xml_pi;+}++// https://www.w3.org/TR/1999/REC-xpath-19991116/#booleans+static bool compare_values(FFI::XPathKind kind, Value const& left, Value const& right)+{+ if (!left.has<NodeSet>() && !right.has<NodeSet>())+ return compare_simple_values(kind, left, right);+ if (!left.has<NodeSet>())+ return compare_values(mirrored(kind), right, left);++ // A node-set compares true to a value if one of its nodes does.+ auto const& left_set = left.get<NodeSet>();+ if (right.has<bool>())+ return compare_simple_values(kind, to_boolean(left), right);+ if (right.has<double>()) {+ for (auto& node : left_set.nodes) {+ if (compare_numbers(kind, string_to_number(string_value(node)), right.get<double>()))+ return true;+ }+ return false;}- case DOM::NodeType::COMMENT_NODE: {- auto const& comment = static_cast<DOM::Comment const&>(node);- auto* xml_comment = xmlNewDocComment(doc, bit_cast<xmlChar const*>(comment.data().to_byte_string().characters()));- xml_comment->_private = bit_cast<void*>(&node);- return xml_comment;+ if (right.has<Utf16String>()) {+ for (auto& node : left_set.nodes) {+ if (compare_simple_values(kind, string_value(node), right))+ return true;+ }+ return false;}- case DOM::NodeType::DOCUMENT_NODE: {- auto const& document = static_cast<DOM::Document const&>(node);- auto const* document_element = document.document_element();- if (!document_element)- return nullptr;- return mirror_node(doc, *document_element);++ // Two node-sets compare true if a node of one and a node of the other do.+ auto const& right_set = right.get<NodeSet>();+ if (left_set.nodes.is_empty() || right_set.nodes.is_empty())+ return false;+ if (kind == FFI::XPathKind::Equal) {+ // OPTIMIZATION: Look each string of one set up in the other, which is the common way to join two sets.+ HashTable<Utf16String> right_strings;+ for (auto& node : right_set.nodes)+ right_strings.set(string_value(node));+ for (auto& node : left_set.nodes) {+ if (right_strings.contains(string_value(node)))+ return true;+ }+ return false;}- case DOM::NodeType::DOCUMENT_TYPE_NODE: {- return nullptr; // Unused in libxml2+ if (kind == FFI::XPathKind::NotEqual) {+ // OPTIMIZATION: Some two strings differ unless every node of both sets has the same one, so each node is+ // looked at once, and no pair of them is.+ auto first = string_value(left_set.nodes[0]);+ auto has_another_string = [&](NodeSet const& set) {+ for (auto& node : set.nodes) {+ if (string_value(node) != first)+ return true;+ }+ return false;+ };+ return has_another_string(left_set) || has_another_string(right_set);}- case DOM::NodeType::DOCUMENT_FRAGMENT_NODE: {- auto const& fragment = static_cast<DOM::DocumentFragment const&>(node);- auto* xml_fragment = xmlNewDocFragment(doc);- xml_fragment->_private = bit_cast<void*>(&node);- auto children = fragment.children_as_vector();- for (auto& child : children) {- xmlAddChild(xml_fragment, mirror_node(doc, *child));++ // OPTIMIZATION: Some number of one set is less than some number of the other exactly if its smallest is less than+ // the other's largest, so each node is looked at once, and no pair of them is. A node that is no+ // number compares false to everything, and so does a set of nothing but such nodes.+ struct Range {+ double smallest { NAN };+ double largest { NAN };+ };+ auto range_of = [](NodeSet const& set) {+ Range range;+ for (auto& node : set.nodes) {+ auto number = string_to_number(string_value(node));+ if (isnan(number))+ continue;+ if (isnan(range.smallest) || number < range.smallest)+ range.smallest = number;+ if (isnan(range.largest) || number > range.largest)+ range.largest = number;}- return xml_fragment;+ return range;+ };+ auto left_range = range_of(left_set);+ auto right_range = range_of(right_set);+ if (kind == FFI::XPathKind::Less || kind == FFI::XPathKind::LessOrEqual)+ return compare_numbers(kind, left_range.smallest, right_range.largest);+ return compare_numbers(kind, left_range.largest, right_range.smallest);+}++static bool is_reverse_axis(FFI::XPathAxis axis)+{+ return first_is_one_of(axis, FFI::XPathAxis::Ancestor, FFI::XPathAxis::AncestorOrSelf, FFI::XPathAxis::Preceding, FFI::XPathAxis::PrecedingSibling);+}++// Calls `callback` with each node on `axis` of `context`, nearest first: in document order for a forward axis and in+// reverse document order for a reverse one.+template<typename Callback>+static void for_each_node_on_axis(FFI::XPathAxis axis, DOM::Node& context, Callback callback)+{+ auto* attribute = as_if<DOM::Attr>(context);++ switch (axis) {+ case FFI::XPathAxis::Self_:+ callback(context);+ return;+ case FFI::XPathAxis::Child:+ for (auto* child = context.first_child(); child; child = child->next_sibling())+ callback(*child);+ return;+ case FFI::XPathAxis::DescendantOrSelf:+ callback(context);+ [[fallthrough]];+ case FFI::XPathAxis::Descendant:+ for (auto* node = context.first_child(); node; node = node->next_in_pre_order(&context))+ callback(*node);+ return;+ case FFI::XPathAxis::Parent:+ if (auto* parent = parent_of(context))+ callback(*parent);+ return;+ case FFI::XPathAxis::AncestorOrSelf:+ callback(context);+ [[fallthrough]];+ case FFI::XPathAxis::Ancestor:+ for (auto* node = parent_of(context); node; node = node->parent())+ callback(*node);+ return;+ case FFI::XPathAxis::FollowingSibling:+ for (auto* node = context.next_sibling(); node; node = node->next_sibling())+ callback(*node);+ return;+ case FFI::XPathAxis::PrecedingSibling:+ for (auto* node = context.previous_sibling(); node; node = node->previous_sibling())+ callback(*node);+ return;+ case FFI::XPathAxis::Following: {+ DOM::Node* node = nullptr;+ if (attribute) {+ // What follows an attribute starts with its element's children.+ if (auto* element = attribute->owner_element())+ node = element->next_in_pre_order();+ } else {+ // What follows a node starts after its last descendant.+ for (auto* ancestor = &context; ancestor && !node; ancestor = ancestor->parent())+ node = ancestor->next_sibling();+ }+ for (; node; node = node->next_in_pre_order())+ callback(*node);+ return;}- case DOM::NodeType::NOTATION_NODE: {- return nullptr; // Unused in libxml2+ case FFI::XPathAxis::Preceding: {+ // Everything before the node except its ancestors.+ auto* node = attribute ? attribute->owner_element() : &context;+ if (!node)+ return;+ while (auto* parent = node->parent()) {+ for (node = node->previous_in_pre_order(); node != parent; node = node->previous_in_pre_order())+ callback(*node);+ node = parent;+ }+ return;}+ case FFI::XPathAxis::Attribute: {+ auto* element = as_if<DOM::Element>(context);+ if (!element)+ return;+ for (size_t i = 0; i < element->attribute_list_size(); ++i) {+ // A namespace declaration is a namespace node in XPath's data model, not an attribute.+ auto attribute = element->attributes()->item(i);+ if (attribute->namespace_uri() != Namespace::XMLNS)+ callback(*attribute);+ }+ return;}-- return nullptr;+ case FFI::XPathAxis::Namespace:+ // The DOM has no namespace nodes.+ return;+ }+ VERIFY_NOT_REACHED();}-static void convert_xpath_result(xmlXPathObjectPtr xpath_result, GC::Ptr<XPath::XPathResult> result, unsigned short type)+// Unlike getElementById(), id() selects every element that has the id.+template<typename Callback>+static void for_each_element_with_id(DOM::Node& root, Utf16View id, Callback callback){- if (!xpath_result) {+ if (auto* document = as_if<DOM::Document>(root)) {+ document->element_by_id().for_each_element_with_id(id, root, [&](DOM::Element& element) { callback(element); });return;}+ root.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {+ if (element.id().has_value() && element.id()->view() == id)+ callback(element);+ return TraversalDecision::Continue;+ });+}- switch (xpath_result->type) {- case XPATH_UNDEFINED:- break;- case XPATH_NODESET: {- GC::RootVector<GC::Ptr<DOM::Node>> node_list;+class Evaluator {+public:+ explicit Evaluator(Expression const& expression)+ : m_expression(expression)+ , m_program(XML::XPath::view(*expression.m_program))+ {+ }++ Value run(DOM::Node& context_node)+ {+ return evaluate(m_program.root, { .node = context_node });+ }++ // Whether a value that isn't a node-set was used where only a node-set makes sense.+ bool had_type_error() const { return m_had_type_error; }++private:+ ReadonlySpan<u32> list(u32 first, u32 count) const+ {+ return { m_program.lists + first, count };+ }++ NodeSet to_node_set(Value value)+ {+ if (auto* set = value.get_pointer<NodeSet>())+ return move(*set);+ m_had_type_error = true;+ return {};+ }- if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr > 0) {- node_list.ensure_capacity(xpath_result->nodesetval->nodeNr);- for (int i = 0; i < xpath_result->nodesetval->nodeNr; i++) {- auto* node = xpath_result->nodesetval->nodeTab[i];- auto* dom_node = static_cast<DOM::Node*>(node->_private);+ bool node_matches(FFI::XPathStep const& step, Expression::Name const& name, DOM::Node& node) const+ {+ switch (static_cast<FFI::XPathNodeTest>(step.test)) {+ case FFI::XPathNodeTest::Node:+ return true;+ case FFI::XPathNodeTest::Text:+ return node.is_text();+ case FFI::XPathNodeTest::Comment:+ return node.is_comment();+ case FFI::XPathNodeTest::ProcessingInstruction:+ return is<DOM::ProcessingInstruction>(node);+ case FFI::XPathNodeTest::ProcessingInstructionWithTarget: {+ auto* processing_instruction = as_if<DOM::ProcessingInstruction>(node);+ return processing_instruction && processing_instruction->target() == name.local_name;+ }+ case FFI::XPathNodeTest::AnyName:+ case FFI::XPathNodeTest::AnyNameInNamespace:+ case FFI::XPathNodeTest::Name:+ break;+ }- node_list.unchecked_append(dom_node);+ // A name test only matches nodes of its axis' principal type: attributes on the attribute axis and elements+ // on every other.+ bool any_name = static_cast<FFI::XPathNodeTest>(step.test) != FFI::XPathNodeTest::Name;+ if (static_cast<FFI::XPathAxis>(step.axis) == FFI::XPathAxis::Attribute) {+ auto& attribute = as<DOM::Attr>(node);+ if (any_name)+ return !name.namespace_.has_value() || attribute.namespace_uri() == name.namespace_;+ // https://html.spec.whatwg.org/multipage/infrastructure.html#interactions-with-xpath-and-xslt+ // An attribute of an HTML element in an HTML document is matched without regard to ASCII case.+ if (!name.namespace_.has_value() && !attribute.namespace_uri().has_value() && node.document().is_html_document()) {+ auto const* element = attribute.owner_element();+ if (element && element->namespace_uri() == Namespace::HTML)+ return attribute.local_name().view().equals_ignoring_ascii_case(name.local_name.view());}+ return attribute.local_name() == name.local_name && attribute.namespace_uri() == name.namespace_;}- result->set_node_set(move(node_list), type);- break;+ auto* element = as_if<DOM::Element>(node);+ if (!element)+ return false;+ if (any_name)+ return !name.namespace_.has_value() || element->namespace_uri() == name.namespace_;+ // https://html.spec.whatwg.org/multipage/infrastructure.html#interactions-with-xpath-and-xslt+ // In an HTML document, a name without a prefix is one in the HTML namespace, and it is matched to an HTML+ // element's name without regard to ASCII case.+ if (node.document().is_html_document()) {+ if (element->namespace_uri() == Namespace::HTML) {+ return (!name.namespace_.has_value() || name.namespace_ == Namespace::HTML)+ && element->local_name().view().equals_ignoring_ascii_case(name.local_name.view());+ }+ return name.namespace_.has_value() && element->local_name() == name.local_name && element->namespace_uri() == name.namespace_;+ }+ return element->local_name() == name.local_name && element->namespace_uri() == name.namespace_;}- case XPATH_BOOLEAN: {- result->set_boolean(xpath_result->boolval);- break;++ bool predicate_holds(u32 predicate, Context const& context)+ {+ auto value = evaluate(predicate, context);+ // A number is short for a test of the position: [3] is [position() = 3].+ if (auto* number = value.get_pointer<double>())+ return *number == static_cast<double>(context.position);+ return to_boolean(value);}- case XPATH_NUMBER: {- result->set_number(xpath_result->floatval);- break;++ // Narrows `nodes`, which are in the order their positions count in, to those that each of `predicates` holds for.+ void apply_predicates(ReadonlySpan<u32> predicates, GC::RootVector<GC::Ref<DOM::Node>>& nodes)+ {+ for (auto predicate : predicates) {+ size_t kept = 0;+ auto size = nodes.size();+ for (size_t i = 0; i < size; ++i) {+ if (predicate_holds(predicate, { .node = nodes[i], .position = i + 1, .size = size }))+ nodes[kept++] = nodes[i];+ }+ nodes.shrink(kept, true);+ }}- case XPATH_STRING: {- ReadonlyBytes bytes(xpath_result->stringval, xmlStrlen(xpath_result->stringval));- result->set_string(Utf16String::from_utf8_without_validation(bytes));- break;++ // https://www.w3.org/TR/1999/REC-xpath-19991116/#location-paths+ NodeSet apply_steps(NodeSet input, u32 first_step, u32 step_count)+ {+ for (u32 step_index = first_step; step_index < first_step + step_count; ++step_index) {+ auto const& step = m_program.steps[step_index];+ auto const& name = m_expression.m_names[step_index];+ auto axis = static_cast<FFI::XPathAxis>(step.axis);+ auto predicates = list(step.first_predicate, step.predicate_count);++ // Two context nodes can only reach the same node on an axis that goes past a context node's own children.+ bool several_contexts = input.nodes.size() > 1;+ bool can_repeat = several_contexts && !first_is_one_of(axis, FFI::XPathAxis::Self_, FFI::XPathAxis::Child, FFI::XPathAxis::Attribute);++ NodeSet output;+ GC::RootHashTable<DOM::Node*> seen;+ GC::RootVector<GC::Ref<DOM::Node>> matches;+ for (auto& context_node : input.nodes) {+ matches.clear_with_capacity();+ for_each_node_on_axis(axis, context_node, [&](DOM::Node& node) {+ if (node_matches(step, name, node))+ matches.append(node);+ });+ apply_predicates(predicates, matches);+ for (auto& match : matches) {+ if (!can_repeat || seen.set(match.ptr()) == HashSetResult::InsertedNewEntry)+ output.nodes.append(match);+ }+ }++ if (!several_contexts) {+ // OPTIMIZATION: What one context node selects on a reverse axis is in reverse document order, so+ // turning it around saves sorting it later.+ if (is_reverse_axis(axis))+ output.nodes.reverse();+ } else {+ output.is_in_document_order = output.nodes.size() < 2+ || (input.is_in_document_order && first_is_one_of(axis, FFI::XPathAxis::Self_, FFI::XPathAxis::Attribute));+ }+ input = move(output);+ }+ return input;}- case XPATH_USERS:- case XPATH_XSLT_TREE: /* An XSLT value tree, non modifiable */- break;++ Utf16String string_argument(ReadonlySpan<u32> arguments, size_t index, Context const& context)+ {+ if (index < arguments.size())+ return to_string(evaluate(arguments[index], context));+ return string_value(context.node);}-}-WebIDL::ExceptionOr<GC::Ref<XPathExpression>> create_expression(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver)-{- return XPathExpression::create(expression, resolver);-}+ // The node a function like name() is about: the first of its argument, or the context node if it has none.+ GC::Ptr<DOM::Node> node_argument(ReadonlySpan<u32> arguments, Context const& context)+ {+ if (arguments.is_empty())+ return context.node;+ auto value = evaluate(arguments[0], context);+ if (auto* set = value.get_pointer<NodeSet>())+ return first_in_document_order(*set);+ // Nothing converts a boolean, a number or a string to a node-set.+ m_had_type_error = true;+ return nullptr;+ }-EvaluateResult evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPathNSResolver> /*resolver*/, unsigned short type, GC::Ptr<XPathResult> result)-{- // Parse the expression as xpath- auto expression_bytes = expression.to_utf8().to_byte_string();- auto* xpath_compiled = xmlXPathCompile(bit_cast<xmlChar const*>(expression_bytes.characters()));- if (!xpath_compiled)- return EvaluationError::InvalidExpression;- ScopeGuard xpath_compiled_cleanup = [&] { xmlXPathFreeCompExpr(xpath_compiled); };+ // https://www.w3.org/TR/1999/REC-xpath-19991116/#corelib+ Value call_function(FFI::XPathFunction function, ReadonlySpan<u32> arguments, Context const& context)+ {+ auto string = [&](size_t index) { return string_argument(arguments, index, context); };+ auto number = [&](size_t index) { return to_number(evaluate(arguments[index], context)); };- auto* xml_document = xmlNewDoc(nullptr);- ScopeGuard xml_cleanup = [&] { xmlFreeDoc(xml_document); };+ switch (function) {+ case FFI::XPathFunction::Last:+ return static_cast<double>(context.size);+ case FFI::XPathFunction::Position:+ return static_cast<double>(context.position);+ case FFI::XPathFunction::Count:+ return static_cast<double>(to_node_set(evaluate(arguments[0], context)).nodes.size());+ case FFI::XPathFunction::Id:+ return function_id(evaluate(arguments[0], context), context);+ case FFI::XPathFunction::LocalName: {+ auto node = node_argument(arguments, context);+ if (auto* element = as_if<DOM::Element>(node.ptr()))+ return element->local_name().to_utf16_string();+ if (auto* attribute = as_if<DOM::Attr>(node.ptr()))+ return attribute->local_name().to_utf16_string();+ if (auto* processing_instruction = as_if<DOM::ProcessingInstruction>(node.ptr()))+ return processing_instruction->target().to_utf16_string();+ return Utf16String {};+ }+ case FFI::XPathFunction::NamespaceUri: {+ auto node = node_argument(arguments, context);+ Optional<Utf16FlyString> namespace_;+ if (auto* element = as_if<DOM::Element>(node.ptr()))+ namespace_ = element->namespace_uri();+ else if (auto* attribute = as_if<DOM::Attr>(node.ptr()))+ namespace_ = attribute->namespace_uri();+ return namespace_.has_value() ? namespace_->to_utf16_string() : Utf16String {};+ }+ case FFI::XPathFunction::Name: {+ auto node = node_argument(arguments, context);+ if (auto* element = as_if<DOM::Element>(node.ptr()))+ return element->qualified_name().to_utf16_string();+ if (auto* attribute = as_if<DOM::Attr>(node.ptr()))+ return attribute->name().to_utf16_string();+ if (auto* processing_instruction = as_if<DOM::ProcessingInstruction>(node.ptr()))+ return processing_instruction->target().to_utf16_string();+ return Utf16String {};+ }+ case FFI::XPathFunction::String:+ return string(0);+ case FFI::XPathFunction::Concat: {+ Utf16StringBuilder builder;+ for (size_t i = 0; i < arguments.size(); ++i)+ builder.append(string(i));+ return builder.to_string();+ }+ case FFI::XPathFunction::StartsWith: {+ auto haystack = string(0);+ auto needle = string(1);+ return needle.is_empty() || haystack.utf16_view().starts_with(needle.utf16_view());+ }+ case FFI::XPathFunction::Contains: {+ auto haystack = string(0);+ auto needle = string(1);+ return needle.is_empty() || haystack.utf16_view().contains(needle.utf16_view());+ }+ case FFI::XPathFunction::SubstringBefore: {+ auto haystack = string(0);+ auto needle = string(1);+ if (needle.is_empty())+ return Utf16String {};+ auto offset = haystack.utf16_view().find_code_unit_offset(needle.utf16_view());+ if (!offset.has_value())+ return Utf16String {};+ return Utf16String::from_utf16(haystack.utf16_view().substring_view(0, *offset));+ }+ case FFI::XPathFunction::SubstringAfter: {+ auto haystack = string(0);+ auto needle = string(1);+ if (needle.is_empty())+ return haystack;+ auto offset = haystack.utf16_view().find_code_unit_offset(needle.utf16_view());+ if (!offset.has_value())+ return Utf16String {};+ return Utf16String::from_utf16(haystack.utf16_view().substring_view(*offset + needle.length_in_code_units()));+ }+ case FFI::XPathFunction::Substring: {+ auto source = string(0);+ auto start = round_number(number(1));+ auto end = start + (arguments.size() == 3 ? round_number(number(2)) : static_cast<double>(INFINITY));+ if (isnan(start) || isnan(end))+ return Utf16String {};+ // Positions count from one, and the end is the position after the last character.+ auto length = static_cast<double>(source.length_in_code_units());+ auto first = clamp(start, 1.0, length + 1);+ auto last = clamp(end, first, length + 1);+ return Utf16String::from_utf16(source.utf16_view().substring_view(static_cast<size_t>(first) - 1, static_cast<size_t>(last - first)));+ }+ case FFI::XPathFunction::StringLength:+ return static_cast<double>(string(0).length_in_code_units());+ case FFI::XPathFunction::NormalizeSpace:+ return normalize_space(string(0));+ case FFI::XPathFunction::Translate: {+ auto source = string(0);+ auto from = string(1);+ auto to = string(2);+ Utf16StringBuilder builder;+ for (size_t i = 0; i < source.length_in_code_units(); ++i) {+ auto code_unit = source.code_unit_at(i);+ auto offset = from.utf16_view().find_code_unit_offset(code_unit);+ if (!offset.has_value())+ builder.append_code_unit(code_unit);+ else if (*offset < to.length_in_code_units())+ builder.append_code_unit(to.code_unit_at(*offset));+ }+ return builder.to_string();+ }+ case FFI::XPathFunction::Boolean:+ return to_boolean(evaluate(arguments[0], context));+ case FFI::XPathFunction::Not:+ return !to_boolean(evaluate(arguments[0], context));+ case FFI::XPathFunction::True:+ return true;+ case FFI::XPathFunction::False:+ return false;+ case FFI::XPathFunction::Lang:+ return function_lang(string(0), context);+ case FFI::XPathFunction::Number:+ if (arguments.is_empty())+ return string_to_number(string_value(context.node));+ return number(0);+ case FFI::XPathFunction::Sum: {+ double sum = 0;+ for (auto& node : to_node_set(evaluate(arguments[0], context)).nodes)+ sum += string_to_number(string_value(node));+ return sum;+ }+ case FFI::XPathFunction::Floor:+ return floor(number(0));+ case FFI::XPathFunction::Ceiling:+ return ceil(number(0));+ case FFI::XPathFunction::Round:+ return round_number(number(0));+ }+ VERIFY_NOT_REACHED();+ }++ // https://www.w3.org/TR/1999/REC-xpath-19991116/#function-id+ Value function_id(Value const& argument, Context const& context)+ {+ // The ids are the white space separated words of the argument, or of each node's string-value if it is a+ // node-set.+ Vector<Utf16String> lists;+ if (auto* set = argument.get_pointer<NodeSet>()) {+ for (auto& node : set->nodes)+ lists.append(string_value(node));+ } else {+ lists.append(to_string(argument));+ }- if (context_node.type() == DOM::NodeType::DOCUMENT_NODE) {- xml_document->_private = bit_cast<void*>(&context_node);- } else {- xml_document->_private = bit_cast<void*>(&context_node.document());+ NodeSet result;+ result.is_in_document_order = false;+ auto& root = root_of(context.node);+ GC::RootHashTable<DOM::Node*> seen;+ for (auto& ids : lists) {+ auto normalized = normalize_space(ids);+ normalized.utf16_view().for_each_split_view(' ', SplitBehavior::Nothing, [&](Utf16View id) {+ for_each_element_with_id(root, id, [&](DOM::Element& element) {+ if (seen.set(&element) == HashSetResult::InsertedNewEntry)+ result.nodes.append(element);+ });+ return IterationDecision::Continue;+ });+ }+ return result;}- auto* xml_node = mirror_node(xml_document, context_node);- if (!xml_node) {- return EvaluationError::EvaluationFailed;+ // https://www.w3.org/TR/1999/REC-xpath-19991116/#function-lang+ static bool function_lang(Utf16String const& language, Context const& context)+ {+ for (auto* node = context.node->is_attribute() ? parent_of(context.node) : context.node.ptr(); node; node = node->parent()) {+ auto* element = as_if<DOM::Element>(*node);+ if (!element)+ continue;+ auto xml_lang = element->get_attribute_ns(Namespace::XML, HTML::AttributeNames::lang);+ if (!xml_lang.has_value())+ continue;+ // The nearest xml:lang decides: it has to be the language, or the language and a suffix that starts with+ // a hyphen.+ auto const& value = *xml_lang;+ auto length = language.length_in_code_units();+ if (value.length_in_code_units() < length)+ return false;+ if (!value.utf16_view().substring_view(0, length).equals_ignoring_ascii_case(language.utf16_view()))+ return false;+ return value.length_in_code_units() == length || value.code_unit_at(length) == '-';+ }+ return false;}- xmlDocSetRootElement(xml_document, xml_node);+ FFI::XPathKind kind_of(u32 index) const { return static_cast<FFI::XPathKind>(m_program.kinds[index]); }- auto* xpath_context = xmlXPathNewContext(xml_document);- xmlXPathSetContextNode(xml_node, xpath_context);+ // The binary operators are the first kinds there are.+ static bool is_binary_operator(FFI::XPathKind kind) { return to_underlying(kind) <= to_underlying(FFI::XPathKind::Union); }- auto* xpath_result = xmlXPathCompiledEval(xpath_compiled, xpath_context);+ Value evaluate(u32 index, Context const& context)+ {+ // The binary operators associate to the left, so "1 + 1 + 1" is a tree in which each operator is the left+ // operand of the next: as deep as the expression is long, which nothing limits. So the left operands are+ // followed in a loop, and only what the compiler limits the nesting of is evaluated by recursion.+ Vector<u32, 8> operators;+ while (is_binary_operator(kind_of(index))) {+ operators.append(index);+ index = m_program.a[index];+ }+ auto value = evaluate_operand(index, context);+ while (!operators.is_empty())+ value = apply_binary_operator(operators.take_last(), move(value), context);+ return value;+ }- ScopeGuard xpath_result_cleanup = [&] {- xmlXPathFreeObject(xpath_result);- xmlXPathFreeContext(xpath_context);+ // Evaluates the binary operator at `index`, whose left operand has the value `left`.+ Value apply_binary_operator(u32 index, Value left, Context const& context)+ {+ auto kind = kind_of(index);+ auto b = m_program.b[index];++ switch (kind) {+ case FFI::XPathKind::Or:+ return to_boolean(left) || to_boolean(evaluate(b, context));+ case FFI::XPathKind::And:+ return to_boolean(left) && to_boolean(evaluate(b, context));+ case FFI::XPathKind::Equal:+ case FFI::XPathKind::NotEqual:+ case FFI::XPathKind::Less:+ case FFI::XPathKind::LessOrEqual:+ case FFI::XPathKind::Greater:+ case FFI::XPathKind::GreaterOrEqual: {+ auto right = evaluate(b, context);+ return compare_values(kind, left, right);+ }+ case FFI::XPathKind::Add:+ case FFI::XPathKind::Subtract:+ case FFI::XPathKind::Multiply:+ case FFI::XPathKind::Divide:+ case FFI::XPathKind::Modulo: {+ auto left_number = to_number(left);+ auto right_number = to_number(evaluate(b, context));+ if (kind == FFI::XPathKind::Add)+ return left_number + right_number;+ if (kind == FFI::XPathKind::Subtract)+ return left_number - right_number;+ if (kind == FFI::XPathKind::Multiply)+ return left_number * right_number;+ if (kind == FFI::XPathKind::Divide)+ return left_number / right_number;+ return fmod(left_number, right_number);+ }+ case FFI::XPathKind::Union: {+ auto result = to_node_set(move(left));+ auto right = to_node_set(evaluate(b, context));+ if (right.nodes.is_empty())+ return result;+ GC::RootHashTable<DOM::Node*> seen;+ for (auto& node : result.nodes)+ seen.set(node.ptr());+ for (auto& node : right.nodes) {+ if (seen.set(node.ptr()) == HashSetResult::InsertedNewEntry)+ result.nodes.append(node);+ }+ result.is_in_document_order = result.nodes.size() < 2;+ return result;+ }+ default:+ VERIFY_NOT_REACHED();+ }+ }++ // Evaluates the node at `index`, which is anything but a binary operator.+ Value evaluate_operand(u32 index, Context const& context)+ {+ auto kind = kind_of(index);+ auto a = m_program.a[index];+ auto b = m_program.b[index];+ auto c = m_program.c[index];++ switch (kind) {+ case FFI::XPathKind::Or:+ case FFI::XPathKind::And:+ case FFI::XPathKind::Equal:+ case FFI::XPathKind::NotEqual:+ case FFI::XPathKind::Less:+ case FFI::XPathKind::LessOrEqual:+ case FFI::XPathKind::Greater:+ case FFI::XPathKind::GreaterOrEqual:+ case FFI::XPathKind::Add:+ case FFI::XPathKind::Subtract:+ case FFI::XPathKind::Multiply:+ case FFI::XPathKind::Divide:+ case FFI::XPathKind::Modulo:+ case FFI::XPathKind::Union:+ // evaluate() takes these apart.+ VERIFY_NOT_REACHED();+ case FFI::XPathKind::Negate:+ return -to_number(evaluate(a, context));+ case FFI::XPathKind::Number:+ return m_program.numbers[a];+ case FFI::XPathKind::String:+ return m_expression.m_strings.get(index).value();+ case FFI::XPathKind::Variable:+ // An expression with a variable reference doesn't compile, as there is no way to give it a value.+ VERIFY_NOT_REACHED();+ case FFI::XPathKind::Function:+ return call_function(static_cast<FFI::XPathFunction>(a), list(b, c), context);+ case FFI::XPathKind::Filter: {+ // The positions in a filter's predicates count in document order.+ auto set = to_node_set(evaluate(a, context));+ sort_in_document_order(set);+ apply_predicates(list(b, c), set.nodes);+ return set;+ }+ case FFI::XPathKind::RelativePath: {+ NodeSet start;+ start.nodes.append(context.node);+ return apply_steps(move(start), b, c);+ }+ case FFI::XPathKind::AbsolutePath: {+ // The root is that of the tree the context node is in, which needn't be a document.+ NodeSet start;+ start.nodes.append(root_of(context.node));+ return apply_steps(move(start), b, c);+ }+ case FFI::XPathKind::ExpressionPath:+ return apply_steps(to_node_set(evaluate(a, context)), b, c);+ }+ VERIFY_NOT_REACHED();+ }++ Expression const& m_expression;+ FFI::XPathProgramView m_program;+ bool m_had_type_error { false };+};++static WebIDL::ExceptionOr<Utf16FlyString> resolve_prefix(GC::Ptr<XPathNSResolver> resolver, Utf16String const& prefix)+{+ auto unknown_prefix = [&] {+ return WebIDL::NamespaceError::create(Utf16String::formatted("The prefix '{}' in the XPath expression has no namespace", prefix));};+ if (!resolver)+ return unknown_prefix();- if (!result) {- result = XPathResult::create();+ auto& callback = resolver->callback();+ auto& vm = callback.associated_realm().vm();+ auto completion = WebIDL::call_user_object_operation(callback, "lookupNamespaceURI"_utf16_fly_string, {}, { { JS::Value { JS::PrimitiveString::create(vm, prefix) } } });+ // https://webidl.spec.whatwg.org/#call-a-user-objects-operation+ // What the resolver throws is reported and not thrown on to the caller, who is told the prefix is unknown.+ if (completion.is_abrupt()) {+ HTML::report_an_exception(callback.associated_realm().global_object(), completion.value());+ return unknown_prefix();}+ auto result = completion.value();+ if (result.is_nullish())+ return unknown_prefix();+ auto namespace_ = WebIDL::to_utf16_string(vm, result);+ if (namespace_.is_error()) {+ HTML::report_an_exception(callback.associated_realm().global_object(), namespace_.error_value());+ return unknown_prefix();+ }+ return Utf16FlyString::from_utf16(namespace_.value().utf16_view());+}- convert_xpath_result(xpath_result, result, type);+WebIDL::ExceptionOr<NonnullOwnPtr<Expression>> Expression::compile(Utf16String const& source, GC::Ptr<XPathNSResolver> resolver)+{+ auto utf8 = source.to_utf8();+ auto bytes = utf8.bytes();+ auto expression = adopt_own(*new Expression);+ expression->m_program = XML::XPath::compile(bytes);+ if (!expression->m_program)+ return WebIDL::SyntaxError::create("Invalid XPath expression"_utf16);- return GC::Ref<XPathResult> { *result };+ auto program = XML::XPath::view(*expression->m_program);+ auto text = [&](u32 offset, u32 length) {+ return Utf16String::from_utf8_without_validation(bytes.slice(offset, length));+ };++ for (size_t i = 0; i < program.node_count; ++i) {+ auto kind = static_cast<FFI::XPathKind>(program.kinds[i]);+ if (kind == FFI::XPathKind::Variable)+ return WebIDL::SyntaxError::create("XPath variable references are not supported"_utf16);+ if (kind == FFI::XPathKind::String)+ expression->m_strings.set(i, text(program.a[i], program.b[i]));+ }++ // The resolver is script and can tell in what order it is asked, so ask in the order the prefixes are written.+ Vector<size_t> steps_with_prefix;+ expression->m_names.resize(program.step_count);+ for (size_t i = 0; i < program.step_count; ++i) {+ auto const& step = program.steps[i];+ expression->m_names[i].local_name = Utf16FlyString::from_utf8_without_validation(StringView { bytes.slice(step.local_offset, step.local_length) });+ if (step.prefix_length != 0)+ steps_with_prefix.append(i);+ }+ quick_sort(steps_with_prefix, [&](auto a, auto b) { return program.steps[a].prefix_offset < program.steps[b].prefix_offset; });+ for (auto i : steps_with_prefix) {+ auto const& step = program.steps[i];+ expression->m_names[i].namespace_ = TRY(resolve_prefix(resolver, text(step.prefix_offset, step.prefix_length)));+ }+ return expression;}-WebIDL::ExceptionOr<GC::Ref<XPathResult>> throw_evaluation_error_if_needed(EvaluateResult result)+Expression::~Expression(){- return result.visit(- [](GC::Ref<XPathResult> result) -> WebIDL::ExceptionOr<GC::Ref<XPathResult>> {- return result;- },- [&](EvaluationError error) -> WebIDL::ExceptionOr<GC::Ref<XPathResult>> {- switch (error) {- case EvaluationError::InvalidExpression:- return WebIDL::SyntaxError::create("Invalid XPath expression"_utf16);- case EvaluationError::EvaluationFailed:- return WebIDL::OperationError::create("XPath evaluation failed"_utf16);+ XML::XPath::free(m_program);+}++WebIDL::ExceptionOr<GC::Ref<XPathResult>> Expression::evaluate(DOM::Node const& context_node, WebIDL::UnsignedShort type, GC::Ptr<XPathResult> result) const+{+ // A document fragment or a doctype is no node of XPath's data model.+ if (context_node.is_document_fragment() || context_node.is_document_type())+ return WebIDL::NotSupportedError::create("The node cannot be the context node of an XPath expression"_utf16);+ if (type > XPathResult::FIRST_ORDERED_NODE_TYPE)+ return WebIDL::NotSupportedError::create("Invalid XPath result type"_utf16);++ Evaluator evaluator { *this };+ auto value = evaluator.run(const_cast<DOM::Node&>(context_node));+ if (evaluator.had_type_error())+ return WebIDL::SyntaxError::create("The XPath expression uses a value that is not a node-set as one"_utf16);++ if (!result)+ result = XPathResult::create();+ switch (type) {+ case XPathResult::ANY_TYPE:+ break;+ case XPathResult::NUMBER_TYPE:+ value = to_number(value);+ break;+ case XPathResult::STRING_TYPE:+ value = to_string(value);+ break;+ case XPathResult::BOOLEAN_TYPE:+ value = to_boolean(value);+ break;+ default:+ if (!value.has<NodeSet>())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The XPath expression does not select nodes"_utf16 };+ break;+ }++ value.visit(+ [&](bool boolean) { result->set_boolean(boolean); },+ [&](double number) { result->set_number(number); },+ [&](Utf16String const& string) { result->set_string(string); },+ [&](NodeSet& set) {+ auto& root = root_of(const_cast<DOM::Node&>(context_node));+ // OPTIMIZATION: A result that only ever gives out one node holds just that node, and one that may give out+ // any node of the set doesn't have the set sorted to pick it.+ if (type == XPathResult::ANY_UNORDERED_NODE_TYPE) {+ result->set_node_set(set.nodes.span().trim(1), type, root);+ return;}- VERIFY_NOT_REACHED();+ sort_in_document_order(set);+ if (type == XPathResult::FIRST_ORDERED_NODE_TYPE)+ result->set_node_set(set.nodes.span().trim(1), type, root);+ else+ result->set_node_set(set.nodes, type, root);});+ return GC::Ref<XPathResult> { *result };+}++WebIDL::ExceptionOr<GC::Ref<XPathExpression>> create_expression(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver)+{+ return XPathExpression::create(TRY(Expression::compile(expression, resolver)));+}++WebIDL::ExceptionOr<GC::Ref<XPathResult>> evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPathNSResolver> resolver, WebIDL::UnsignedShort type, GC::Ptr<XPathResult> result)+{+ auto compiled = TRY(Expression::compile(expression, resolver));+ return compiled->evaluate(context_node, type, result);}}diff --git a/Libraries/LibWeb/XPath/XPath.h b/Libraries/LibWeb/XPath/XPath.hindex 2d369809747..5b3ae4e13a0 100644--- a/Libraries/LibWeb/XPath/XPath.h+++ b/Libraries/LibWeb/XPath/XPath.h@@ -1,23 +1,67 @@/** Copyright (c) 2025, Johannes Gustafsson <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#pragma once+#include <AK/HashMap.h>+#include <AK/NonnullOwnPtr.h>+#include <AK/Utf16FlyString.h>+#include <AK/Utf16String.h>+#include <AK/Vector.h>#include <LibGC/Ptr.h>+#include <LibWeb/Forward.h>#include <LibWeb/WebIDL/ExceptionOr.h>+#include <LibWebCommon/WebIDL/Types.h>-#include "EvaluateResult.h"-#include "XPathExpression.h"-#include "XPathNSResolver.h"-#include "XPathResult.h"+namespace XML::FFI {++struct XPathProgram;++}namespace Web::XPath {+class XPathExpression;+class XPathNSResolver;+class XPathResult;++// An XPath 1.0 expression, compiled and with its namespace prefixes resolved.+class Expression {+ AK_MAKE_NONCOPYABLE(Expression);+ AK_MAKE_NONMOVABLE(Expression);+ AK_ALLOC_WITH_KMALLOC;++public:+ // Throws a SyntaxError if the text isn't an expression, and a NamespaceError if it uses a prefix the resolver+ // doesn't know. What the resolver throws is reported, and the prefix is one it doesn't know.+ static WebIDL::ExceptionOr<NonnullOwnPtr<Expression>> compile(Utf16String const&, GC::Ptr<XPathNSResolver>);+ ~Expression();++ WebIDL::ExceptionOr<GC::Ref<XPathResult>> evaluate(DOM::Node const& context_node, WebIDL::UnsignedShort type, GC::Ptr<XPathResult>) const;++ // What a step's node test compares names to.+ struct Name {+ Utf16FlyString local_name;+ Optional<Utf16FlyString> namespace_;+ };++private:+ friend class Evaluator;++ Expression() = default;++ XML::FFI::XPathProgram* m_program { nullptr };+ // One per step of the program.+ Vector<Name> m_names;+ // The string literals, by the node they are.+ HashMap<u32, Utf16String> m_strings;+};+WebIDL::ExceptionOr<GC::Ref<XPathExpression>> create_expression(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver);-EvaluateResult evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPathNSResolver> resolver, unsigned short type, GC::Ptr<XPathResult> result);-WebIDL::ExceptionOr<GC::Ref<XPathResult>> throw_evaluation_error_if_needed(EvaluateResult);+WebIDL::ExceptionOr<GC::Ref<XPathResult>> evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPathNSResolver> resolver, WebIDL::UnsignedShort type, GC::Ptr<XPathResult> result);}diff --git a/Libraries/LibWeb/XPath/XPathEvaluator.cpp b/Libraries/LibWeb/XPath/XPathEvaluator.cppindex 4c9945e8909..f3a50a41cf7 100644--- a/Libraries/LibWeb/XPath/XPathEvaluator.cpp+++ b/Libraries/LibWeb/XPath/XPathEvaluator.cpp@@ -34,7 +34,7 @@ WebIDL::ExceptionOr<GC::Ref<XPathExpression>> XPathEvaluator::create_expression(WebIDL::ExceptionOr<GC::Ref<XPathResult>> XPathEvaluator::evaluate(Utf16String const& expression, DOM::Node const& context_node, GC::Ptr<XPathNSResolver> resolver, WebIDL::UnsignedShort type, GC::Ptr<XPathResult> result){- return XPath::throw_evaluation_error_if_needed(XPath::evaluate(expression, context_node, resolver, type, result));+ return XPath::evaluate(expression, context_node, resolver, type, result);}GC::Ref<DOM::Node> XPathEvaluator::create_ns_resolver(GC::Ref<DOM::Node> node_resolver)diff --git a/Libraries/LibWeb/XPath/XPathEvaluator.h b/Libraries/LibWeb/XPath/XPathEvaluator.hindex b07f0ee2db5..fb721cee149 100644--- a/Libraries/LibWeb/XPath/XPathEvaluator.h+++ b/Libraries/LibWeb/XPath/XPathEvaluator.h@@ -10,7 +10,6 @@#include <LibWeb/Forward.h>#include <LibWebCommon/WebIDL/Types.h>-#include "EvaluateResult.h"#include "XPathExpression.h"#include "XPathNSResolver.h"#include "XPathResult.h"diff --git a/Libraries/LibWeb/XPath/XPathExpression.cpp b/Libraries/LibWeb/XPath/XPathExpression.cppindex 56544172e30..7c212cc04f9 100644--- a/Libraries/LibWeb/XPath/XPathExpression.cpp+++ b/Libraries/LibWeb/XPath/XPathExpression.cpp@@ -17,28 +17,21 @@ namespace Web::XPath {GC_DEFINE_ALLOCATOR(XPathExpression);-GC::Ref<XPathExpression> XPathExpression::create(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver)+GC::Ref<XPathExpression> XPathExpression::create(NonnullOwnPtr<Expression> expression){- return GC::Heap::the().allocate<XPathExpression>(expression, resolver);+ return GC::Heap::the().allocate<XPathExpression>(move(expression));}-XPathExpression::XPathExpression(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver)- : m_expression(expression)- , m_resolver(resolver)+XPathExpression::XPathExpression(NonnullOwnPtr<Expression> expression)+ : m_expression(move(expression)){}-void XPathExpression::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_resolver);-}-XPathExpression::~XPathExpression() = default;WebIDL::ExceptionOr<GC::Ref<XPathResult>> XPathExpression::evaluate(DOM::Node const& context_node, WebIDL::UnsignedShort type, GC::Ptr<XPathResult> result){- return XPath::throw_evaluation_error_if_needed(XPath::evaluate(m_expression, context_node, m_resolver, type, result));+ return m_expression->evaluate(context_node, type, result);}}diff --git a/Libraries/LibWeb/XPath/XPathExpression.h b/Libraries/LibWeb/XPath/XPathExpression.hindex 3aea16bb2d9..7b455e90671 100644--- a/Libraries/LibWeb/XPath/XPathExpression.h+++ b/Libraries/LibWeb/XPath/XPathExpression.h@@ -8,29 +8,28 @@#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Forward.h>-#include <LibWeb/XPath/EvaluateResult.h>#include <LibWeb/XPath/XPathNSResolver.h>#include <LibWeb/XPath/XPathResult.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::XPath {+class Expression;+class XPathExpression final : public Bindings::GCAllocatedWrappable {WEB_WRAPPABLE(XPathExpression, Bindings::GCAllocatedWrappable);GC_DECLARE_ALLOCATOR(XPathExpression);public:- [[nodiscard]] static GC::Ref<XPathExpression> create(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver);+ [[nodiscard]] static GC::Ref<XPathExpression> create(NonnullOwnPtr<Expression>);- explicit XPathExpression(Utf16String const& expression, GC::Ptr<XPathNSResolver> resolver);+ explicit XPathExpression(NonnullOwnPtr<Expression>);virtual ~XPathExpression() override;- virtual void visit_edges(GC::Cell::Visitor&) override;WebIDL::ExceptionOr<GC::Ref<XPathResult>> evaluate(DOM::Node const& context_node, WebIDL::UnsignedShort type = 0, GC::Ptr<XPathResult> result = nullptr);private:- Utf16String m_expression;- GC::Ptr<XPathNSResolver> m_resolver;+ NonnullOwnPtr<Expression> m_expression;};}diff --git a/Libraries/LibWeb/XPath/XPathResult.cpp b/Libraries/LibWeb/XPath/XPathResult.cppindex d76d2bda1e3..93f8cf90345 100644--- a/Libraries/LibWeb/XPath/XPathResult.cpp+++ b/Libraries/LibWeb/XPath/XPathResult.cpp@@ -5,6 +5,7 @@*/#include <LibGC/Heap.h>+#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Node.h>#include "XPathResult.h"@@ -18,63 +19,137 @@ GC::Ref<XPathResult> XPathResult::create()return GC::Heap::the().allocate<XPathResult>();}-XPathResult::XPathResult()-{- m_node_set_iter = m_node_set.end();-}+XPathResult::XPathResult() = default;void XPathResult::visit_edges(GC::Cell::Visitor& visitor){Base::visit_edges(visitor);visitor.visit(m_node_set);- if (!m_node_set_iter.is_end())- visitor.visit(*m_node_set_iter);+ visitor.visit(m_root);}XPathResult::~XPathResult() = default;+// A result that is used again for a value that isn't a node-set must not keep the tree of the last one alive.+void XPathResult::forget_node_set()+{+ m_node_set.clear();+ m_root = nullptr;+ m_next_node = 0;+}+void XPathResult::set_number(WebIDL::Double number_value){+ forget_node_set();m_result_type = NUMBER_TYPE;m_number_value = number_value;}+void XPathResult::set_string(Utf16String string_value){+ forget_node_set();m_result_type = STRING_TYPE;m_string_value = move(string_value);}void XPathResult::set_boolean(bool boolean_value){+ forget_node_set();m_result_type = BOOLEAN_TYPE;m_boolean_value = boolean_value;}-void XPathResult::set_node_set(Vector<GC::Ptr<DOM::Node>>&& node_set, unsigned short type)+void XPathResult::set_node_set(ReadonlySpan<GC::Ref<DOM::Node>> node_set, unsigned short type, DOM::Node& root){- if (type >= XPathResult::UNORDERED_NODE_ITERATOR_TYPE && type <= XPathResult::FIRST_ORDERED_NODE_TYPE)+ // A result nobody asked a type of is an unordered iterator.+ if (type >= UNORDERED_NODE_ITERATOR_TYPE && type <= FIRST_ORDERED_NODE_TYPE)m_result_type = type;else- m_result_type = UNORDERED_NODE_ITERATOR_TYPE; // Default if the caller does not explicity ask for anything else+ m_result_type = UNORDERED_NODE_ITERATOR_TYPE;++ m_node_set.clear_with_capacity();+ m_node_set.ensure_capacity(node_set.size());+ for (auto node : node_set)+ m_node_set.unchecked_append(node);+ m_next_node = 0;+ m_root = root;+ m_dom_tree_version = root.dom_tree_version();+ m_character_data_version = root.character_data_version();+}- m_node_set = move(node_set);- m_node_set_iter = m_node_set.begin();+static WebIDL::SimpleException wrong_type()+{+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The XPathResult is not of the type this needs"_utf16 };}-GC::Ptr<DOM::Node> XPathResult::iterate_next()+// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-numberValue+WebIDL::ExceptionOr<WebIDL::Double> XPathResult::number_value() const{- if (m_node_set_iter == m_node_set.end())- return nullptr;+ if (m_result_type != NUMBER_TYPE)+ return wrong_type();+ return m_number_value;+}++// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-stringValue+WebIDL::ExceptionOr<Utf16String> XPathResult::string_value() const+{+ if (m_result_type != STRING_TYPE)+ return wrong_type();+ return m_string_value;+}- return *m_node_set_iter++;+// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-booleanValue+WebIDL::ExceptionOr<WebIDL::Boolean> XPathResult::boolean_value() const+{+ if (m_result_type != BOOLEAN_TYPE)+ return wrong_type();+ return m_boolean_value;+}++// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-singleNodeValue+WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> XPathResult::single_node_value() const+{+ if (m_result_type != ANY_UNORDERED_NODE_TYPE && m_result_type != FIRST_ORDERED_NODE_TYPE)+ return wrong_type();+ return m_node_set.is_empty() ? nullptr : m_node_set.first();+}++// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-invalid-iterator-state+WebIDL::Boolean XPathResult::invalid_iterator_state() const+{+ // Changing the data of a text node changes the tree as much as moving a node does.+ return is_iterator()+ && (m_root->dom_tree_version() != m_dom_tree_version || m_root->character_data_version() != m_character_data_version);}-GC::Ptr<DOM::Node> XPathResult::snapshot_item(int index)+// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshot-length+WebIDL::ExceptionOr<WebIDL::UnsignedLong> XPathResult::snapshot_length() const{- if (index < 0 || static_cast<size_t>(index) >= m_node_set.size())+ if (!is_snapshot())+ return wrong_type();+ return m_node_set.size();+}++// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-iterateNext+WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> XPathResult::iterate_next()+{+ if (!is_iterator())+ return wrong_type();+ if (invalid_iterator_state())+ return WebIDL::InvalidStateError::create("The tree has changed since the XPath expression was evaluated"_utf16);+ if (m_next_node >= m_node_set.size())return nullptr;+ return m_node_set[m_next_node++];+}- return m_node_set.at(index);+// https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult-snapshotItem+WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> XPathResult::snapshot_item(WebIDL::UnsignedLong index) const+{+ if (!is_snapshot())+ return wrong_type();+ if (index >= m_node_set.size())+ return nullptr;+ return m_node_set[index];}}diff --git a/Libraries/LibWeb/XPath/XPathResult.h b/Libraries/LibWeb/XPath/XPathResult.hindex 49b7d883ff9..42de9a21259 100644--- a/Libraries/LibWeb/XPath/XPathResult.h+++ b/Libraries/LibWeb/XPath/XPathResult.h@@ -10,6 +10,7 @@#include <AK/Vector.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Forward.h>+#include <LibWeb/WebIDL/ExceptionOr.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::XPath {@@ -37,31 +38,41 @@ public:virtual void visit_edges(GC::Cell::Visitor&) override;WebIDL::UnsignedShort result_type() const { return m_result_type; }- WebIDL::Double number_value() const { return m_number_value; }- Utf16String string_value() { return m_string_value; }- WebIDL::Boolean boolean_value() const { return m_boolean_value; }- GC::Ptr<DOM::Node> single_node_value() { return m_node_set.is_empty() ? nullptr : m_node_set.first(); }- WebIDL::Boolean invalid_iterator_state() const { return m_invalid_iterator_state; }- WebIDL::UnsignedLong snapshot_length() const { return m_node_set.size(); }+ WebIDL::ExceptionOr<WebIDL::Double> number_value() const;+ WebIDL::ExceptionOr<Utf16String> string_value() const;+ WebIDL::ExceptionOr<WebIDL::Boolean> boolean_value() const;+ WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> single_node_value() const;+ WebIDL::Boolean invalid_iterator_state() const;+ WebIDL::ExceptionOr<WebIDL::UnsignedLong> snapshot_length() const;- GC::Ptr<DOM::Node> iterate_next();- GC::Ptr<DOM::Node> snapshot_item(int index);+ WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> iterate_next();+ WebIDL::ExceptionOr<GC::Ptr<DOM::Node>> snapshot_item(WebIDL::UnsignedLong index) const;++ // The nodes of a result that has nodes, in document order.+ ReadonlySpan<GC::Ptr<DOM::Node>> nodes() const { return m_node_set; }void set_number(WebIDL::Double number_value);void set_string(Utf16String string_value);void set_boolean(bool boolean_value);- void set_node_set(Vector<GC::Ptr<DOM::Node>>&& node_set, unsigned short type);+ // `root` is the root of the tree the nodes were selected in: changing that tree invalidates an iterator over them.+ void set_node_set(ReadonlySpan<GC::Ref<DOM::Node>> node_set, unsigned short type, DOM::Node& root);private:+ void forget_node_set();++ bool is_iterator() const { return m_result_type == UNORDERED_NODE_ITERATOR_TYPE || m_result_type == ORDERED_NODE_ITERATOR_TYPE; }+ bool is_snapshot() const { return m_result_type == UNORDERED_NODE_SNAPSHOT_TYPE || m_result_type == ORDERED_NODE_SNAPSHOT_TYPE; }+WebIDL::UnsignedShort m_result_type { 0 };WebIDL::Double m_number_value { 0 };Utf16String m_string_value;WebIDL::Boolean m_boolean_value { false };- WebIDL::Boolean m_invalid_iterator_state { false };- WebIDL::UnsignedLong m_snapshot_length { 0 };Vector<GC::Ptr<DOM::Node>> m_node_set;- Vector<GC::Ptr<DOM::Node>>::Iterator m_node_set_iter;+ size_t m_next_node { 0 };+ GC::Ptr<DOM::Node> m_root;+ u64 m_dom_tree_version { 0 };+ u64 m_character_data_version { 0 };};}diff --git a/Tests/LibWeb/Text/expected/XPath/iterator-detached-tree.txt b/Tests/LibWeb/Text/expected/XPath/iterator-detached-tree.txtnew file mode 100644index 00000000000..2e740979201--- /dev/null+++ b/Tests/LibWeb/Text/expected/XPath/iterator-detached-tree.txt@@ -0,0 +1,8 @@+first: true+invalid after a change elsewhere: false+invalid after a change to its tree: true+InvalidStateError+invalid before a change to its text: false+invalid after a change to its text: true+invalid in a detached shadow tree: false+invalid after a change while connected: truediff --git a/Tests/LibWeb/Text/expected/XPath/long-operator-chains.txt b/Tests/LibWeb/Text/expected/XPath/long-operator-chains.txtnew file mode 100644index 00000000000..49a17c18dfa--- /dev/null+++ b/Tests/LibWeb/Text/expected/XPath/long-operator-chains.txt@@ -0,0 +1,21 @@+sum: 200001+or: true+union: 5+1 - 2 - 3: -4+8 div 2 div 2: 2+1 + 2 * 3 - 4: 3+3 > 2 > 1: false+0 or 1 and 0: false+round(0.49999999999999994): 0+round(-1.5): -1+round(4503599627370497): 4503599627370497+//i < //b: true+//i > //b: true+//s < //i: false+//u < //u: false+//u <= //u: true+//u != //u: false+//i != //i: true+//u != //s: true+//u = //i: false+//missing != //u: falsediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/evaluator-different-document.tentative.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/evaluator-different-document.tentative.txtindex 4204e7badb7..eac282dc7bc 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/evaluator-different-document.tentative.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/evaluator-different-document.tentative.txt@@ -2,13 +2,12 @@ Harness status: OKFound 8 tests-4 Pass-4 Fail-Fail evaluate operation on XML document, context node in XML document, no namespace resolver+8 Pass+Pass evaluate operation on XML document, context node in XML document, no namespace resolverPass evaluate operation on HTML document, context node in HTML document, no namespace resolverPass evaluate operation on XML document, context node in HTML document, no namespace resolver-Fail evaluate operation on HTML document, context node in XML document, no namespace resolver-Fail evaluate operation on XML document, context node in XML document, with namespace resolver+Pass evaluate operation on HTML document, context node in XML document, no namespace resolver+Pass evaluate operation on XML document, context node in XML document, with namespace resolverPass evaluate operation on HTML document, context node in HTML document, with namespace resolverPass evaluate operation on XML document, context node in HTML document, with namespace resolver-Fail evaluate operation on HTML document, context node in XML document, with namespace resolver\ No newline at end of file+Pass evaluate operation on HTML document, context node in XML document, with namespace resolver\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/expression-different-document.tentative.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/expression-different-document.tentative.txtindex 5793bf8e06b..a483c11f084 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/expression-different-document.tentative.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/expression-different-document.tentative.txt@@ -2,13 +2,12 @@ Harness status: OKFound 8 tests-4 Pass-4 Fail-Fail expression from XML document, context node in XML document, no namespace resolver+8 Pass+Pass expression from XML document, context node in XML document, no namespace resolverPass expression from HTML document, context node in HTML document, no namespace resolverPass expression from XML document, context node in HTML document, no namespace resolver-Fail expression from HTML document, context node in XML document, no namespace resolver-Fail expression from XML document, context node in XML document, with namespace resolver+Pass expression from HTML document, context node in XML document, no namespace resolver+Pass expression from XML document, context node in XML document, with namespace resolverPass expression from HTML document, context node in HTML document, with namespace resolverPass expression from XML document, context node in HTML document, with namespace resolver-Fail expression from HTML document, context node in XML document, with namespace resolver\ No newline at end of file+Pass expression from HTML document, context node in XML document, with namespace resolver\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-id.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-id.txtindex 1a13e1d284a..ee2bc4c22c0 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-id.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-id.txt@@ -2,13 +2,12 @@ Harness status: OKFound 8 tests-6 Pass-2 Fail+8 PassPass id("test1"): <root><div id="test1">Match</div></root>Pass id("test1 test2"): <root><div id="test1">First</div><div id="test2">Second</div></root>Pass id("nonexistent"): <root><div id="test1">No match</div></root>Pass id("Test1"): <root><div id="test1">No match</div></root>-Fail id("duplicate"): <root><div id="duplicate">First</div><div id="duplicate">Second</div></root>+Pass id("duplicate"): <root><div id="duplicate">First</div><div id="duplicate">Second</div></root>Pass id("test-1"): <root><div id="test-1">Match</div></root>Pass id(""): <root><div id="">Empty ID</div></root>-Fail id(" test1 "): <root><div id="test1">Match</div></root>\ No newline at end of file+Pass id(" test1 "): <root><div id="test1">Match</div></root>\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-lang.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-lang.txtindex 0c921ec59b2..b34c8e5ad84 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-lang.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-lang.txt@@ -2,12 +2,11 @@ Harness status: OKFound 7 tests-6 Pass-1 Fail+7 PassPass lang("en"): <root><match xml:lang="en"/></root>Pass lang("en"): <root><match xml:lang="EN"/></root>Pass lang("en"): <root><match xml:lang="en-us"/></root>Pass lang("en"): <root><unmatch/></root>-Fail lang("ja"): <root xml:lang="ja"><match/></root>+Pass lang("ja"): <root xml:lang="ja"><match/></root>Pass lang("ja"): <root xml:lang="ja-jp"><unmatch xml:lang="ja_JP"/></root>Pass lang("ko"): <root><unmatch xml:lang="Ko"/></root>\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-normalize-space.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-normalize-space.txtindex 622fa32ff46..70a4fcfbac0 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-normalize-space.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/fn-normalize-space.txt@@ -2,7 +2,6 @@ Harness status: OKFound 2 tests-1 Pass-1 Fail+2 PassPass normalize-space() without arguments-Fail normalize-space() should handle only #x20, #x9, #xD, and #xA\ No newline at end of file+Pass normalize-space() should handle only #x20, #x9, #xD, and #xA\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-callback-interface.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-callback-interface.txtindex 240ece4cfb0..9e5c526393a 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-callback-interface.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-callback-interface.txt@@ -2,14 +2,15 @@ Harness status: OKFound 10 tests-10 Fail-Fail callable resolver-Fail callable resolver: result is not cached+6 Pass+4 Fail+Pass callable resolver+Pass callable resolver: result is not cachedFail callable resolver: abrupt completion from Call-Fail callable resolver: no 'lookupNamespaceURI' lookups-Fail object resolver-Fail object resolver: this value and `prefix` argument-Fail object resolver: 'lookupNamespaceURI' is not cached+Pass callable resolver: no 'lookupNamespaceURI' lookups+Pass object resolver+Pass object resolver: this value and `prefix` argument+Pass object resolver: 'lookupNamespaceURI' is not cachedFail object resolver: abrupt completion from GetFail object resolver: 'lookupNamespaceURI' is thruthy and not callableFail object resolver: 'lookupNamespaceURI' is falsy and not callable\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-non-string-result.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-non-string-result.txtindex 44dc8ee03ca..29356d4a4ef 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-non-string-result.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/resolver-non-string-result.txt@@ -2,10 +2,11 @@ Harness status: OKFound 6 tests-6 Fail-Fail undefined-Fail null-Fail number-Fail boolean+4 Pass+2 Fail+Pass undefined+Pass null+Pass number+Pass booleanFail symbolFail object coercion (abrupt completion)\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/result-iterateNext.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/result-iterateNext.txtindex 156aba7c715..c4c52a0e353 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/result-iterateNext.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/result-iterateNext.txt@@ -2,12 +2,11 @@ Harness status: OKFound 7 tests-3 Pass-4 Fail+7 PassPass Using an ordered iterator without modifying the dom should yield the expected elements in correct order without errors.Pass Using an unordered iterator without modifying the dom should yield the correct number of elements without errors.Pass invalidIteratorState should be false for non-iterable results.-Fail Calling iterateNext on a non-iterable XPathResult should throw a TypeError.-Fail Calling iterateNext on a non-iterable XPathResult after modifying the DOM should throw a TypeError.-Fail Calling iterateNext after having modified the DOM should throw an exception.-Fail Calling iterateNext after having modified the DOM should throw an exception even if the iterator is exhausted.\ No newline at end of file+Pass Calling iterateNext on a non-iterable XPathResult should throw a TypeError.+Pass Calling iterateNext on a non-iterable XPathResult after modifying the DOM should throw a TypeError.+Pass Calling iterateNext after having modified the DOM should throw an exception.+Pass Calling iterateNext after having modified the DOM should throw an exception even if the iterator is exhausted.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-attributes.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-attributes.txtindex 4c814d54867..0acb8940af5 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-attributes.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-attributes.txt@@ -2,20 +2,19 @@ Harness status: OKFound 15 tests-10 Pass-5 Fail+15 PassPass Select html element based on attribute-Fail Select html element based on attribute mixed case+Pass Select html element based on attribute mixed casePass Select both HTML and SVG elements based on attributePass Select HTML element with non-ascii attribute 1Pass Select HTML element with non-ascii attribute 2-Fail Select HTML element with non-ascii attribute 3+Pass Select HTML element with non-ascii attribute 3Pass Select SVG element based on mixed case attribute-Fail Select both HTML and SVG elements based on mixed case attribute+Pass Select both HTML and SVG elements based on mixed case attributePass Select SVG elements with refX attributePass Select SVG elements with refX attribute incorrect casePass Select SVG elements with refX attribute lowercasePass Select SVG element with non-ascii attribute 1Pass Select SVG element with non-ascii attribute 2-Fail xmlns attribute-Fail svg element with XLink attribute\ No newline at end of file+Pass xmlns attribute+Pass svg element with XLink attribute\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-elements.txt b/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-elements.txtindex 054ca2e9480..19dbfa02d72 100644--- a/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-elements.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/domxpath/text-html-elements.txt@@ -2,16 +2,15 @@ Harness status: OKFound 11 tests-4 Pass-7 Fail+11 PassPass HTML elements no namespace prefix-Fail HTML elements namespace prefix-Fail HTML elements mixed use of prefix-Fail SVG elements no namespace prefix-Fail SVG elements namespace prefix-Fail HTML elements mixed case+Pass HTML elements namespace prefix+Pass HTML elements mixed use of prefix+Pass SVG elements no namespace prefix+Pass SVG elements namespace prefix+Pass HTML elements mixed casePass SVG elements mixed case selectorPass Non-ascii HTML elementPass Non-ascii HTML element2-Fail Non-ascii HTML element3-Fail Throw with invalid prefix\ No newline at end of file+Pass Non-ascii HTML element3+Pass Throw with invalid prefix\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/XPath/iterator-detached-tree.html b/Tests/LibWeb/Text/input/XPath/iterator-detached-tree.htmlnew file mode 100644index 00000000000..1adf58269d9--- /dev/null+++ b/Tests/LibWeb/Text/input/XPath/iterator-detached-tree.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const root = document.createElement("div");+ root.innerHTML = "<x></x><x></x>";+ const result = document.evaluate(".//x", root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);+ println(`first: ${result.iterateNext() === root.firstChild}`);++ // A change to another tree leaves the iterator alone.+ document.body.appendChild(document.createElement("p")).remove();+ println(`invalid after a change elsewhere: ${result.invalidIteratorState}`);++ // A change to the tree the nodes were selected in invalidates it.+ root.appendChild(document.createElement("x"));+ println(`invalid after a change to its tree: ${result.invalidIteratorState}`);+ try {+ result.iterateNext();+ println("FAIL: did not throw");+ } catch (e) {+ println(e.name);+ }++ // So does a change to the data of a text node in it.+ const text = root.firstChild.appendChild(document.createTextNode("a"));+ const other = document.evaluate(".//x", root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);+ println(`invalid before a change to its text: ${other.invalidIteratorState}`);+ text.data = "b";+ println(`invalid after a change to its text: ${other.invalidIteratorState}`);++ // And a change to a shadow tree made while its host was in the document.+ const host = document.createElement("div");+ const shadowRoot = host.attachShadow({ mode: "open" });+ shadowRoot.innerHTML = "<div><x></x><x></x></div>";+ const inShadowTree = document.evaluate(".//x", shadowRoot.firstChild, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);+ println(`invalid in a detached shadow tree: ${inShadowTree.invalidIteratorState}`);+ document.body.appendChild(host);+ shadowRoot.firstChild.firstChild.remove();+ host.remove();+ println(`invalid after a change while connected: ${inShadowTree.invalidIteratorState}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/XPath/long-operator-chains.html b/Tests/LibWeb/Text/input/XPath/long-operator-chains.htmlnew file mode 100644index 00000000000..f1da5649c56--- /dev/null+++ b/Tests/LibWeb/Text/input/XPath/long-operator-chains.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<div id="numbers"><i>3</i><i>7</i><i>x</i><b>5</b><b>y</b><u>4</u><u>4</u><s>q</s></div>+<script>+ test(() => {+ const evaluate = expression => {+ const result = document.evaluate(expression, document, null, XPathResult.ANY_TYPE);+ if (result.resultType === XPathResult.NUMBER_TYPE)+ return result.numberValue;+ return result.booleanValue;+ };++ // A chain of operators is as deep a tree as it is long.+ println(`sum: ${evaluate("1" + " + 1".repeat(200000))}`);+ println(`or: ${evaluate("0" + " or 0".repeat(200000) + " or 1")}`);+ println(`union: ${evaluate("count(//i" + " | //b".repeat(200000) + ")")}`);++ for (const expression of [+ "1 - 2 - 3",+ "8 div 2 div 2",+ "1 + 2 * 3 - 4",+ "3 > 2 > 1",+ "0 or 1 and 0",+ "round(0.49999999999999994)",+ "round(-1.5)",+ "round(4503599627370497)",+ "//i < //b",+ "//i > //b",+ "//s < //i",+ "//u < //u",+ "//u <= //u",+ "//u != //u",+ "//i != //i",+ "//u != //s",+ "//u = //i",+ "//missing != //u",+ ])+ println(`${expression}: ${evaluate(expression)}`);+ });+</script>