Skip to content

Truly independent web browser

LibWeb: Scan fragments for the fast path in Rust, in one pass

Andreas Klingc23c2039ef10
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 799035054f6..47c50991cd5 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -107,13 +107,6 @@ static Utf16FlyString utf16_fly_string_from_ffi(u16 const* ptr, size_t len)
return Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(ptr), len });
}
-static Utf16String utf16_string_from_span(ReadonlySpan<char> utf8)
-{
- if (utf8.is_empty())
- return {};
- return Utf16String::from_utf8_without_validation({ utf8.data(), utf8.size() });
-}
-
static Utf16String utf16_string_from_span(ReadonlySpan<char16_t> utf16)
{
if (utf16.is_empty())
@@ -1531,329 +1524,128 @@ DOM::Document& HTMLParser::document()
return *m_document;
}
-namespace {
-
-// Attribute names are ASCII, since the scanner only accepts lowercase ASCII letters, digits and hyphens in names.
-template<typename CharT>
-struct FragmentAttribute {
- ReadonlySpan<CharT> name;
- ReadonlySpan<CharT> value;
-};
-
-template<typename CharT>
-bool fragment_span_equals(ReadonlySpan<CharT> span, StringView ascii)
+// The whitespace the tree builder drops before the html element.
+static constexpr bool is_fragment_whitespace(u32 code_unit)
{
- if (span.size() != ascii.length())
- return false;
- for (size_t i = 0; i < span.size(); ++i) {
- if (span[i] != static_cast<CharT>(ascii[i]))
- return false;
- }
- return true;
+ return code_unit == ' ' || code_unit == '\t' || code_unit == '\n' || code_unit == '\f';
}
-Utf16FlyString const* supported_fragment_tag(StringView name)
-{
- // Keep this subset deliberately small. Adding a tag requires checking its in-body tree-builder rules,
- // its insertion steps, and interactions with every other supported tag. A supported tag must not have children
- // changed steps, since the fast path links children below a new element without running them.
- if (name == "a"sv)
- return &TagNames::a;
- if (name == "b"sv)
- return &TagNames::b;
- if (name == "br"sv)
- return &TagNames::br;
- if (name == "button"sv)
- return &TagNames::button;
- if (name == "div"sv)
- return &TagNames::div;
- if (name == "footer"sv)
- return &TagNames::footer;
- if (name == "i"sv)
- return &TagNames::i;
- if (name == "input"sv)
- return &TagNames::input;
- if (name == "label"sv)
- return &TagNames::label;
- if (name == "li"sv)
- return &TagNames::li;
- if (name == "ol"sv)
- return &TagNames::ol;
- if (name == "span"sv)
- return &TagNames::span;
- if (name == "strong"sv)
- return &TagNames::strong;
- if (name == "ul"sv)
- return &TagNames::ul;
- if (name == "article"sv)
- return &TagNames::article;
- if (name == "aside"sv)
- return &TagNames::aside;
- if (name == "header"sv)
- return &TagNames::header;
- if (name == "main"sv)
- return &TagNames::main;
- if (name == "nav"sv)
- return &TagNames::nav;
- if (name == "section"sv)
- return &TagNames::section;
- if (name == "big"sv)
- return &TagNames::big;
- if (name == "code"sv)
- return &TagNames::code;
- if (name == "em"sv)
- return &TagNames::em;
- if (name == "s"sv)
- return &TagNames::s;
- if (name == "small"sv)
- return &TagNames::small;
- if (name == "strike"sv)
- return &TagNames::strike;
- if (name == "tt"sv)
- return &TagNames::tt;
- if (name == "u"sv)
- return &TagNames::u;
- return nullptr;
-}
+static void insert_node_for_parser(DOM::Node& parent, DOM::Node& node, DOM::Node* child);
-template<typename CharT>
-Utf16FlyString const* supported_fragment_tag(ReadonlySpan<CharT> name)
-{
- if constexpr (IsSame<CharT, char>) {
- return supported_fragment_tag(StringView { name.data(), name.size() });
- } else {
- // Supported tag names are ASCII and short.
- Array<char, 8> ascii_name;
- if (name.size() > ascii_name.size())
- return nullptr;
- for (size_t i = 0; i < name.size(); ++i) {
- if (!is_ascii(name[i]))
- return nullptr;
- ascii_name[i] = static_cast<char>(name[i]);
- }
- return supported_fragment_tag(StringView { ascii_name.data(), name.size() });
- }
-}
+namespace {
-// The whitespace the scanner skips between attributes and the tree builder drops before the html element.
-constexpr bool is_fragment_whitespace(u32 code_unit)
-{
- return code_unit == ' ' || code_unit == '\t' || code_unit == '\n' || code_unit == '\f';
-}
+// What the scanner of the fragment fast path made of some markup: the operations that build its nodes. The markup
+// has to stay where it is for as long as this is around, since the operations refer to ranges of it.
+class ScannedFragment {
+ AK_MAKE_NONCOPYABLE(ScannedFragment);
-template<typename CharT>
-class FragmentScanner {
public:
- explicit FragmentScanner(ReadonlySpan<CharT> input)
- : m_input(input)
+ // Scans input, which gives nothing if it has anything in it that needs the general parser.
+ static Optional<ScannedFragment> scan(Utf16View input)
{
+ auto scan = rust_html_fragment_scan(utf16_view_to_ffi(input));
+ if (!scan.tape)
+ return {};
+ return ScannedFragment { input, scan };
}
- template<typename Open, typename Close, typename Text>
- bool parse(Open&& open, Close&& close, Text&& text)
+ ScannedFragment(ScannedFragment&& other)
+ : m_input(other.m_input)
+ , m_scan(exchange(other.m_scan, {}))
{
- Vector<Utf16FlyString const*, 32> stack;
- Vector<FragmentAttribute<CharT>, 16> attributes;
- while (m_offset < m_input.size()) {
- if (peek() != '<') {
- auto start = m_offset;
- while (m_offset < m_input.size() && peek() != '<') {
- if (!consume_data_code_point())
- return false;
- }
- text(m_input.slice(start, m_offset - start));
- continue;
- }
- ++m_offset;
- bool is_end_tag = consume('/');
- auto name = scan_name();
- auto* tag = supported_fragment_tag(name);
- if (!tag)
- return false;
- if (is_end_tag) {
- skip_whitespace();
- if (!consume('>') || stack.is_empty() || stack.take_last() != tag)
- return false;
- close();
- continue;
- }
-
- // Leave implicit closing of anchors, buttons, and list items to the general parser.
- if ((tag == &TagNames::a || tag == &TagNames::button) && stack.contains_slow(tag))
- return false;
- if (tag == &TagNames::li) {
- for (size_t i = stack.size(); i > 0; --i) {
- auto* ancestor = stack[i - 1];
- if (ancestor == &TagNames::li)
- return false;
- // A nested list stops the in-body rule from closing an outer list item.
- if (ancestor == &TagNames::ul || ancestor == &TagNames::ol)
- break;
- }
- }
- if (stack.size() >= 128)
- return false;
-
- attributes.clear_with_capacity();
- while (true) {
- skip_whitespace();
- if (peek() == '>' || peek() == '/')
- break;
- auto attribute_name = scan_name();
- if (attribute_name.is_empty() || fragment_span_equals(attribute_name, "is"sv) || attributes.size() >= 64)
- return false;
- for (auto const& attribute : attributes) {
- if (attribute.name == attribute_name)
- return false;
- }
- skip_whitespace();
- ReadonlySpan<CharT> value;
- if (consume('=')) {
- skip_whitespace();
- CharT quote = peek();
- if (quote != '\'' && quote != '"')
- return false;
- ++m_offset;
- auto start = m_offset;
- while (m_offset < m_input.size() && peek() != quote) {
- if (!consume_data_code_point())
- return false;
- }
- value = m_input.slice(start, m_offset - start);
- if (!consume(quote))
- return false;
- }
- if (tag == &TagNames::input && fragment_span_equals(attribute_name, "type"sv) && !fragment_span_equals(value, "text"sv) && !fragment_span_equals(value, "checkbox"sv))
- return false;
- attributes.append({ attribute_name, value });
- }
- bool is_void = tag == &TagNames::br || tag == &TagNames::input;
- if (consume('/') && !is_void)
- return false;
- if (!consume('>'))
- return false;
- open(*tag, attributes.span(), is_void);
- if (!is_void)
- stack.append(tag);
- }
- return stack.is_empty();
}
-private:
- CharT peek() const { return m_offset < m_input.size() ? m_input[m_offset] : '\0'; }
+ ~ScannedFragment()
+ {
+ if (m_scan.tape)
+ rust_html_fragment_tape_release(m_scan.tape);
+ }
- // Consumes one code point of text or of an attribute value, unless it needs the general parser.
- bool consume_data_code_point()
+ // Builds the nodes for parsing in context, and appends the ones without a parent to top_level_nodes.
+ void build_into_detached_nodes(DOM::Element& context, GC::RootVector<GC::Ref<DOM::Node>>& top_level_nodes) const
{
- auto ch = peek();
- // Character references and input preprocessing use the general parser.
- if (ch == '&' || ch == '\r' || ch == '\0')
- return false;
- if constexpr (IsSame<CharT, char16_t>) {
- // The general parser replaces a lone surrogate with U+FFFD.
- if (AK::UnicodeUtils::is_utf16_low_surrogate(ch))
- return false;
- if (AK::UnicodeUtils::is_utf16_high_surrogate(ch)) {
- if (m_offset + 1 == m_input.size() || !AK::UnicodeUtils::is_utf16_low_surrogate(m_input[m_offset + 1]))
- return false;
- ++m_offset;
+ auto& document = context.document();
+ auto registry = look_up_a_custom_element_registry(context);
+ GC::RootVector<GC::Ref<DOM::Node>, 32> parents;
+ auto append = [&](GC::Ref<DOM::Node> node) {
+ if (parents.is_empty())
+ top_level_nodes.append(node);
+ else
+ parents.last()->parser_append_child_without_insertion_steps(node);
+ };
+
+ ReadonlySpan<RustFfiHtmlFragmentOperation> operations { m_scan.operations, m_scan.operation_count };
+ ReadonlySpan<RustFfiHtmlFragmentAttribute> attributes { m_scan.attributes, m_scan.attribute_count };
+ for (auto const& operation : operations) {
+ switch (operation.kind) {
+ case RustFfiHtmlFragmentOperationKind::OpenElement:
+ case RustFfiHtmlFragmentOperationKind::AppendVoidElement: {
+ auto element = MUST(DOM::create_element(document, Utf16FlyString::from_raw(operation.tag_name), Namespace::HTML, {}, {}, false, registry));
+ element->ensure_attribute_capacity(operation.length);
+ for (auto const& attribute : attributes.slice(operation.start, operation.length)) {
+ auto is_ascii = attribute.value_is_ascii ? IsKnownToBeASCII::Yes : IsKnownToBeASCII::No;
+ auto value = with_code_units(attribute.value_start, attribute.value_length, [&](auto code_units) {
+ return utf16_string_from_span(code_units, is_ascii);
+ });
+ element->append_attribute(DOM::QualifiedName { attribute_name(attribute), {}, {} }, move(value));
+ }
+ auto& html_element = as<HTMLElement>(*element);
+ if (html_element.is_form_associated_element() && html_element.is_resettable())
+ html_element.reset_algorithm();
+ append(element);
+ if (operation.kind == RustFfiHtmlFragmentOperationKind::OpenElement)
+ parents.append(element);
+ break;
+ }
+ case RustFfiHtmlFragmentOperationKind::CloseElement:
+ parents.take_last();
+ break;
+ case RustFfiHtmlFragmentOperationKind::AppendText: {
+ auto is_ascii = operation.is_ascii ? IsKnownToBeASCII::Yes : IsKnownToBeASCII::No;
+ auto data = with_code_units(operation.start, operation.length, [&](auto code_units) {
+ return text_node_data_from_span(code_units, is_ascii);
+ });
+ append(DOM::Text::create(document, move(data)));
+ break;
+ }
}
}
- ++m_offset;
- return true;
}
- bool consume(CharT ch)
+private:
+ ScannedFragment(Utf16View input, RustFfiHtmlFragmentScan scan)
+ : m_input(input)
+ , m_scan(scan)
{
- if (m_offset == m_input.size() || peek() != ch)
- return false;
- ++m_offset;
- return true;
}
- void skip_whitespace()
+ template<typename Callback>
+ Utf16String with_code_units(size_t start, size_t length, Callback&& callback) const
{
- while (is_fragment_whitespace(peek()))
- ++m_offset;
+ if (m_input.has_latin1_storage())
+ return callback(m_input.latin1_span().slice(start, length));
+ return callback(m_input.utf16_span().slice(start, length));
}
- ReadonlySpan<CharT> scan_name()
+ Utf16FlyString attribute_name(RustFfiHtmlFragmentAttribute const& attribute) const
{
- auto start = m_offset;
- while (is_ascii_lower_alpha(peek()) || is_ascii_digit(peek()) || peek() == '-')
- ++m_offset;
- return m_input.slice(start, m_offset - start);
+ if (attribute.known_name)
+ return Utf16FlyString::from_raw(attribute.known_name);
+ // NB: The scanner only takes names of lowercase ASCII letters, digits and hyphens.
+ if (m_input.has_latin1_storage()) {
+ auto name = m_input.latin1_span().slice(attribute.name_start, attribute.name_length);
+ return Utf16FlyString::from_utf8_without_validation({ name.data(), name.size() });
+ }
+ auto name = m_input.utf16_span().slice(attribute.name_start, attribute.name_length);
+ return Utf16FlyString::from_utf16({ name.data(), name.size() });
}
- ReadonlySpan<CharT> m_input;
- size_t m_offset { 0 };
+ Utf16View m_input;
+ RustFfiHtmlFragmentScan m_scan;
};
}
-static void insert_node_for_parser(DOM::Node& parent, DOM::Node& node, DOM::Node* child);
-
-template<typename CharT>
-static bool can_parse_fragment_fast(ReadonlySpan<CharT> source)
-{
- return FragmentScanner<CharT> { source }.parse([](auto const&, auto, bool) { }, [] { }, [](auto) { });
-}
-
-// Builds the nodes of source, which can_parse_fragment_fast() has accepted, for parsing in context.
-template<typename CharT>
-static void build_fast_fragment_into_detached_nodes(DOM::Element& context, ReadonlySpan<CharT> source, GC::RootVector<GC::Ref<DOM::Node>>& top_level_nodes)
-{
- auto& document = context.document();
- auto registry = look_up_a_custom_element_registry(context);
- GC::RootVector<GC::Ref<DOM::Node>, 32> parents;
- auto append = [&](GC::Ref<DOM::Node> node) {
- if (parents.is_empty())
- top_level_nodes.append(node);
- else
- parents.last()->parser_append_child_without_insertion_steps(node);
- };
- auto success = FragmentScanner<CharT> { source }.parse(
- [&](Utf16FlyString const& tag, ReadonlySpan<FragmentAttribute<CharT>> attributes, bool is_void) {
- auto element = MUST(DOM::create_element(document, tag, Namespace::HTML, {}, {}, false, registry));
- element->ensure_attribute_capacity(attributes.size());
- for (auto const& attribute : attributes) {
- Utf16FlyString local_name;
- if constexpr (IsSame<CharT, char>)
- local_name = Utf16FlyString::from_utf8_without_validation({ attribute.name.data(), attribute.name.size() });
- else
- local_name = Utf16FlyString::from_utf16({ attribute.name.data(), attribute.name.size() });
- element->append_attribute(DOM::QualifiedName { move(local_name), {}, {} }, utf16_string_from_span(attribute.value));
- }
- auto& html_element = as<HTMLElement>(*element);
- if (html_element.is_form_associated_element() && html_element.is_resettable())
- html_element.reset_algorithm();
- append(element);
- if (!is_void)
- parents.append(element);
- },
- [&] { parents.take_last(); },
- [&](ReadonlySpan<CharT> text) {
- append(DOM::Text::create(document, text_node_data_from_span(text)));
- });
- VERIFY(success);
-}
-
-template<typename Callback>
-static decltype(auto) with_code_unit_span(Utf16View input, Callback&& callback)
-{
- if (input.has_ascii_storage())
- return callback(ReadonlySpan<char> { input.ascii_span().data(), input.length_in_code_units() });
- // NB: The fast path makes UTF-8 strings of one-byte spans, so Latin-1 is parsed as UTF-16.
- if (input.has_latin1_storage()) {
- Vector<char16_t> code_units;
- code_units.ensure_capacity(input.length_in_code_units());
- for (auto byte : input.latin1_span())
- code_units.unchecked_append(byte);
- return callback(ReadonlySpan<char16_t> { code_units.data(), code_units.size() });
- }
- return callback(input.utf16_span());
-}
-
static bool can_parse_fragment_fast_in_context(DOM::Element const& context)
{
if (context.namespace_uri() != Namespace::HTML || context.document().is_xml_document())
@@ -1866,9 +1658,10 @@ static bool can_parse_fragment_fast_in_context(DOM::Element const& context)
bool HTMLParser::try_parse_html_fragment_fast_into_detached_nodes(DOM::Element& context, Utf16View input, GC::RootVector<GC::Ref<DOM::Node>>& top_level_nodes)
{
- // OPTIMIZATION: Validate a restricted in-body grammar before allocating or exposing any DOM nodes. The second
- // pass borrows input spans and constructs elements directly, bypassing tokenization and tree building.
- // All unsupported syntax falls back without side effects, including custom elements and foreign content.
+ // OPTIMIZATION: Scan the markup for a restricted in-body grammar before allocating or exposing any DOM nodes. The
+ // scan writes down the nodes to make, which are then constructed directly from ranges of the input,
+ // bypassing tokenization and tree building. All unsupported syntax falls back without side effects,
+ // including custom elements and foreign content.
// Like Blink and WebKit, only link the nodes below each top-level node without running the insertion
// steps. The caller inserts the top-level nodes, which runs the insertion steps for every node once.
// Nothing can observe the skipped steps: the nodes are new, so no script, observer, live range or
@@ -1876,12 +1669,11 @@ bool HTMLParser::try_parse_html_fragment_fast_into_detached_nodes(DOM::Element&
VERIFY(top_level_nodes.is_empty());
if (!can_parse_fragment_fast_in_context(context))
return false;
- return with_code_unit_span(input, [&](auto source) {
- if (!can_parse_fragment_fast(source))
- return false;
- build_fast_fragment_into_detached_nodes(context, source, top_level_nodes);
- return true;
- });
+ auto fragment = ScannedFragment::scan(input);
+ if (!fragment.has_value())
+ return false;
+ fragment->build_into_detached_nodes(context, top_level_nodes);
+ return true;
}
bool HTMLParser::try_parse_document_fast(DOM::Document& document, Utf16View input)
@@ -1904,8 +1696,8 @@ bool HTMLParser::try_parse_document_fast(DOM::Document& document, Utf16View inpu
++content_start;
auto content = input.substring_view(content_start);
- auto can_parse_content = with_code_unit_span(content, [](auto source) { return can_parse_fragment_fast(source); });
- if (!can_parse_content)
+ auto scanned_content = ScannedFragment::scan(content);
+ if (!scanned_content.has_value())
return false;
// NB: These are what creating the parser for a decoded string and running it would have set.
@@ -1925,7 +1717,7 @@ bool HTMLParser::try_parse_document_fast(DOM::Document& document, Utf16View inpu
VERIFY(can_parse_fragment_fast_in_context(body));
GC::RootVector<GC::Ref<DOM::Node>> body_children;
- with_code_unit_span(content, [&](auto source) { build_fast_fragment_into_detached_nodes(*body, source, body_children); });
+ scanned_content->build_into_detached_nodes(*body, body_children);
for (auto child : body_children)
insert_node_for_parser(body, child, nullptr);
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/build.rs b/Libraries/LibWeb/HTML/Parser/Rust/build.rs
index 1e11a0a78c0..57cf41f243a 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/build.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/build.rs
@@ -402,6 +402,7 @@ fn emit_known_names(
);
out.push_str("}\npub(crate) use attribute_name;\n");
emit_tag_ids(&mut out, &[tag_names, svg_tag_names, mathml_tag_names]);
+ emit_known_attribute_name_lookup(&mut out, attribute_names);
fs::write(out_path, out).expect("Failed to write known_names_generated.rs");
}
@@ -452,6 +453,32 @@ fn emit_tag_ids(out: &mut String, tag_name_lists: &[&[(String, String)]]) {
out.push_str(" _ => crate::token::TagId::UNKNOWN,\n }\n}\n");
}
+/// Emits `known_attribute_name`, which finds the known attribute name that has the bytes it is given.
+fn emit_known_attribute_name_lookup(out: &mut String, attribute_names: &[(String, String)]) {
+ let names: std::collections::BTreeSet<&str> = attribute_names.iter().map(|(_, name)| name.as_str()).collect();
+ // NB: As with tag names, the length and first byte of a name leave only a few known names to compare it with.
+ let mut by_length_and_first_byte = std::collections::BTreeMap::<(usize, u8), Vec<&str>>::new();
+ for name in names {
+ by_length_and_first_byte
+ .entry((name.len(), name.as_bytes()[0]))
+ .or_default()
+ .push(name);
+ }
+ out.push_str("\npub(crate) fn known_attribute_name(name: &[u8]) -> Option<crate::token::KnownName> {\n");
+ out.push_str(" let &first_byte = name.first()?;\n");
+ out.push_str(" match (name.len(), first_byte) {\n");
+ for ((length, first_byte), names) in &by_length_and_first_byte {
+ out.push_str(&format!(" ({length}, {first_byte}) => match name {{\n"));
+ for name in names {
+ out.push_str(&format!(
+ " b\"{name}\" => Some(attribute_name!(\"{name}\")),\n"
+ ));
+ }
+ out.push_str(" _ => None,\n },\n");
+ }
+ out.push_str(" _ => None,\n }\n}\n");
+}
+
fn emit_known_name_externs(out: &mut String, names: &[(String, String)], prefix: &str, target_pointer_size: usize) {
for (identifier, name) in names {
if needs_static(name, target_pointer_size) {
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs
new file mode 100644
index 00000000000..97efcc52c48
--- /dev/null
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs
@@ -0,0 +1,627 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The scanner of the fragment fast path.
+//!
+//! Markup given to innerHTML is very often a small subset of what goes in a body: a few kinds of elements, properly
+//! nested, with quoted attribute values and no character references. The scanner reads such markup once and writes
+//! down what the tree builder would have made of it as a flat list of operations, which the host then builds nodes
+//! from without a tokenizer or a tree builder. Anything else is turned down before the host has made a single node,
+//! and goes to the general parser.
+
+use crate::code_units::RustFfiHtmlUtf16View;
+use crate::known_names::known_attribute_name;
+use crate::known_names::tag_id;
+use crate::known_names::tag_id_for_name;
+use crate::scan;
+use crate::scan::CodeUnit;
+use crate::token::TagId;
+use crate::token::TagSet;
+use crate::token::tag_set;
+use std::cell::Cell;
+
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum RustFfiHtmlFragmentOperationKind {
+ /// Make an element and the attributes at `start..start + length` of the attribute list, and append it to the
+ /// innermost open element. It is then the innermost open element.
+ OpenElement,
+ /// The same for an element that takes no children, which is not left open.
+ AppendVoidElement,
+ /// Close the innermost open element.
+ CloseElement,
+ /// Append a text node with the code units at `start..start + length` of the input.
+ AppendText,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct RustFfiHtmlFragmentOperation {
+ pub kind: RustFfiHtmlFragmentOperationKind,
+ /// Whether the text of `AppendText` is all ASCII.
+ pub is_ascii: bool,
+ pub start: u32,
+ pub length: u32,
+ /// The identity of the `Utf16FlyString` with the local name of the element to make.
+ pub tag_name: usize,
+}
+
+/// An attribute of an element to make. The name and the value are ranges of code units of the input.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct RustFfiHtmlFragmentAttribute {
+ /// The identity of the `Utf16FlyString` with the name if it is one the engine knows, and otherwise 0.
+ pub known_name: usize,
+ pub name_start: u32,
+ pub name_length: u32,
+ pub value_start: u32,
+ pub value_length: u32,
+ pub value_is_ascii: bool,
+}
+
+/// What the scanner made of a fragment. `tape` is null if the fragment is not for the fast path, and otherwise must
+/// be given to `rust_html_fragment_tape_release` once the operations have been read.
+#[repr(C)]
+pub struct RustFfiHtmlFragmentScan {
+ pub tape: *mut RustHtmlFragmentTape,
+ pub operations: *const RustFfiHtmlFragmentOperation,
+ pub operation_count: usize,
+ pub attributes: *const RustFfiHtmlFragmentAttribute,
+ pub attribute_count: usize,
+}
+
+#[derive(Default)]
+pub struct RustHtmlFragmentTape {
+ operations: Vec<RustFfiHtmlFragmentOperation>,
+ attributes: Vec<RustFfiHtmlFragmentAttribute>,
+ open_elements: Vec<TagId>,
+}
+
+thread_local! {
+ // NB: One tape is kept between fragments, so that scanning a fragment does not allocate.
+ static SPARE_TAPE: Cell<Option<Box<RustHtmlFragmentTape>>> = const { Cell::new(None) };
+}
+
+// NB: A tape that an unusually large fragment grew past these sizes is freed, so that the spare one stays small.
+const MAX_SPARE_TAPE_OPERATIONS: usize = 4096;
+const MAX_SPARE_TAPE_ATTRIBUTES: usize = 4096;
+
+fn keep_as_spare_tape(tape: Box<RustHtmlFragmentTape>) {
+ if tape.operations.capacity() <= MAX_SPARE_TAPE_OPERATIONS
+ && tape.attributes.capacity() <= MAX_SPARE_TAPE_ATTRIBUTES
+ {
+ SPARE_TAPE.set(Some(tape));
+ }
+}
+
+/// Scans a fragment for the fast path.
+///
+/// # Safety
+/// `input` must point at `input.length` readable code units.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_html_fragment_scan(input: RustFfiHtmlUtf16View) -> RustFfiHtmlFragmentScan {
+ let mut tape = SPARE_TAPE.take().unwrap_or_default();
+ // SAFETY: The caller promises that `input` points at `input.length` code units.
+ let accepted = unsafe {
+ if input.length == 0 {
+ scan::<u8>(&[], &mut tape)
+ } else if !input.latin1.is_null() {
+ scan(ak::slice_from_raw_parts(input.latin1, input.length), &mut tape)
+ } else {
+ scan(ak::slice_from_raw_parts(input.utf16, input.length), &mut tape)
+ }
+ };
+ if !accepted {
+ keep_as_spare_tape(tape);
+ return RustFfiHtmlFragmentScan {
+ tape: std::ptr::null_mut(),
+ operations: std::ptr::null(),
+ operation_count: 0,
+ attributes: std::ptr::null(),
+ attribute_count: 0,
+ };
+ }
+ RustFfiHtmlFragmentScan {
+ operations: tape.operations.as_ptr(),
+ operation_count: tape.operations.len(),
+ attributes: tape.attributes.as_ptr(),
+ attribute_count: tape.attributes.len(),
+ tape: Box::into_raw(tape),
+ }
+}
+
+/// Gives back the tape of a scan whose operations have been read.
+///
+/// # Safety
+/// `tape` must be the tape of a `RustFfiHtmlFragmentScan` that has not been released yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_html_fragment_tape_release(tape: *mut RustHtmlFragmentTape) {
+ // SAFETY: The caller promises that `tape` came from `rust_html_fragment_scan` and is released once.
+ keep_as_spare_tape(unsafe { Box::from_raw(tape) });
+}
+
+/// Defines the tags the fast path takes, and the fly string of each.
+///
+/// Keep this subset deliberately small. Adding a tag requires checking its in-body tree-builder rules, its insertion
+/// steps, and interactions with every other supported tag. A supported tag must not have children changed steps,
+/// since the host links children below a new element without running them.
+macro_rules! supported_tags {
+ ($($name:tt),+ $(,)?) => {
+ const SUPPORTED_TAGS: &TagSet = tag_set![$($name),+];
+
+ /// The identity of the `Utf16FlyString` of every supported tag, by tag id.
+ #[cfg(not(test))]
+ fn tag_names() -> &'static [usize; TAG_ID_COUNT] {
+ static TAG_NAMES: std::sync::OnceLock<[usize; TAG_ID_COUNT]> = std::sync::OnceLock::new();
+ TAG_NAMES.get_or_init(|| {
+ let mut tag_names = [0; TAG_ID_COUNT];
+ $(tag_names[tag_id!($name).index()] = crate::known_names::tag_name!($name).raw_identity();)+
+ tag_names
+ })
+ }
+ };
+}
+
+#[cfg(not(test))]
+const TAG_ID_COUNT: usize = crate::known_names::TAG_SET_WORD_COUNT * 64;
+
+supported_tags![
+ "a", "article", "aside", "b", "big", "br", "button", "code", "div", "em", "footer", "header", "i", "input",
+ "label", "li", "main", "nav", "ol", "s", "section", "small", "span", "strike", "strong", "tt", "u", "ul",
+];
+
+const MAX_OPEN_ELEMENTS: usize = 128;
+const MAX_ATTRIBUTES: usize = 64;
+
+/// The whitespace between the parts of a tag.
+fn is_tag_whitespace(code_unit: u16) -> bool {
+ matches!(code_unit, 0x09 | 0x0A | 0x0C | 0x20)
+}
+
+fn equals_ascii<T: CodeUnit>(code_units: &[T], ascii: &[u8]) -> bool {
+ code_units.len() == ascii.len()
+ && code_units
+ .iter()
+ .zip(ascii)
+ .all(|(&code_unit, &byte)| code_unit.into() == u16::from(byte))
+}
+
+/// The bytes of a name the scanner has read, which is ASCII, if it fits in `buffer`.
+fn name_bytes<'a, T: CodeUnit>(name: &[T], buffer: &'a mut [u8; 32]) -> Option<&'a [u8]> {
+ let bytes = buffer.get_mut(..name.len())?;
+ for (byte, &code_unit) in bytes.iter_mut().zip(name) {
+ *byte = code_unit.into() as u8;
+ }
+ Some(bytes)
+}
+
+fn scan<T: CodeUnit>(input: &[T], tape: &mut RustHtmlFragmentTape) -> bool {
+ tape.operations.clear();
+ tape.attributes.clear();
+ tape.open_elements.clear();
+ // NB: The tape has offsets into the input as 32-bit numbers.
+ if u32::try_from(input.len()).is_err() {
+ return false;
+ }
+ Scanner {
+ input,
+ offset: 0,
+ #[cfg(not(test))]
+ tag_names: tag_names(),
+ tape,
+ }
+ .scan()
+}
+
+struct Scanner<'a, T> {
+ input: &'a [T],
+ offset: usize,
+ #[cfg(not(test))]
+ tag_names: &'static [usize; TAG_ID_COUNT],
+ tape: &'a mut RustHtmlFragmentTape,
+}
+
+impl<'a, T: CodeUnit> Scanner<'a, T> {
+ fn scan(&mut self) -> bool {
+ while self.offset < self.input.len() {
+ let scanned = if self.peek() != u16::from(b'<') {
+ self.scan_text()
+ } else {
+ self.offset += 1;
+ if self.consume(b'/') {
+ self.scan_end_tag()
+ } else {
+ self.scan_start_tag()
+ }
+ };
+ if !scanned {
+ return false;
+ }
+ }
+ self.tape.open_elements.is_empty()
+ }
+
+ fn scan_text(&mut self) -> bool {
+ // NB: Character references and input preprocessing use the general parser, which also replaces a surrogate
+ // that isn't half of a pair with U+FFFD. The run ends at all of those, so it has to end at a tag or at the
+ // end of the input.
+ let run = scan::data_run(&self.input[self.offset..]);
+ let end = self.offset + run.length;
+ if end < self.input.len() && self.input[end].into() != u16::from(b'<') {
+ return false;
+ }
+ self.tape.operations.push(RustFfiHtmlFragmentOperation {
+ kind: RustFfiHtmlFragmentOperationKind::AppendText,
+ is_ascii: run.is_ascii,
+ start: self.offset as u32,
+ length: run.length as u32,
+ tag_name: 0,
+ });
+ self.offset = end;
+ true
+ }
+
+ fn scan_end_tag(&mut self) -> bool {
+ let Some(tag) = self.scan_supported_tag() else {
+ return false;
+ };
+ self.skip_whitespace();
+ if !self.consume(b'>') || self.tape.open_elements.pop() != Some(tag) {
+ return false;
+ }
+ self.tape.operations.push(RustFfiHtmlFragmentOperation {
+ kind: RustFfiHtmlFragmentOperationKind::CloseElement,
+ is_ascii: false,
+ start: 0,
+ length: 0,
+ tag_name: 0,
+ });
+ true
+ }
+
+ fn scan_start_tag(&mut self) -> bool {
+ let Some(tag) = self.scan_supported_tag() else {
+ return false;
+ };
+ let open_elements = &self.tape.open_elements;
+
+ // Leave implicit closing of anchors, buttons, and list items to the general parser.
+ if (tag == tag_id!("a") || tag == tag_id!("button")) && open_elements.contains(&tag) {
+ return false;
+ }
+ if tag == tag_id!("li") {
+ for &ancestor in open_elements.iter().rev() {
+ if ancestor == tag_id!("li") {
+ return false;
+ }
+ // A nested list stops the in-body rule from closing an outer list item.
+ if ancestor == tag_id!("ul") || ancestor == tag_id!("ol") {
+ break;
+ }
+ }
+ }
+ if open_elements.len() >= MAX_OPEN_ELEMENTS {
+ return false;
+ }
+
+ let first_attribute = self.tape.attributes.len();
+ loop {
+ self.skip_whitespace();
+ if self.peek() == u16::from(b'>') || self.peek() == u16::from(b'/') {
+ break;
+ }
+ if !self.scan_attribute(tag, first_attribute) {
+ return false;
+ }
+ }
+
+ let is_void = tag == tag_id!("br") || tag == tag_id!("input");
+ if self.consume(b'/') && !is_void {
+ return false;
+ }
+ if !self.consume(b'>') {
+ return false;
+ }
+
+ self.tape.operations.push(RustFfiHtmlFragmentOperation {
+ kind: if is_void {
+ RustFfiHtmlFragmentOperationKind::AppendVoidElement
+ } else {
+ RustFfiHtmlFragmentOperationKind::OpenElement
+ },
+ is_ascii: false,
+ start: first_attribute as u32,
+ length: (self.tape.attributes.len() - first_attribute) as u32,
+ tag_name: self.tag_name(tag),
+ });
+ if !is_void {
+ self.tape.open_elements.push(tag);
+ }
+ true
+ }
+
+ /// Scans one attribute of a start tag of `tag`, whose attributes so far start at `first_attribute`.
+ fn scan_attribute(&mut self, tag: TagId, first_attribute: usize) -> bool {
+ let input = self.input;
+ let name_start = self.offset;
+ let name = self.scan_name();
+ // NB: Customized built-in elements are made by the general parser.
+ if name.is_empty()
+ || equals_ascii(name, b"is")
+ || self.tape.attributes.len() - first_attribute >= MAX_ATTRIBUTES
+ {
+ return false;
+ }
+ // NB: The tokenizer drops an attribute whose name the tag already has, which the general parser sees to.
+ let is_duplicate = self.tape.attributes[first_attribute..].iter().any(|attribute| {
+ let start = attribute.name_start as usize;
+ input[start..start + attribute.name_length as usize] == *name
+ });
+ if is_duplicate {
+ return false;
+ }
+
+ self.skip_whitespace();
+ let mut value = scan::Run {
+ length: 0,
+ is_ascii: true,
+ };
+ let mut value_start = self.offset;
+ if self.consume(b'=') {
+ self.skip_whitespace();
+ let quote = self.peek();
+ if quote != u16::from(b'\'') && quote != u16::from(b'"') {
+ return false;
+ }
+ self.offset += 1;
+ value_start = self.offset;
+ // NB: As with text, the run ends at everything that the general parser has to see to, so it has to end at
+ // the closing quote.
+ value = scan::quoted_attribute_value_run(&input[value_start..], quote as u8);
+ self.offset = value_start + value.length;
+ if !self.consume(quote as u8) {
+ return false;
+ }
+ }
+
+ // NB: Other input types have insertion steps or children the fast path doesn't cover.
+ let value_code_units = &input[value_start..value_start + value.length];
+ if tag == tag_id!("input")
+ && equals_ascii(name, b"type")
+ && !equals_ascii(value_code_units, b"text")
+ && !equals_ascii(value_code_units, b"checkbox")
+ {
+ return false;
+ }
+
+ self.tape.attributes.push(RustFfiHtmlFragmentAttribute {
+ known_name: known_attribute_name_identity(name),
+ name_start: name_start as u32,
+ name_length: name.len() as u32,
+ value_start: value_start as u32,
+ value_length: value.length as u32,
+ value_is_ascii: value.is_ascii,
+ });
+ true
+ }
+
+ fn scan_supported_tag(&mut self) -> Option<TagId> {
+ let name = self.scan_name();
+ let tag = tag_id_for_name(name_bytes(name, &mut [0; 32])?);
+ (tag != TagId::UNKNOWN && SUPPORTED_TAGS.contains(tag)).then_some(tag)
+ }
+
+ /// Scans a tag name or an attribute name of lowercase ASCII letters, digits and hyphens. Other names are for the
+ /// general parser, which is what finding no name where one has to be leads to.
+ fn scan_name(&mut self) -> &'a [T] {
+ let input = self.input;
+ let start = self.offset;
+ while matches!(self.peek(), 0x61..=0x7A | 0x30..=0x39 | 0x2D) {
+ self.offset += 1;
+ }
+ &input[start..self.offset]
+ }
+
+ fn tag_name(&self, tag: TagId) -> usize {
+ #[cfg(not(test))]
+ {
+ self.tag_names[tag.index()]
+ }
+ // NB: There are no fly strings in the standalone tests, which get the tag id in place of one.
+ #[cfg(test)]
+ {
+ tag.index()
+ }
+ }
+
+ /// The code unit at the offset, or U+0000 NULL at the end of the input. Nothing the scanner takes has a NULL in it.
+ fn peek(&self) -> u16 {
+ self.input.get(self.offset).map_or(0, |&code_unit| code_unit.into())
+ }
+
+ fn consume(&mut self, byte: u8) -> bool {
+ if self.offset == self.input.len() || self.peek() != u16::from(byte) {
+ return false;
+ }
+ self.offset += 1;
+ true
+ }
+
+ fn skip_whitespace(&mut self) {
+ while is_tag_whitespace(self.peek()) {
+ self.offset += 1;
+ }
+ }
+}
+
+fn known_attribute_name_identity<T: CodeUnit>(name: &[T]) -> usize {
+ #[cfg(not(test))]
+ {
+ name_bytes(name, &mut [0; 32])
+ .and_then(known_attribute_name)
+ .map_or(0, |name| name.raw_identity())
+ }
+ // NB: There are no fly strings in the standalone tests, which only tell known names from other names.
+ #[cfg(test)]
+ {
+ usize::from(name_bytes(name, &mut [0; 32]).and_then(known_attribute_name).is_some())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::RustFfiHtmlFragmentOperationKind::*;
+ use super::*;
+
+ /// What the scanner makes of `input`, as one line per operation, or `None` if it turns the input down.
+ fn scan_to_text<T: CodeUnit>(input: &[T]) -> Option<String> {
+ let mut tape = RustHtmlFragmentTape::default();
+ if !scan(input, &mut tape) {
+ return None;
+ }
+ let text_of = |start: u32, length: u32| {
+ let code_units: Vec<u16> = input[start as usize..(start + length) as usize]
+ .iter()
+ .map(|&code_unit| code_unit.into())
+ .collect();
+ String::from_utf16(&code_units).unwrap()
+ };
+ let mut text = String::new();
+ for operation in &tape.operations {
+ match operation.kind {
+ OpenElement | AppendVoidElement => {
+ text.push_str(if operation.kind == OpenElement { "open" } else { "void" });
+ text.push_str(&format!(" #{}", operation.tag_name));
+ let attributes = &tape.attributes[operation.start as usize..][..operation.length as usize];
+ for attribute in attributes {
+ text.push_str(&format!(
+ " {}{}={:?}{}",
+ text_of(attribute.name_start, attribute.name_length),
+ if attribute.known_name != 0 { "!" } else { "" },
+ text_of(attribute.value_start, attribute.value_length),
+ if attribute.value_is_ascii { "" } else { "~" },
+ ));
+ }
+ }
+ CloseElement => text.push_str("close"),
+ AppendText => text.push_str(&format!(
+ "text {:?}{}",
+ text_of(operation.start, operation.length),
+ if operation.is_ascii { "" } else { "~" }
+ )),
+ }
+ text.push('\n');
+ }
+ Some(text)
+ }
+
+ fn scan_str(input: &str) -> Option<String> {
+ let utf16: Vec<u16> = input.encode_utf16().collect();
+ let from_utf16 = scan_to_text(&utf16);
+ if let Some(latin1) = utf16
+ .iter()
+ .map(|&code_unit| u8::try_from(code_unit).ok())
+ .collect::<Option<Vec<u8>>>()
+ {
+ assert_eq!(scan_to_text(&latin1), from_utf16, "Latin-1 and UTF-16 input scan alike");
+ }
+ from_utf16
+ }
+
+ fn accepts(input: &str) -> bool {
+ scan_str(input).is_some()
+ }
+
+ #[test]
+ fn elements_attributes_and_text_become_operations() {
+ let div = tag_id!("div").index();
+ let input = tag_id!("input").index();
+ assert_eq!(
+ scan_str("a<div class=\"x y\" data-id='7' hidden>caf\u{E9}<input type = \"checkbox\" /></div >").unwrap(),
+ format!(
+ "text \"a\"\nopen #{div} class!=\"x y\" data-id=\"7\" hidden!=\"\"\ntext \"caf\u{E9}\"~\n\
+ void #{input} type!=\"checkbox\"\nclose\n"
+ )
+ );
+ assert_eq!(scan_str("").unwrap(), "");
+ assert_eq!(scan_str("x > y").unwrap(), "text \"x > y\"\n");
+ }
+
+ #[test]
+ fn markup_the_tree_builder_takes_as_written_is_accepted() {
+ for input in [
+ "<br>",
+ "<br/>",
+ "<input>",
+ "<li><ul><li></li></ul></li>",
+ "<a><b></b></a><a></a>",
+ "<div title='a<b>\"'></div>",
+ "<div\n\tclass=''\x0C></div\n>",
+ ] {
+ assert!(accepts(input), "{input:?}");
+ }
+ }
+
+ #[test]
+ fn markup_for_the_general_parser_is_turned_down() {
+ for input in [
+ "a &amp; b",
+ "a\rb",
+ "a\0b",
+ "<p>x</p>",
+ "<my-element></my-element>",
+ "<DIV></DIV>",
+ "<div>",
+ "</div>",
+ "<div></span>",
+ "<div/>",
+ "</br>",
+ "<div",
+ "<div class='a",
+ "<div class=a></div>",
+ "<div Class='a'></div>",
+ "<div class='a' class='b'></div>",
+ "<div class='a&amp;b'></div>",
+ "<div class='a\rb'></div>",
+ "<div is='x'></div>",
+ "<a><b><a></a></b></a>",
+ "<button><button></button></button>",
+ "<li><li></li></li>",
+ "<ul><li><b><li></li></b></li></ul>",
+ "<input type='radio'>",
+ "<input type>",
+ "<!-- comment -->",
+ ] {
+ assert!(!accepts(input), "{input:?}");
+ }
+ let too_deep = "<div>".repeat(MAX_OPEN_ELEMENTS + 1) + &"</div>".repeat(MAX_OPEN_ELEMENTS + 1);
+ assert!(!accepts(&too_deep));
+ assert!(accepts(&too_deep["<div>".len()..too_deep.len() - "</div>".len()]));
+ }
+
+ #[test]
+ fn surrogates_are_taken_in_pairs_only() {
+ let code_units = |text: &str, surrogate: &[u16]| {
+ let mut code_units: Vec<u16> = text.encode_utf16().collect();
+ let offset = code_units
+ .iter()
+ .position(|&code_unit| code_unit == u16::from(b'?'))
+ .unwrap();
+ code_units.splice(offset..offset + 1, surrogate.iter().copied());
+ code_units
+ };
+ for text in ["a?b", "<div title='a?b'></div>"] {
+ assert!(scan_to_text(&code_units(text, &[0xD83D, 0xDE00])).is_some());
+ assert!(scan_to_text(&code_units(text, &[0xD83D])).is_none());
+ assert!(scan_to_text(&code_units(text, &[0xDE00])).is_none());
+ assert!(scan_to_text(&code_units(text, &[0xDE00, 0xD83D])).is_none());
+ }
+ assert_eq!(
+ scan_to_text(&code_units("?", &[0xD83D, 0xDE00])).unwrap(),
+ "text \"\u{1F600}\"~\n"
+ );
+ }
+}
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
index 1ea6829f931..9145560a670 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/lib.rs
@@ -6,6 +6,7 @@
pub mod code_units;
pub mod entities;
+pub mod fragment;
mod known_names;
pub mod meta_charset_scanner;
pub mod parser;
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
index 39c7c328a8d..35a8cdd480f 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
@@ -264,6 +264,13 @@ pub fn raw_text_run<T: CodeUnit>(code_units: &[T]) -> Run {
text_run(code_units, [b'<', 0, b'\r'])
}
+/// The number of code units at the start of `code_units` that a quoted attribute value takes as they are, and whether
+/// they are all ASCII: everything up to the first `quote`, U+0026 (&), U+0000 NULL, U+000D CR, or surrogate that isn't
+/// half of a pair.
+pub fn quoted_attribute_value_run<T: CodeUnit>(code_units: &[T], quote: u8) -> Run {
+ text_run(code_units, [quote, b'&', 0, b'\r'])
+}
+
#[inline(always)]
fn text_run<T: CodeUnit, const N: usize>(code_units: &[T], stops: [u8; N]) -> Run {
let mut length = 0;
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs
index cbab7a4f200..7a4a0fef9a2 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/token.rs
@@ -54,6 +54,10 @@ impl TagId {
Self(index)
}
+ pub const fn index(self) -> usize {
+ self.0 as usize
+ }
+
pub fn for_name(name: &str) -> Self {
crate::known_names::tag_id_for_name(name.as_bytes())
}
@@ -253,6 +257,12 @@ impl KnownName {
pub const fn from_literal(name: &'static str) -> Self {
Self::Literal(name)
}
+
+ /// The identity of the C++ `Utf16FlyString` that holds this name.
+ #[cfg(not(test))]
+ pub const fn raw_identity(self) -> usize {
+ self.0
+ }
}
impl HtmlName {
diff --git a/Libraries/LibWeb/HTML/Parser/RustUtf16View.h b/Libraries/LibWeb/HTML/Parser/RustUtf16View.h
index 55bca277deb..eca04555076 100644
--- a/Libraries/LibWeb/HTML/Parser/RustUtf16View.h
+++ b/Libraries/LibWeb/HTML/Parser/RustUtf16View.h
@@ -22,4 +22,12 @@ inline Utf16View utf16_view_from_ffi(RustFfiHtmlUtf16View view)
return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
}
+// A view of code units for the Rust HTML parser to read until the call they are passed to returns.
+inline RustFfiHtmlUtf16View utf16_view_to_ffi(Utf16View view)
+{
+ if (view.has_latin1_storage())
+ return { view.latin1_span().data(), nullptr, view.length_in_code_units() };
+ return { nullptr, reinterpret_cast<u16 const*>(view.utf16_span().data()), view.length_in_code_units() };
+}
+
}
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index abf62729040..f2c8fcbec6a 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -43,6 +43,8 @@ ALLOWED = {
"Libraries/LibJS/JIT/Rust/src/lib.rs:BLOCKS": "per-thread count of the allocator of JIT unit tests, in the cargo test binary that has no runtime",
"Libraries/LibJS/JIT/Rust/src/lib.rs:COUNTING": "per-thread switch of the allocator of JIT unit tests, in the cargo test binary that has no runtime",
"Libraries/LibRegex/Rust/src/vm.rs:INTERRUPT_FLAG": "per-thread, and only libjs_rust's copy sets it; the copy of LibURL's crate has no VM to interrupt, so it only ever sees null",
+ "Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs:SPARE_TAPE": "per-thread allocation pool; a second copy costs memory, never an answer",
+ "Libraries/LibWeb/HTML/Parser/Rust/src/fragment.rs:TAG_NAMES": "immutable table of the C++ fly strings of tag names; each copy reads the same strings",
"Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs:FAKE_DOM": "the fake DOM of tree builder unit tests, in the cargo test binary that has no C++ side",
"Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_LISTS": "per-thread allocation pool; a second copy costs memory, never an answer",
"Libraries/LibWeb/HTML/Parser/Rust/src/token.rs:SPARE_ATTRIBUTE_VALUES": "per-thread allocation pool; a second copy costs memory, never an answer",