Skip to content

Truly independent web browser

LibWeb: Insert parsed text straight from the HTML tokenizer's input

Andreas Klingcbed25162e1b
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index f91f0cf9fb9..1195d39f207 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -120,6 +120,38 @@ static Utf16String utf16_string_from_span(ReadonlySpan<char16_t> utf16)
return Utf16String::from_utf16(Utf16View { utf16.data(), utf16.size() });
}
+enum class IsKnownToBeASCII : u8 {
+ No,
+ Yes,
+};
+
+// OPTIMIZATION: The parser knows whether text it has scanned is ASCII, which saves finding that out again here in
+// order to store the string at one byte per code unit.
+template<typename CodeUnit>
+static Utf16String utf16_string_from_ascii_code_units(ReadonlySpan<CodeUnit> code_units)
+{
+ return Utf16String::create_uninitialized_ascii(code_units.size(), [&](Bytes buffer) {
+ for (size_t i = 0; i < code_units.size(); ++i)
+ buffer[i] = static_cast<u8>(code_units[i]);
+ });
+}
+
+static Utf16String utf16_string_from_span(ReadonlyBytes latin1, IsKnownToBeASCII is_known_to_be_ascii)
+{
+ if (latin1.is_empty())
+ return {};
+ if (is_known_to_be_ascii == IsKnownToBeASCII::Yes)
+ return utf16_string_from_ascii_code_units(latin1);
+ return Utf16String::from_utf16(Utf16View::from_latin1(latin1, false));
+}
+
+static Utf16String utf16_string_from_span(ReadonlySpan<char16_t> utf16, IsKnownToBeASCII is_known_to_be_ascii)
+{
+ if (is_known_to_be_ascii == IsKnownToBeASCII::Yes && !utf16.is_empty())
+ return utf16_string_from_ascii_code_units(utf16);
+ return utf16_string_from_span(utf16);
+}
+
static Utf16String utf16_string_from_ffi(u16 const* ptr, size_t len)
{
if (!ptr)
@@ -152,13 +184,13 @@ static Utf16String const& newline_then_spaces_string(size_t length)
// OPTIMIZATION: Markup indents tags with a newline followed by spaces, so many Text nodes hold such a run. Like Blink,
// share one string for each length of these runs instead of allocating one for every Text node.
-template<typename CharT>
-static Utf16String text_node_data_from_span(ReadonlySpan<CharT> text)
+template<typename CharT, typename... IsKnownToBeASCIIOrNothing>
+static Utf16String text_node_data_from_span(ReadonlySpan<CharT> text, IsKnownToBeASCIIOrNothing... is_known_to_be_ascii)
{
if (text.size() > 1 && text.size() < newline_then_spaces_table_size && text[0] == '\n'
&& all_of(text.slice(1), [](CharT ch) { return ch == ' '; }))
return newline_then_spaces_string(text.size());
- return utf16_string_from_span(text);
+ return utf16_string_from_span(text, is_known_to_be_ascii...);
}
static Optional<Utf16FlyString> attribute_namespace_from_html_parser_ffi(RustFfiHtmlAttributeNamespace);
@@ -185,7 +217,8 @@ extern "C" void ladybird_html_parser_set_document_quirks_mode(void*, RustFfiHtml
extern "C" bool ladybird_html_parser_document_is_iframe_srcdoc_document(void*);
extern "C" size_t ladybird_html_parser_create_document_type(void*, u16 const*, size_t, u16 const*, size_t, u16 const*, size_t);
extern "C" size_t ladybird_html_parser_create_comment(void*, u16 const*, size_t);
-extern "C" void ladybird_html_parser_insert_text(size_t, size_t, u8 const*, size_t);
+extern "C" void ladybird_html_parser_insert_latin1_text(size_t, size_t, u8 const*, size_t, bool);
+extern "C" void ladybird_html_parser_insert_utf16_text(size_t, size_t, u16 const*, size_t, bool);
extern "C" void ladybird_html_parser_add_missing_attribute(void*, size_t, size_t, u16 const*, size_t);
extern "C" u8 ladybird_html_parser_sanitizer_action(void*, size_t);
extern "C" size_t ladybird_html_parser_child_at_index(size_t, size_t);
@@ -3077,7 +3110,8 @@ extern "C" size_t ladybird_html_parser_create_comment(void* parser, u16 const* d
}
// https://html.spec.whatwg.org/multipage/parsing.html#insert-a-character
-extern "C" void ladybird_html_parser_insert_text(size_t parent, size_t offset, u8 const* data_ptr, size_t data_len)
+template<typename CharT>
+static void insert_text_for_rust_parser(size_t parent, size_t offset, ReadonlySpan<CharT> text, bool is_ascii)
{
auto insertion_location = node_and_offset_from_html_parser_ffi(parent, offset);
auto& parent_node = *insertion_location.node;
@@ -3087,15 +3121,25 @@ extern "C" void ladybird_html_parser_insert_text(size_t parent, size_t offset, u
if (parent_node.is_document())
return;
- auto data = text_node_data_from_span(ReadonlySpan<char> { reinterpret_cast<char const*>(data_ptr), data_len });
+ auto data = text_node_data_from_span(text, is_ascii ? IsKnownToBeASCII::Yes : IsKnownToBeASCII::No);
if (auto* previous_text = as_if<DOM::Text>(insertion_location.previous_child())) {
HTMLOrSVGScriptElement::ParserChildrenChangeScope script_children_change { parent_node };
(void)previous_text->append_data(data);
return;
}
- auto text = DOM::Text::create(parent_node.document(), data);
- insert_node_for_parser(parent_node, *text, insertion_location.child_at_offset());
+ auto text_node = DOM::Text::create(parent_node.document(), data);
+ insert_node_for_parser(parent_node, *text_node, insertion_location.child_at_offset());
+}
+
+extern "C" void ladybird_html_parser_insert_latin1_text(size_t parent, size_t offset, u8 const* data_ptr, size_t data_len, bool is_ascii)
+{
+ insert_text_for_rust_parser(parent, offset, ReadonlyBytes { data_ptr, data_len }, is_ascii);
+}
+
+extern "C" void ladybird_html_parser_insert_utf16_text(size_t parent, size_t offset, u16 const* data_ptr, size_t data_len, bool is_ascii)
+{
+ insert_text_for_rust_parser(parent, offset, ReadonlySpan<char16_t> { reinterpret_cast<char16_t const*>(data_ptr), data_len }, is_ascii);
}
// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs
index 87fc9b68872..317a512bfd2 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/input.rs
@@ -4,6 +4,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+use crate::scan;
+use std::ops::Range;
+
/// The code units of a tokenizer's input stream.
///
/// Most documents only have code units below U+0100, and are kept at one byte per code unit. The stream is widened
@@ -15,6 +18,14 @@ pub enum Input {
Utf16(Vec<u16>),
}
+/// Where a run of code units is in the input.
+#[derive(Clone, Debug)]
+pub struct InputRun {
+ pub range: Range<usize>,
+ /// Whether every code unit of the run is known to be ASCII.
+ pub is_ascii: bool,
+}
+
/// A borrowed run of input code units.
#[derive(Clone, Copy, Debug)]
pub enum InputSlice<'a> {
@@ -78,6 +89,13 @@ impl Input {
}
}
+ pub fn slice(&self, range: Range<usize>) -> InputSlice<'_> {
+ match self {
+ Self::Latin1(code_units) => InputSlice::Latin1(&code_units[range]),
+ Self::Utf16(code_units) => InputSlice::Utf16(&code_units[range]),
+ }
+ }
+
pub fn append(&mut self, code_units: InputSlice<'_>) {
self.insert(self.len(), code_units);
}
@@ -125,9 +143,22 @@ impl InputSlice<'_> {
}
pub fn to_utf16(&self) -> Vec<u16> {
+ let mut code_units = Vec::with_capacity(self.len());
+ self.append_to(&mut code_units);
+ code_units
+ }
+
+ pub fn contains_non_whitespace(&self) -> bool {
+ match self {
+ Self::Latin1(code_units) => scan::contains_non_whitespace(code_units),
+ Self::Utf16(code_units) => scan::contains_non_whitespace(code_units),
+ }
+ }
+
+ pub fn append_to(&self, output: &mut Vec<u16>) {
match self {
- Self::Latin1(code_units) => code_units.iter().copied().map(u16::from).collect(),
- Self::Utf16(code_units) => code_units.to_vec(),
+ Self::Latin1(code_units) => output.extend(code_units.iter().copied().map(u16::from)),
+ Self::Utf16(code_units) => output.extend_from_slice(code_units),
}
}
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
index f6ae82a7978..273b6bdc5f4 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
@@ -5,6 +5,9 @@
*/
use crate::RustFfiTokenizerHandle;
+use crate::input::Input;
+use crate::input::InputRun;
+use crate::input::InputSlice;
use crate::known_names::attribute_name;
use crate::known_names::tag_name;
use crate::token::AttributeList;
@@ -121,7 +124,20 @@ unsafe extern "C" {
system_id_len: usize,
) -> usize;
fn ladybird_html_parser_create_comment(parser: *mut c_void, data_ptr: *const u16, data_len: usize) -> usize;
- fn ladybird_html_parser_insert_text(parent: usize, offset: usize, data_ptr: *const u8, data_len: usize);
+ fn ladybird_html_parser_insert_latin1_text(
+ parent: usize,
+ offset: usize,
+ data_ptr: *const u8,
+ data_len: usize,
+ is_ascii: bool,
+ );
+ fn ladybird_html_parser_insert_utf16_text(
+ parent: usize,
+ offset: usize,
+ data_ptr: *const u16,
+ data_len: usize,
+ is_ascii: bool,
+ );
fn ladybird_html_parser_add_missing_attribute(
parser: *mut c_void,
element: usize,
@@ -387,7 +403,7 @@ struct ParserState {
allow_declarative_shadow_roots: bool,
scripting_enabled: bool,
next_line_feed_can_be_ignored: bool,
- pending_text: String,
+ pending_text: PendingText,
attribute_buffers: AttributeBuffers,
pending_table_text: String,
pending_table_text_contains_non_whitespace: bool,
@@ -423,7 +439,7 @@ impl ParserState {
allow_declarative_shadow_roots: false,
scripting_enabled: true,
next_line_feed_can_be_ignored: false,
- pending_text: String::new(),
+ pending_text: PendingText::default(),
attribute_buffers: AttributeBuffers::default(),
pending_table_text: String::new(),
pending_table_text_contains_non_whitespace: false,
@@ -681,15 +697,13 @@ impl TreeBuilder {
// SAFETY: See above.
// FIXME: Recheck the tokenizer state after reconstruction; custom element reactions can abort
// the parser, invalidating the previously available Data-state run.
- let contains_non_whitespace = unsafe {
- self.tokenizer
- .as_mut()
- .try_fast_data_run(&mut self.pending_text)
- .unwrap()
- };
- if contains_non_whitespace {
+ let run = unsafe { self.tokenizer.as_mut().try_fast_data_run().unwrap() };
+ // SAFETY: See above.
+ let input = unsafe { &self.tokenizer.as_ref().input };
+ if self.frameset_ok && input.slice(run.range.clone()).contains_non_whitespace() {
self.frameset_ok = false;
}
+ self.pending_text.push_input_run(run, input);
continue;
}
}
@@ -4157,9 +4171,10 @@ impl TreeBuilder {
// https://html.spec.whatwg.org/multipage/parsing.html#insert-a-character
fn insert_character(&mut self, code_point: u32) {
- if let Some(character) = char::from_u32(code_point) {
- self.pending_text.push(character);
- }
+ // SAFETY: TreeBuilder is only constructed with a tokenizer pointer owned by the C++ HTMLParser's Rust
+ // tokenizer handle, and the handle outlives each parser run.
+ let input = unsafe { &self.tokenizer.as_ref().input };
+ self.pending_text.push_code_point(code_point, input);
}
// https://html.spec.whatwg.org/multipage/parsing.html#insert-a-character
@@ -4169,25 +4184,37 @@ impl TreeBuilder {
}
// AD-HOC: Coalesce consecutive character tokens before asking the host to insert text. The host still runs the
// same DOM insertion logic for the adjusted insertion location.
- let mut data = std::mem::take(&mut self.pending_text);
+ let input_run = self.pending_text.input_run.take();
+ let mut code_units = std::mem::take(&mut self.pending_text.code_units);
let insertion_location = self.adjusted_insertion_location_for_text();
- self.insert_text(insertion_location, &data);
+ if let Some(input_run) = input_run {
+ // OPTIMIZATION: Text that is one run of the input is handed to the host from the input buffer itself.
+ // SAFETY: TreeBuilder is only constructed with a tokenizer pointer owned by the C++ HTMLParser's Rust
+ // tokenizer handle, and the handle outlives each parser run.
+ let input = unsafe { &self.tokenizer.as_ref().input };
+ self.insert_text(insertion_location, input.slice(input_run.range), input_run.is_ascii);
+ } else {
+ self.insert_text(insertion_location, InputSlice::Utf16(&code_units), false);
+ }
// OPTIMIZATION: Keep small text buffers for the next run without retaining large text nodes.
- if data.capacity() <= 4096 && self.pending_text.is_empty() {
- data.clear();
- self.pending_text = data;
+ if code_units.capacity() <= 4096 && self.pending_text.is_empty() {
+ code_units.clear();
+ self.pending_text.code_units = code_units;
}
}
- fn insert_text(&mut self, insertion_location: AdjustedInsertionLocation, data: &str) {
+ fn insert_text(&mut self, insertion_location: AdjustedInsertionLocation, text: InputSlice<'_>, is_ascii: bool) {
+ let AdjustedInsertionLocation { parent, offset } = insertion_location;
unsafe {
- ladybird_html_parser_insert_text(
- insertion_location.parent,
- insertion_location.offset,
- data.as_ptr(),
- data.len(),
- )
+ match text {
+ InputSlice::Latin1(text) => {
+ ladybird_html_parser_insert_latin1_text(parent, offset, text.as_ptr(), text.len(), is_ascii)
+ }
+ InputSlice::Utf16(text) => {
+ ladybird_html_parser_insert_utf16_text(parent, offset, text.as_ptr(), text.len(), is_ascii)
+ }
+ }
}
}
@@ -5213,6 +5240,52 @@ impl TreeBuilder {
}
}
+/// The text of the character tokens that haven't been inserted yet.
+#[derive(Default)]
+struct PendingText {
+ /// The run of tokenizer input that is all of the text, for as long as the text is exactly that. The run doesn't
+ /// outlive a parser run, so the input can't change under it.
+ input_run: Option<InputRun>,
+ /// The text, once it is anything other than a single run of input.
+ code_units: Vec<u16>,
+}
+
+impl PendingText {
+ fn is_empty(&self) -> bool {
+ self.input_run.is_none() && self.code_units.is_empty()
+ }
+
+ fn push_code_point(&mut self, code_point: u32, input: &Input) {
+ let Some(character) = char::from_u32(code_point) else {
+ return;
+ };
+ self.copy_input_run(input);
+ self.code_units.extend_from_slice(character.encode_utf16(&mut [0; 2]));
+ }
+
+ fn push_input_run(&mut self, run: InputRun, input: &Input) {
+ if self.is_empty() {
+ self.input_run = Some(run);
+ return;
+ }
+ if let Some(input_run) = &mut self.input_run
+ && input_run.range.end == run.range.start
+ {
+ input_run.range.end = run.range.end;
+ input_run.is_ascii &= run.is_ascii;
+ return;
+ }
+ self.copy_input_run(input);
+ input.slice(run.range).append_to(&mut self.code_units);
+ }
+
+ fn copy_input_run(&mut self, input: &Input) {
+ if let Some(input_run) = self.input_run.take() {
+ input.slice(input_run.range).append_to(&mut self.code_units);
+ }
+ }
+}
+
#[derive(Default)]
struct AttributeBuffers {
attributes: Vec<RustFfiHtmlParserAttribute>,
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs
index 515f4c2a85a..e991ba4c394 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/test_host.rs
@@ -264,13 +264,36 @@ extern "C" fn ladybird_html_parser_create_comment(
}
#[unsafe(no_mangle)]
-unsafe extern "C" fn ladybird_html_parser_insert_text(
+unsafe extern "C" fn ladybird_html_parser_insert_latin1_text(
parent: usize,
offset: usize,
data_ptr: *const u8,
data_len: usize,
+ is_ascii: bool,
) {
- let data = std::str::from_utf8(unsafe { ak::slice_from_raw_parts(data_ptr, data_len) }).unwrap();
+ let data = unsafe { ak::slice_from_raw_parts(data_ptr, data_len) };
+ assert!(!is_ascii || data.is_ascii());
+ insert_text(
+ parent,
+ offset,
+ &data.iter().copied().map(char::from).collect::<String>(),
+ );
+}
+
+#[unsafe(no_mangle)]
+unsafe extern "C" fn ladybird_html_parser_insert_utf16_text(
+ parent: usize,
+ offset: usize,
+ data_ptr: *const u16,
+ data_len: usize,
+ is_ascii: bool,
+) {
+ let data = unsafe { ak::slice_from_raw_parts(data_ptr, data_len) };
+ assert!(!is_ascii || data.iter().all(|code_unit| *code_unit < 0x80));
+ insert_text(parent, offset, &String::from_utf16(data).unwrap());
+}
+
+fn insert_text(parent: usize, offset: usize, data: &str) {
with_fake_dom(|dom| {
dom.record_insertion(FakeInsertionCall::InsertText, parent, offset);
if dom.node(parent).kind == FakeNodeKind::Document {
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs
index f67157f477b..59413bf6fa4 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser/tests.rs
@@ -65,6 +65,18 @@ impl ScriptCreatedParser {
self.run(true);
}
+ /// Gives the parser the rest of its input from the network rather than from a script.
+ fn append_and_close(&mut self, markup: &str) {
+ let code_units: Vec<u16> = markup.encode_utf16().collect();
+ if code_units.iter().all(|code_unit| *code_unit <= 0xff) {
+ let bytes: Vec<u8> = code_units.iter().map(|code_unit| *code_unit as u8).collect();
+ self.tokenizer().append_input(InputSlice::Latin1(&bytes));
+ } else {
+ self.tokenizer().append_input(InputSlice::Utf16(&code_units));
+ }
+ self.close();
+ }
+
fn close(&mut self) {
self.tokenizer().insert_eof();
self.run(false);
@@ -170,3 +182,47 @@ fn foster_parented_text_is_inserted_before_the_table_at_an_explicit_offset() {
);
assert!(test_host::children(body_children[1]).is_empty());
}
+
+fn text_of_each_paragraph(markup: &str) -> Vec<String> {
+ let mut parser = ScriptCreatedParser::open();
+ parser.append_and_close(markup);
+ test_host::children(body_element())
+ .into_iter()
+ .map(|paragraph| match &test_host::children(paragraph)[..] {
+ [text] => match test_host::kind(*text) {
+ FakeNodeKind::Text(text) => text,
+ kind => panic!("expected text in the paragraph, not {kind:?}"),
+ },
+ children => panic!("expected one text node in the paragraph, not {} nodes", children.len()),
+ })
+ .collect()
+}
+
+#[test]
+fn text_is_inserted_as_one_node_however_the_tokenizer_emits_it() {
+ // Text that is taken straight from the input, in both forms the input is stored in.
+ assert_eq!(
+ text_of_each_paragraph("<p>plain<p>caf\u{e9}\nau lait"),
+ ["plain", "caf\u{e9}\nau lait"]
+ );
+ assert_eq!(
+ text_of_each_paragraph("<p>plain<p>wide \u{2014} \u{1f600}!"),
+ ["plain", "wide \u{2014} \u{1f600}!"]
+ );
+ // Text that is put together from runs of input and the characters between them that the tokenizer changes.
+ assert_eq!(
+ text_of_each_paragraph("<p>a &amp; b &lt;<p>x\r\ny\rz<p>&amp;<p>\u{1f600} first"),
+ ["a & b <", "x\ny\nz", "&", "\u{1f600} first"]
+ );
+ // A surrogate without its other half becomes U+FFFD.
+ let mut parser = ScriptCreatedParser::open();
+ parser
+ .tokenizer()
+ .append_input(InputSlice::Utf16(&[0x3C, 0x70, 0x3E, 0x61, 0xD83D, 0x62]));
+ parser.close();
+ let paragraph = test_host::children(body_element())[0];
+ assert_eq!(
+ kinds_of(&test_host::children(paragraph)),
+ [FakeNodeKind::Text("a\u{fffd}b".to_string())]
+ );
+}
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
index 88d5a1d4c07..52daaf93555 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
@@ -12,14 +12,109 @@
use crate::token::Position;
/// A code unit of the input stream, in either of the forms it is stored in.
-pub trait CodeUnit: Copy + Eq + Into<u16> + From<u8> {}
+pub trait CodeUnit: Copy + Eq + Into<u16> + From<u8> {
+ /// Whether this is half of a surrogate pair. One-byte code units never are.
+ fn is_surrogate(self) -> bool;
+}
-impl CodeUnit for u8 {}
+impl CodeUnit for u8 {
+ #[inline(always)]
+ fn is_surrogate(self) -> bool {
+ false
+ }
+}
-impl CodeUnit for u16 {}
+impl CodeUnit for u16 {
+ #[inline(always)]
+ fn is_surrogate(self) -> bool {
+ self & 0xF800 == 0xD800
+ }
+}
const CHUNK_SIZE: usize = 32;
+// Most runs of text in markup are short, and are over before a chunk would be.
+const SHORT_RUN_LENGTH: usize = 16;
+
+/// The offset of the first code unit that `stops` accepts, or the length of `code_units` if there is none. The bits of
+/// the code units before it are added to `seen_bits`.
+#[inline(always)]
+fn find_first<T: CodeUnit>(code_units: &[T], stops: impl Fn(T) -> bool, seen_bits: &mut u16) -> usize {
+ let scan_one_by_one = |range: std::ops::Range<usize>, seen_bits: &mut u16| {
+ for offset in range {
+ let code_unit = code_units[offset];
+ if stops(code_unit) {
+ return Some(offset);
+ }
+ *seen_bits |= code_unit.into();
+ }
+ None
+ };
+
+ let mut offset = code_units.len().min(SHORT_RUN_LENGTH);
+ if let Some(stop) = scan_one_by_one(0..offset, seen_bits) {
+ return stop;
+ }
+ let (chunks, _) = code_units[offset..].as_chunks::<CHUNK_SIZE>();
+ for chunk in chunks {
+ let mut any_stops = false;
+ let mut bits = 0;
+ for &code_unit in chunk {
+ any_stops |= stops(code_unit);
+ bits |= code_unit.into();
+ }
+ if any_stops {
+ break;
+ }
+ *seen_bits |= bits;
+ offset += CHUNK_SIZE;
+ }
+ scan_one_by_one(offset..code_units.len(), seen_bits).unwrap_or(code_units.len())
+}
+
+/// A run of code units at the start of some input.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct Run {
+ pub length: usize,
+ pub is_ascii: bool,
+}
+
+/// The run of code units at the start of `code_units` that the data state emits as they are: everything up to the
+/// first U+003C (<), U+0026 (&), U+0000 NULL, U+000D CR, or surrogate that isn't half of a pair.
+pub fn data_run<T: CodeUnit>(code_units: &[T]) -> Run {
+ let stops = |code_unit: T| {
+ code_unit == T::from(b'<')
+ || code_unit == T::from(b'&')
+ || code_unit == T::from(0)
+ || code_unit == T::from(b'\r')
+ || code_unit.is_surrogate()
+ };
+ let mut length = 0;
+ let mut seen_bits = 0;
+ loop {
+ length += find_first(&code_units[length..], stops, &mut seen_bits);
+ let Some(&[high, low]) = code_units.get(length..length + 2) else {
+ break;
+ };
+ if !is_surrogate_pair(high.into(), low.into()) {
+ break;
+ }
+ seen_bits |= high.into();
+ length += 2;
+ }
+ Run {
+ length,
+ is_ascii: seen_bits < 0x80,
+ }
+}
+
+/// Whether any code unit is something other than the ASCII whitespace the tree builder ignores for "frameset-ok".
+pub fn contains_non_whitespace<T: CodeUnit>(code_units: &[T]) -> bool {
+ code_units
+ .iter()
+ .any(|&code_unit| !matches!(code_unit.into(), 0x09 | 0x0A | 0x0C | 0x0D | 0x20))
+}
+
/// The number of U+000A LF and of U+000D CR code units.
fn count_line_feeds_and_carriage_returns<T: CodeUnit>(code_units: &[T]) -> (usize, usize) {
let mut line_feeds = 0;
@@ -94,6 +189,58 @@ mod tests {
input.encode_utf16().collect()
}
+ fn run(length: usize, is_ascii: bool) -> Run {
+ Run { length, is_ascii }
+ }
+
+ #[test]
+ fn data_runs_stop_at_markup_and_characters_the_tokenizer_changes() {
+ assert_eq!(data_run(b"plain text" as &[u8]), run(10, true));
+ assert_eq!(data_run(b"" as &[u8]), run(0, true));
+ assert_eq!(data_run(b"a<b" as &[u8]), run(1, true));
+ assert_eq!(data_run(b"a&b" as &[u8]), run(1, true));
+ assert_eq!(data_run(b"a\0b" as &[u8]), run(1, true));
+ assert_eq!(data_run(b"a\r\nb" as &[u8]), run(1, true));
+ assert_eq!(data_run(b"caf\xe9\n<" as &[u8]), run(5, false));
+ assert_eq!(data_run(b"caf<\xe9" as &[u8]), run(3, true));
+ }
+
+ #[test]
+ fn data_runs_find_stops_and_non_ascii_at_every_offset() {
+ // Long enough to put a stop in the short run the scan starts with, in the chunks after it, in the remainder
+ // after those, and on the seams.
+ let length = SHORT_RUN_LENGTH + CHUNK_SIZE * 3;
+ for offset in 0..length {
+ let mut input = vec![b'x'; length];
+ input[offset] = b'<';
+ assert_eq!(data_run(&input), run(offset, true));
+ let mut wide: Vec<u16> = input.iter().copied().map(u16::from).collect();
+ assert_eq!(data_run(&wide), run(offset, true));
+
+ input[offset] = 0xe9;
+ assert_eq!(data_run(&input), run(length, false));
+ wide[offset] = 0x2014;
+ assert_eq!(data_run(&wide), run(length, false));
+ }
+ assert_eq!(data_run(&vec![b'x'; length]), run(length, true));
+ }
+
+ #[test]
+ fn data_runs_take_surrogate_pairs_but_not_lone_surrogates() {
+ assert_eq!(data_run(&code_units("a\u{1f600}b\u{1f600}<")), run(6, false));
+ assert_eq!(data_run::<u16>(&[0x61, 0xD83D]), run(1, true));
+ assert_eq!(data_run::<u16>(&[0x61, 0xD83D, 0x62]), run(1, true));
+ assert_eq!(data_run::<u16>(&[0x61, 0xDE00, 0xD83D]), run(1, true));
+ assert_eq!(data_run::<u16>(&[0x61, 0xD83D, 0xDE00]), run(3, false));
+ }
+
+ #[test]
+ fn finds_non_whitespace() {
+ assert!(!contains_non_whitespace(b" \t\n\x0c" as &[u8]));
+ assert!(contains_non_whitespace(b" \t\n\x0c." as &[u8]));
+ assert!(contains_non_whitespace(&code_units(" \u{a0}")));
+ }
+
fn position_after_all<T: CodeUnit>(code_units: &[T]) -> (u64, u64) {
let position = position_after(Position { line: 3, column: 5 }, code_units);
(position.line, position.column)
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
index efcbe2aee7e..4d8a8ffe6f5 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
@@ -8,6 +8,7 @@ use std::collections::VecDeque;
use crate::entities::NamedCharacterReferenceMatcher;
use crate::input::Input;
+use crate::input::InputRun;
use crate::input::InputSlice;
use crate::scan;
use crate::token::Attribute;
@@ -682,47 +683,30 @@ impl HtmlTokenizer {
Some(cp)
}
- /// Append a run of ordinary ASCII characters from the Data state to
- /// `output`. The caller can process the run as character tokens without
- /// constructing and dispatching a `Token` for each code point.
+ /// Consume the run of input at the current position that the Data state would emit unchanged, one character
+ /// token per code point, and return where in the input it is. The caller can take the text straight from the
+ /// input instead of having a `Token` constructed and dispatched for each code point.
#[inline(always)]
- pub fn try_fast_data_run(&mut self, output: &mut String) -> Option<bool> {
+ pub fn try_fast_data_run(&mut self) -> Option<InputRun> {
if !self.has_fast_data_run() {
return None;
}
let start_offset = self.current_offset;
- let input_len = self.fast_scan_limit();
- let mut offset = start_offset;
- let mut contains_non_whitespace = false;
- while offset < input_len {
- let code_point = u32::from(self.input.code_unit_at(offset));
- if code_point == 0x3C
- || code_point == 0x26
- || code_point == 0x00
- || code_point == 0x0D
- || code_point >= 0x80
- {
- break;
- }
- if !is_whitespace(code_point) {
- contains_non_whitespace = true;
- }
- offset += 1;
- }
- if offset == start_offset {
- return None;
- }
-
- output.reserve(offset - start_offset);
- for offset in start_offset..offset {
- let code_point = self.input.code_unit_at(offset);
- // SAFETY: The scan above only accepts ASCII code points.
- unsafe { output.as_mut_vec().push(code_point as u8) };
- }
- self.prev_offset = offset - 1;
- self.current_offset = offset;
- Some(contains_non_whitespace)
+ let limit = self.fast_scan_limit();
+ let scan::Run { length, is_ascii } = match &self.input {
+ Input::Latin1(code_units) => scan::data_run(&code_units[start_offset..limit]),
+ Input::Utf16(code_units) => scan::data_run(&code_units[start_offset..limit]),
+ };
+ debug_assert!(length > 0);
+ let end_offset = start_offset + length;
+ let ends_with_surrogate_pair = (0xDC00..=0xDFFF).contains(&self.input.code_unit_at(end_offset - 1));
+ self.prev_offset = end_offset - if ends_with_surrogate_pair { 2 } else { 1 };
+ self.current_offset = end_offset;
+ Some(InputRun {
+ range: start_offset..end_offset,
+ is_ascii,
+ })
}
#[inline(always)]
@@ -733,8 +717,10 @@ impl HtmlTokenizer {
if self.current_offset >= self.fast_scan_limit() {
return false;
}
- let code_point = u32::from(self.input.code_unit_at(self.current_offset));
- code_point != 0x3C && code_point != 0x26 && code_point != 0x00 && code_point != 0x0D && code_point < 0x80
+ // NB: A surrogate pair can be inside a run, but a run that starts with one is left to the slow path, which
+ // knows what to do when the surrogate turns out not to have its other half.
+ let code_unit = self.input.code_unit_at(self.current_offset);
+ !matches!(code_unit, 0x3C | 0x26 | 0x00 | 0x0D | 0xD800..=0xDFFF)
}
fn restore_to(&mut self, offset: usize) {