Skip to content

Truly independent web browser

LibWeb: Insert the text of script and style elements in runs of input

Andreas Klingfbf9b1e6ea00
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
index 609525118d7..6446ae84ae0 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
@@ -695,6 +695,25 @@ impl TreeBuilder {
}
}
+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-incdata
+ // OPTIMIZATION: Text of a script, a style element and the like is inserted a run of input at a time, which
+ // is what "insert the token's character" does for each character of it.
+ if !stop_at_insertion_point
+ && !self.next_line_feed_can_be_ignored
+ && self.insertion_mode == InsertionMode::Text
+ && self
+ .adjusted_current_node()
+ .is_some_and(|node| node.namespace_ == RustFfiHtmlNamespace::Html)
+ {
+ // SAFETY: See above.
+ if let Some(run) = unsafe { self.tokenizer.as_mut().try_fast_element_text_run() } {
+ // SAFETY: See above.
+ let input = unsafe { &self.tokenizer.as_ref().input };
+ self.pending_text.push_input_run(run, input);
+ continue;
+ }
+ }
+
let cdata_allowed = self
.adjusted_current_node()
.is_some_and(|node| node.namespace_ != RustFfiHtmlNamespace::Html);
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
index 035be7ff555..39c7c328a8d 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/scan.rs
@@ -252,13 +252,24 @@ pub struct Run {
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.
+/// The run of code units at the start of `code_units` that the data and RCDATA states emit 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 {
+ text_run(code_units, [b'<', b'&', 0, b'\r'])
+}
+
+/// The run of code units at the start of `code_units` that the RAWTEXT and script data states emit as they are:
+/// everything up to the first U+003C (<), U+0000 NULL, U+000D CR, or surrogate that isn't half of a pair.
+pub fn raw_text_run<T: CodeUnit>(code_units: &[T]) -> Run {
+ text_run(code_units, [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;
let mut seen_non_ascii = false;
loop {
- length += find_first(&code_units[length..], [b'<', b'&', 0, b'\r'], &mut seen_non_ascii);
+ length += find_first(&code_units[length..], stops, &mut seen_non_ascii);
let Some(&[high, low]) = code_units.get(length..length + 2) else {
break;
};
@@ -377,6 +388,15 @@ mod tests {
assert_eq!(data_run(b"caf<\xe9" as &[u8]), run(3, true));
}
+ #[test]
+ fn raw_text_runs_go_on_past_ampersands() {
+ assert_eq!(raw_text_run(b"a && b < c" as &[u8]), run(7, true));
+ assert_eq!(raw_text_run(b"a && b\0" as &[u8]), run(6, true));
+ assert_eq!(raw_text_run(b"a\r\n" as &[u8]), run(1, true));
+ assert_eq!(raw_text_run(&code_units("a&\u{1f600}</")), run(4, false));
+ assert_eq!(raw_text_run::<u16>(&[0x61, 0x26, 0xD83D]), run(2, true));
+ }
+
#[test]
fn data_runs_find_stops_and_non_ascii_at_every_offset() {
// Long enough to put a stop in every place of a block, in the part that is less than a block, and on the
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
index f8a99e42d09..405c4c2a92b 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
@@ -339,6 +339,15 @@ fn is_ascii_lower_alpha(c: u32) -> bool {
matches!(c, 0x61..=0x7A)
}
+/// What ends a run of text that a state emits as it is, besides U+0000 NULL, U+000D CR and lone surrogates.
+#[derive(Clone, Copy, Eq, PartialEq)]
+enum TextRunStops {
+ /// U+003C (<).
+ Markup,
+ /// U+003C (<) and U+0026 (&).
+ MarkupAndCharacterReferences,
+}
+
impl HtmlTokenizer {
/// Create a new tokenizer for the given input.
pub fn new(input: impl Into<CodeUnits>) -> Self {
@@ -676,22 +685,78 @@ impl HtmlTokenizer {
if !self.has_fast_data_run() {
return None;
}
+ Some(self.take_text_run(TextRunStops::MarkupAndCharacterReferences))
+ }
+
+ /// Whether `try_fast_data_run()` would return a run.
+ #[inline(always)]
+ pub fn has_fast_data_run(&self) -> bool {
+ self.state == State::Data && self.has_text_run(TextRunStops::MarkupAndCharacterReferences)
+ }
+
+ /// Like `try_fast_data_run()`, for the text of an element whose content isn't markup: what the RCDATA, RAWTEXT
+ /// and script data states would emit unchanged.
+ #[inline(always)]
+ pub fn try_fast_element_text_run(&mut self) -> Option<InputRun> {
+ let stops = self.element_text_run_stops()?;
+ if !self.has_text_run(stops) {
+ return None;
+ }
+ Some(self.take_text_run(stops))
+ }
+
+ #[inline(always)]
+ fn element_text_run_stops(&self) -> Option<TextRunStops> {
+ match self.state {
+ State::RCDATA => Some(TextRunStops::MarkupAndCharacterReferences),
+ State::RAWTEXT | State::ScriptData => Some(TextRunStops::Markup),
+ _ => None,
+ }
+ }
+
+ #[inline(always)]
+ fn has_text_run(&self, stops: TextRunStops) -> bool {
+ if self.aborted || !self.queued_tokens.is_empty() {
+ return false;
+ }
+ if self.current_offset >= self.fast_scan_limit() {
+ return false;
+ }
+ // 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.
+ match self.input.code_unit_at(self.current_offset) {
+ 0x3C | 0x00 | 0x0D | 0xD800..=0xDFFF => false,
+ 0x26 => stops == TextRunStops::Markup,
+ _ => true,
+ }
+ }
+ fn take_text_run(&mut self, stops: TextRunStops) -> InputRun {
let start_offset = self.current_offset;
let limit = self.fast_scan_limit();
- let scan::Run { length, is_ascii } = match &self.input {
- CodeUnits::Latin1(code_units) => scan::data_run(&code_units[start_offset..limit]),
- CodeUnits::Utf16(code_units) => scan::data_run(&code_units[start_offset..limit]),
+ let scan::Run { length, is_ascii } = match (&self.input, stops) {
+ (CodeUnits::Latin1(code_units), TextRunStops::MarkupAndCharacterReferences) => {
+ scan::data_run(&code_units[start_offset..limit])
+ }
+ (CodeUnits::Utf16(code_units), TextRunStops::MarkupAndCharacterReferences) => {
+ scan::data_run(&code_units[start_offset..limit])
+ }
+ (CodeUnits::Latin1(code_units), TextRunStops::Markup) => {
+ scan::raw_text_run(&code_units[start_offset..limit])
+ }
+ (CodeUnits::Utf16(code_units), TextRunStops::Markup) => {
+ scan::raw_text_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 {
+ InputRun {
range: start_offset..end_offset,
is_ascii,
- })
+ }
}
/// Appends the code units that come next to the attribute value being read, as far as a value in quotes takes
@@ -716,20 +781,6 @@ impl HtmlTokenizer {
self.current_offset = end_offset;
}
- #[inline(always)]
- pub fn has_fast_data_run(&self) -> bool {
- if self.aborted || self.state != State::Data || !self.queued_tokens.is_empty() {
- return false;
- }
- if self.current_offset >= self.fast_scan_limit() {
- return false;
- }
- // 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) {
self.current_offset = offset;
}