Skip to content

Truly independent web browser

LibWeb: Resume speculative parsing where the last scan stopped

sideshowbarker98d623d1636d
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 4cbd284e8c3..a55291a6ae1 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -274,6 +274,7 @@ void HTMLParser::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_context_element);
visitor.visit(m_root_insertion_target);
visitor.visit(m_active_speculative_html_parser);
+ visitor.visit(m_speculative_html_parser);
visitor.visit(m_change_encoding_callback);
visitor.visit(m_ready_for_more_input_callback);
visitor.visit(m_parsing_complete_callback);
@@ -2719,11 +2720,19 @@ void HTMLParser::start_the_speculative_html_parser()
stop_the_speculative_html_parser();
// 3. Let speculativeParser be a new speculative HTML parser, with the same state as parser.
+ // OPTIMIZATION: The spec says user agents can restart speculative parsing more efficiently, as long as the end
+ // result is equivalent. So, while this parser hasn't got past where the last speculative parser
+ // stopped, the new one goes on from there rather than scanning the input up to there again. That
+ // keeps a document with many parser-blocking scripts from being scanned once for each of them.
+ if (!m_speculative_html_parser)
+ m_speculative_html_parser = SpeculativeHTMLParser::create(*m_document, m_scripting_mode);
+ auto speculative_parser = m_speculative_html_parser;
+ speculative_parser->take_unscanned_input(m_tokenizer.ffi_handle({}), m_document->base_url());
+
// 4. Let speculativeDoc be a new isomorphic representation of parser's Document, where all elements are instead
// speculative mock elements. Let speculativeParser parse into speculativeDoc.
// NOTE: The Rust preload scanner emits speculative fetch candidates directly, so we do not materialize a
// speculativeDoc tree or speculative mock elements.
- auto speculative_parser = SpeculativeHTMLParser::create(*m_document, m_tokenizer.unparsed_input(), m_document->base_url(), m_scripting_mode);
// 5. Set parser's active speculative HTML parser to speculativeParser.
m_active_speculative_html_parser = speculative_parser;
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.h b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
index 2f290b2a654..7a05e3b2902 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.h
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
@@ -195,6 +195,10 @@ private:
// https://html.spec.whatwg.org/multipage/parsing.html#active-speculative-html-parser
GC::Ptr<SpeculativeHTMLParser> m_active_speculative_html_parser;
+
+ // The speculative HTML parser that the active one is whenever it's not null, so that it can go on from where it
+ // stopped while this parser hasn't got past there.
+ GC::Ptr<SpeculativeHTMLParser> m_speculative_html_parser;
};
class HTMLParserEndState final : public JS::Cell {
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
index bdd2ba952c7..5f2d316043b 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/preload_scanner.rs
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+use crate::RustFfiTokenizerHandle;
use crate::known_names::attribute_name;
use crate::known_names::tag_name;
use crate::token::Attribute;
@@ -72,94 +73,145 @@ pub struct RustFfiPreloadScannerEntry {
pub media_len: usize,
}
-/// Scan pending Latin-1 parser input for resources the speculative HTML parser can fetch.
+/// A preload scanner that keeps its place in the parser's input from one run to the next, so that a speculative HTML
+/// parser started while another script blocks the parser goes on from where the last one stopped, rather than scanning
+/// the same input again.
+pub struct RustFfiPreloadScanner {
+ tokenizer: HtmlTokenizer,
+ template_depth: u64,
+ foreign_depth: u64,
+ scripting_enabled: bool,
+}
+
+impl RustFfiPreloadScanner {
+ fn new(scripting_enabled: bool) -> Self {
+ let mut tokenizer = HtmlTokenizer::new(Vec::new());
+ // More input can arrive, so the scanner waits at the end of what it has for the rest of a token.
+ tokenizer.set_input_stream_closed(false);
+ RustFfiPreloadScanner {
+ tokenizer,
+ template_depth: 0,
+ foreign_depth: 0,
+ scripting_enabled,
+ }
+ }
+
+ fn reset(&mut self) {
+ *self = Self::new(self.scripting_enabled);
+ }
+
+ fn append_input(&mut self, code_units: &[u16]) {
+ self.tokenizer.append_input(code_units);
+ }
+
+ fn scan(&mut self, callback: &mut impl FnMut(&RustFfiPreloadScannerEntry) -> bool) {
+ while let Some(token) = self.tokenizer.next_token(false, false) {
+ let should_continue = match token.token_type {
+ TokenType::StartTag => {
+ let should_continue =
+ process_start_tag(&token, &mut self.template_depth, &mut self.foreign_depth, callback);
+
+ // The tree builder switches the tokenizer out of the data state for these elements, so their
+ // contents are text rather than markup. It never does so for foreign content.
+ if self.foreign_depth == 0
+ && let Some(state) = tokenizer_state_after_start_tag(token.tag_name(), self.scripting_enabled)
+ {
+ self.tokenizer.switch_to(state);
+ }
+ should_continue
+ }
+ TokenType::EndTag => {
+ process_end_tag(&token, &mut self.template_depth, &mut self.foreign_depth);
+ true
+ }
+ TokenType::EndOfFile => false,
+ _ => true,
+ };
+ if !should_continue {
+ break;
+ }
+ }
+
+ // Drop the input scanned so far, unless a token that isn't finished yet still needs it.
+ self.tokenizer.parser_did_run();
+ }
+}
+
+/// Create a preload scanner for a speculative HTML parser.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_html_preload_scanner_create(scripting_enabled: bool) -> *mut RustFfiPreloadScanner {
+ Box::into_raw(Box::new(RustFfiPreloadScanner::new(scripting_enabled)))
+}
+
+/// Destroy a preload scanner.
///
/// # Safety
-/// `callback` must not retain pointers from the provided entry beyond the callback invocation.
+/// `scanner` must come from `rust_html_preload_scanner_create`, and must not be used afterwards.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_html_preload_scanner_scan_latin1(
- input: ak::Span<'_, u8>,
- scripting_enabled: bool,
- ctx: *mut c_void,
- callback: unsafe extern "C" fn(ctx: *mut c_void, entry: *const RustFfiPreloadScannerEntry) -> bool,
-) {
- let code_units = input.as_slice().iter().map(|&byte| u16::from(byte)).collect();
- scan_code_units(code_units, scripting_enabled, &mut |entry| unsafe {
- callback(ctx, &raw const *entry)
- });
+pub unsafe extern "C" fn rust_html_preload_scanner_destroy(scanner: *mut RustFfiPreloadScanner) {
+ if !scanner.is_null() {
+ // SAFETY: The caller passes a scanner from rust_html_preload_scanner_create.
+ drop(unsafe { Box::from_raw(scanner) });
+ }
}
-/// Scan pending UTF-16 parser input for resources the speculative HTML parser can fetch.
+/// Hand the scanner the input of the parser that it hasn't seen yet. Returns false if the scanner had to start over at
+/// the parser's current position, because the parser got past where it stopped, input was inserted before there, or
+/// the caller asked for it with `start_over`.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_html_preload_scanner_append_parser_input(
+ scanner: Option<&mut RustFfiPreloadScanner>,
+ tokenizer: Option<&mut RustFfiTokenizerHandle>,
+ start_over: bool,
+) -> bool {
+ let (Some(scanner), Some(tokenizer)) = (scanner, tokenizer) else {
+ return false;
+ };
+ if start_over {
+ tokenizer.tokenizer.forget_speculative_scan_end();
+ }
+ let (input, continues) = tokenizer.tokenizer.input_for_speculative_scan();
+ if !continues {
+ scanner.reset();
+ }
+ scanner.append_input(input);
+ continues
+}
+
+/// Scan the input the scanner has for resources the speculative HTML parser can fetch, stopping at the end of it or
+/// once `callback` returns false.
///
/// # Safety
/// `callback` must not retain pointers from the provided entry beyond the callback invocation.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_html_preload_scanner_scan_utf16(
- input: ak::Span<'_, u16>,
- scripting_enabled: bool,
+pub unsafe extern "C" fn rust_html_preload_scanner_scan(
+ scanner: Option<&mut RustFfiPreloadScanner>,
ctx: *mut c_void,
callback: unsafe extern "C" fn(ctx: *mut c_void, entry: *const RustFfiPreloadScannerEntry) -> bool,
) {
- let input = input.as_slice();
-
- scan_utf16(input, scripting_enabled, |entry| unsafe {
- callback(ctx, &raw const *entry)
- });
+ let Some(scanner) = scanner else {
+ return;
+ };
+ scanner.scan(&mut |entry| unsafe { callback(ctx, &raw const *entry) });
}
#[cfg(test)]
-pub(crate) fn scan(
- input: &[u8],
- scripting_enabled: bool,
- mut callback: impl FnMut(&RustFfiPreloadScannerEntry) -> bool,
-) {
- // SAFETY: The FFI entry point guarantees valid UTF-8.
- let code_units = unsafe { std::str::from_utf8_unchecked(input) }.encode_utf16().collect();
- scan_code_units(code_units, scripting_enabled, &mut callback);
+pub(crate) fn scan(input: &[u8], scripting_enabled: bool, callback: impl FnMut(&RustFfiPreloadScannerEntry) -> bool) {
+ // SAFETY: The tests pass valid UTF-8.
+ let code_units: Vec<u16> = unsafe { std::str::from_utf8_unchecked(input) }.encode_utf16().collect();
+ scan_utf16(&code_units, scripting_enabled, callback);
}
+#[cfg(test)]
pub(crate) fn scan_utf16(
input: &[u16],
scripting_enabled: bool,
mut callback: impl FnMut(&RustFfiPreloadScannerEntry) -> bool,
) {
- scan_code_units(input.to_vec(), scripting_enabled, &mut callback);
-}
-
-fn scan_code_units(
- code_units: Vec<u16>,
- scripting_enabled: bool,
- callback: &mut impl FnMut(&RustFfiPreloadScannerEntry) -> bool,
-) {
- let mut tokenizer = HtmlTokenizer::new(code_units);
- let mut template_depth: u64 = 0;
- let mut foreign_depth: u64 = 0;
-
- while let Some(token) = tokenizer.next_token(false, false) {
- let should_continue = match token.token_type {
- TokenType::StartTag => {
- let should_continue = process_start_tag(&token, &mut template_depth, &mut foreign_depth, callback);
-
- // The tree builder switches the tokenizer out of the data state for these elements, so their
- // contents are text rather than markup. It never does so for foreign content.
- if foreign_depth == 0
- && let Some(state) = tokenizer_state_after_start_tag(token.tag_name(), scripting_enabled)
- {
- tokenizer.switch_to(state);
- }
- should_continue
- }
- TokenType::EndTag => {
- process_end_tag(&token, &mut template_depth, &mut foreign_depth);
- true
- }
- TokenType::EndOfFile => false,
- _ => true,
- };
- if !should_continue {
- break;
- }
- }
+ let mut scanner = RustFfiPreloadScanner::new(scripting_enabled);
+ scanner.append_input(input);
+ scanner.tokenizer.set_input_stream_closed(true);
+ scanner.scan(&mut callback);
}
fn process_start_tag(
@@ -945,4 +997,81 @@ mod tests {
]
);
}
+
+ fn code_units(input: &str) -> Vec<u16> {
+ input.encode_utf16().collect()
+ }
+
+ fn scan_urls(scanner: &mut RustFfiPreloadScanner) -> Vec<String> {
+ let mut urls = Vec::new();
+ scanner.scan(&mut |entry| {
+ let url = unsafe { ak::slice_from_raw_parts(entry.url_ptr, entry.url_len) };
+ urls.push(std::str::from_utf8(url).unwrap().to_string());
+ true
+ });
+ urls
+ }
+
+ #[test]
+ fn goes_on_from_where_it_stopped() {
+ let mut scanner = RustFfiPreloadScanner::new(true);
+
+ // The input runs out inside a tag, and then inside the text of a script.
+ scanner.append_input(&code_units(r#"<img src="./a.png"><img sr"#));
+ assert_eq!(scan_urls(&mut scanner), vec!["./a.png"]);
+
+ scanner.append_input(&code_units(r#"c="./b.png"><script>var trap = '<img src="./tr"#));
+ assert_eq!(scan_urls(&mut scanner), vec!["./b.png"]);
+
+ scanner.append_input(&code_units(r#"ap.png">';</script><img src="./c.png">"#));
+ assert_eq!(scan_urls(&mut scanner), vec!["./c.png"]);
+ }
+
+ #[test]
+ fn hands_on_only_input_not_scanned_yet() {
+ let mut parser_tokenizer = HtmlTokenizer::new(code_units("<img src=a>"));
+ parser_tokenizer.set_input_stream_closed(false);
+
+ let (input, continues) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=a>"));
+ assert!(!continues);
+
+ parser_tokenizer.append_input(&code_units("<img src=b>"));
+ let (input, continues) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=b>"));
+ assert!(continues);
+
+ // Once the parser gets past the scanned input, the scan starts over where the parser is.
+ while parser_tokenizer.next_token(false, false).is_some() {}
+ parser_tokenizer.append_input(&code_units("<img src=c>"));
+ let (input, continues) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=c>"));
+ assert!(continues);
+ parser_tokenizer.append_input(&code_units("<img src=d><img src=e>"));
+ while parser_tokenizer.next_token(false, false).is_some() {}
+ parser_tokenizer.parser_did_run();
+ parser_tokenizer.append_input(&code_units("<img src=f>"));
+ let (input, continues) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=f>"));
+ assert!(!continues);
+ }
+
+ #[test]
+ fn starts_over_after_input_is_inserted_before_the_scanned_input() {
+ let mut parser_tokenizer = HtmlTokenizer::new(code_units("<script></script><img src=a>"));
+ parser_tokenizer.set_input_stream_closed(false);
+ parser_tokenizer.next_token(false, false);
+ parser_tokenizer.next_token(false, false);
+ parser_tokenizer.update_insertion_point();
+
+ let (input, _) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=a>"));
+
+ // Input that document.write() inserts at the insertion point comes before the scanned input, so the scan has
+ // to take it in too.
+ parser_tokenizer.insert_input_at_insertion_point(&code_units("<img src=w>"));
+ let (input, continues) = parser_tokenizer.input_for_speculative_scan();
+ assert_eq!(input, code_units("<img src=w><img src=a>"));
+ assert!(!continues);
+ }
}
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
index 0a9aaab0e95..78331d1f04f 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/tokenizer.rs
@@ -233,6 +233,9 @@ pub struct HtmlTokenizer {
stop_at_insertion_point: bool,
cdata_allowed: bool,
entity_matcher: NamedCharacterReferenceMatcher,
+ // Where the input that a speculative HTML parser's preload scanner has been given ends, while it's still a place
+ // the scanner can go on from.
+ speculative_scan_end: Option<usize>,
}
#[inline]
@@ -366,6 +369,7 @@ impl HtmlTokenizer {
stop_at_insertion_point: false,
cdata_allowed: false,
entity_matcher: NamedCharacterReferenceMatcher::new(),
+ speculative_scan_end: None,
}
}
@@ -420,6 +424,7 @@ impl HtmlTokenizer {
let ip = ip.min(self.input.len());
self.input.splice(ip..ip, code_units.iter().copied());
self.insertion_point = Some(ip + code_units.len());
+ self.forget_speculative_scan_end_before(ip);
for old_insertion_point in &mut self.old_insertion_points {
if let Some(old_ip) = old_insertion_point
&& ip <= *old_ip
@@ -435,6 +440,7 @@ impl HtmlTokenizer {
let ip = ip.min(self.input.len());
self.input.splice(ip..ip, bytes.iter().map(|byte| u16::from(*byte)));
self.insertion_point = Some(ip + bytes.len());
+ self.forget_speculative_scan_end_before(ip);
for old_insertion_point in &mut self.old_insertion_points {
if let Some(old_ip) = old_insertion_point
&& ip <= *old_ip
@@ -449,6 +455,29 @@ impl HtmlTokenizer {
String::from_utf16_lossy(&self.input[self.current_offset..])
}
+ /// The input a speculative HTML parser's preload scanner hasn't been given yet, and whether the scanner can go on
+ /// from where it stopped. It can't once this tokenizer has got past that point, or input was inserted before it;
+ /// the input then runs from the current position, and the scanner has to start over there.
+ pub fn input_for_speculative_scan(&mut self) -> (&[u16], bool) {
+ let (start, continues) = match self.speculative_scan_end {
+ Some(end) if end >= self.current_offset => (end, true),
+ _ => (self.current_offset, false),
+ };
+ self.speculative_scan_end = Some(self.input.len());
+ (&self.input[start..], continues)
+ }
+
+ /// Makes the next speculative scan start over at the current position.
+ pub fn forget_speculative_scan_end(&mut self) {
+ self.speculative_scan_end = None;
+ }
+
+ fn forget_speculative_scan_end_before(&mut self, offset: usize) {
+ if self.speculative_scan_end.is_some_and(|end| offset < end) {
+ self.speculative_scan_end = None;
+ }
+ }
+
fn can_discard_consumed_input(&self) -> bool {
if self.current_offset == 0 || self.current_offset != self.input.len() {
return false;
@@ -470,6 +499,11 @@ impl HtmlTokenizer {
return;
}
+ // All of the input is consumed, so a preload scanner that has been given all of it can still go on from there.
+ self.speculative_scan_end = self
+ .speculative_scan_end
+ .filter(|end| *end == self.input.len())
+ .map(|_| 0);
self.input = Vec::new();
self.current_offset = 0;
self.prev_offset = 0;
diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
index e024ec4b2a0..ffb4a8a2983 100644
--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
@@ -34,20 +34,23 @@ namespace Web::HTML {
GC_DEFINE_ALLOCATOR(SpeculativeHTMLParser);
-GC::Ref<SpeculativeHTMLParser> SpeculativeHTMLParser::create(GC::Ref<DOM::Document> document, Utf16String pending_input, URL::URL base_url, ParserScriptingMode scripting_mode)
+GC::Ref<SpeculativeHTMLParser> SpeculativeHTMLParser::create(GC::Ref<DOM::Document> document, ParserScriptingMode scripting_mode)
{
- return document->relevant_settings_object().realm().create<SpeculativeHTMLParser>(document, move(pending_input), move(base_url), scripting_mode);
+ return document->relevant_settings_object().realm().create<SpeculativeHTMLParser>(document, scripting_mode);
}
-SpeculativeHTMLParser::SpeculativeHTMLParser(GC::Ref<DOM::Document> document, Utf16String pending_input, URL::URL base_url, ParserScriptingMode scripting_mode)
+SpeculativeHTMLParser::SpeculativeHTMLParser(GC::Ref<DOM::Document> document, ParserScriptingMode scripting_mode)
: m_document(document)
- , m_input(move(pending_input))
- , m_base_url(move(base_url))
- , m_scripting_mode(scripting_mode)
+ , m_scanner(rust_html_preload_scanner_create(scripting_mode != ParserScriptingMode::Disabled))
{
}
-SpeculativeHTMLParser::~SpeculativeHTMLParser() = default;
+void SpeculativeHTMLParser::finalize()
+{
+ Base::finalize();
+ rust_html_preload_scanner_destroy(m_scanner);
+ m_scanner = nullptr;
+}
void SpeculativeHTMLParser::visit_edges(JS::Cell::Visitor& visitor)
{
@@ -63,6 +66,20 @@ void SpeculativeHTMLParser::stop()
m_stopped = true;
}
+void SpeculativeHTMLParser::take_unscanned_input(RustFfiTokenizerHandle* tokenizer, URL::URL const& base_url)
+{
+ m_stopped = false;
+
+ // NB: A scan resolves URLs against the document's base URL as it was when the scan started, so once that has
+ // changed, the scan starts over.
+ auto start_over = base_url != m_document_base_url;
+ m_document_base_url = base_url;
+
+ // NB: A scan that starts over leaves behind any base element the last one found ahead of the parser.
+ if (!rust_html_preload_scanner_append_parser_input(m_scanner, tokenizer, start_over))
+ m_base_url = base_url;
+}
+
void SpeculativeHTMLParser::run()
{
if (m_stopped)
@@ -77,14 +94,7 @@ void SpeculativeHTMLParser::run()
return !parser.m_stopped;
};
- auto scripting_enabled = m_scripting_mode != ParserScriptingMode::Disabled;
- auto input = m_input.utf16_view();
- if (input.has_latin1_storage()) {
- rust_html_preload_scanner_scan_latin1(input.latin1_span(), scripting_enabled, this, scanner_callback);
- } else {
- auto code_units = input.utf16_span();
- rust_html_preload_scanner_scan_utf16({ reinterpret_cast<u16 const*>(code_units.data()), code_units.size() }, scripting_enabled, this, scanner_callback);
- }
+ rust_html_preload_scanner_scan(m_scanner, this, scanner_callback);
}
namespace {
diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.h b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.h
index d2f9057b930..e3d7dc5f497 100644
--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.h
+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.h
@@ -6,14 +6,15 @@
#pragma once
-#include <AK/Utf16String.h>
#include <LibGC/Ptr.h>
#include <LibJS/Heap/Cell.h>
#include <LibURL/URL.h>
#include <LibWeb/Forward.h>
#include <LibWeb/HTML/Parser/ParserScriptingMode.h>
+struct RustFfiPreloadScanner;
struct RustFfiPreloadScannerEntry;
+struct RustFfiTokenizerHandle;
namespace Web::HTML {
@@ -23,23 +24,27 @@ class SpeculativeHTMLParser final : public JS::Cell {
GC_DECLARE_ALLOCATOR(SpeculativeHTMLParser);
public:
- static GC::Ref<SpeculativeHTMLParser> create(GC::Ref<DOM::Document>, Utf16String pending_input, URL::URL base_url, ParserScriptingMode);
+ static GC::Ref<SpeculativeHTMLParser> create(GC::Ref<DOM::Document>, ParserScriptingMode);
- virtual ~SpeculativeHTMLParser() override;
+ // Takes the input of the parser's tokenizer that this hasn't scanned yet. That's the input from where the last run
+ // stopped, if the parser hasn't got past there, or else the parser's unparsed input, which a new scan starts on
+ // with the given base URL.
+ void take_unscanned_input(RustFfiTokenizerHandle*, URL::URL const& base_url);
void run();
void stop();
private:
- SpeculativeHTMLParser(GC::Ref<DOM::Document>, Utf16String pending_input, URL::URL base_url, ParserScriptingMode);
+ SpeculativeHTMLParser(GC::Ref<DOM::Document>, ParserScriptingMode);
virtual void visit_edges(JS::Cell::Visitor&) override;
+ virtual void finalize() override;
void process_preload_scanner_entry(RustFfiPreloadScannerEntry const&);
GC::Ref<DOM::Document> m_document;
- Utf16String m_input;
+ RustFfiPreloadScanner* m_scanner { nullptr };
URL::URL m_base_url;
- ParserScriptingMode m_scripting_mode {};
+ URL::URL m_document_base_url;
bool m_stopped { false };
};
diff --git a/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/base-url-change-restarts-scan.txt b/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/base-url-change-restarts-scan.txt
new file mode 100644
index 00000000000..3c76efe5df0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/base-url-change-restarts-scan.txt
@@ -0,0 +1,2 @@
+PASS: speculative parser fetched the image against the first base URL while the first script was held
+PASS: speculative parser fetched the image against the new base URL while the second script was held
diff --git a/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/document-write-before-scanned-input.txt b/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/document-write-before-scanned-input.txt
new file mode 100644
index 00000000000..ee49b357adf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/speculative-html-parser/document-write-before-scanned-input.txt
@@ -0,0 +1,2 @@
+PASS: speculative parser fetched the image after the scripts while the first script was held
+PASS: speculative parser fetched the written image while the written script was held
diff --git a/Tests/LibWeb/Text/input/HTML/speculative-html-parser/base-url-change-restarts-scan.html b/Tests/LibWeb/Text/input/HTML/speculative-html-parser/base-url-change-restarts-scan.html
new file mode 100644
index 00000000000..712ed3fd720
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/speculative-html-parser/base-url-change-restarts-scan.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const run = crypto.randomUUID();
+ const firstGate = `${run}-first`;
+ const secondGate = `${run}-second`;
+ const path = name => `/speculative-html-parser-base-${run}-${name}`;
+ const javascriptHeaders = { "Content-Type": "text/javascript" };
+ const imageHeaders = { "Content-Type": "image/png" };
+
+ const firstBlockerURL = await server.createEcho("GET", path("first-blocker.js"), {
+ status: 200,
+ headers: javascriptHeaders,
+ body: "",
+ wait_for_unblock: firstGate,
+ });
+ const secondBlockerURL = await server.createEcho("GET", path("second-blocker.js"), {
+ status: 200,
+ headers: javascriptHeaders,
+ body: "",
+ wait_for_unblock: secondGate,
+ });
+ const oldImageURL = await server.createEcho("GET", path("old/photo.png"), { status: 200, headers: imageHeaders, body: "" });
+ const newImageURL = await server.createEcho("GET", path("new/photo.png"), { status: 200, headers: imageHeaders, body: "" });
+ const oldBase = new URL(".", oldImageURL).href;
+ const newBase = new URL(".", newImageURL).href;
+
+ // While the parser waits for the first script, the speculative parser finds the image and resolves its URL
+ // against the document's base URL. The script after it changes that base URL, so the speculative parser started
+ // for the second script resolves the image's URL against the new one.
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageBody = `<!DOCTYPE html>
+ <base href="${oldBase}">
+ ${scriptStartTag} src="${firstBlockerURL}">${scriptEndTag}
+ ${scriptStartTag}>document.querySelector("base").href = "${newBase}";${scriptEndTag}
+ ${scriptStartTag} src="${secondBlockerURL}">${scriptEndTag}
+ <img src="photo.png">`;
+ const pageURL = await server.createEcho("GET", path("page.html"), {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: pageBody,
+ });
+
+ const hasRecordedRequest = async url => {
+ try {
+ const response = await fetch(server.recordedRequestHeadersURL(url));
+ return response.ok;
+ } catch {
+ return false;
+ }
+ };
+
+ const frame = document.createElement("iframe");
+ const frameLoaded = new Promise(resolve => (frame.onload = resolve));
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+
+ while (!(await hasRecordedRequest(oldImageURL))) {}
+ println("PASS: speculative parser fetched the image against the first base URL while the first script was held");
+
+ await fetch(`${server.baseURL}/unblock/${firstGate}`);
+
+ // Only the speculative parser can request the image against the new base URL while the second script is held.
+ while (!(await hasRecordedRequest(newImageURL))) {}
+ println("PASS: speculative parser fetched the image against the new base URL while the second script was held");
+
+ await fetch(`${server.baseURL}/unblock/${secondGate}`);
+ await frameLoaded;
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/speculative-html-parser/document-write-before-scanned-input.html b/Tests/LibWeb/Text/input/HTML/speculative-html-parser/document-write-before-scanned-input.html
new file mode 100644
index 00000000000..38a3bfdf64e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/speculative-html-parser/document-write-before-scanned-input.html
@@ -0,0 +1,72 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const run = crypto.randomUUID();
+ const firstGate = `${run}-first`;
+ const writtenGate = `${run}-written`;
+ const path = name => `/speculative-html-parser-write-${run}-${name}`;
+ const javascriptHeaders = { "Content-Type": "text/javascript" };
+ const imageHeaders = { "Content-Type": "image/png" };
+
+ const firstBlockerURL = await server.createEcho("GET", path("first-blocker.js"), {
+ status: 200,
+ headers: javascriptHeaders,
+ body: "",
+ wait_for_unblock: firstGate,
+ });
+ const writtenBlockerURL = await server.createEcho("GET", path("written-blocker.js"), {
+ status: 200,
+ headers: javascriptHeaders,
+ body: "",
+ wait_for_unblock: writtenGate,
+ });
+ const afterImageURL = await server.createEcho("GET", path("after.png"), { status: 200, headers: imageHeaders, body: "" });
+ const writtenImageURL = await server.createEcho("GET", path("written.png"), { status: 200, headers: imageHeaders, body: "" });
+
+ // While the parser waits for the first script, the speculative parser scans the rest of the page. The script
+ // after it then writes a parser-blocking script and an image ahead of the input scanned already, and the
+ // speculative parser started for the written script has to scan the written image too.
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const pageBody = `<!DOCTYPE html>
+ ${scriptStartTag} src="${firstBlockerURL}">${scriptEndTag}
+ ${scriptStartTag}>
+ document.write('${scriptStartTag} src="${writtenBlockerURL}"><\\/script><img src="${writtenImageURL}">');
+ ${scriptEndTag}
+ <img src="${afterImageURL}">`;
+ const pageURL = await server.createEcho("GET", path("page.html"), {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: pageBody,
+ });
+
+ const hasRecordedRequest = async url => {
+ try {
+ const response = await fetch(server.recordedRequestHeadersURL(url));
+ return response.ok;
+ } catch {
+ return false;
+ }
+ };
+
+ const frame = document.createElement("iframe");
+ const frameLoaded = new Promise(resolve => (frame.onload = resolve));
+ frame.src = pageURL;
+ document.body.appendChild(frame);
+
+ while (!(await hasRecordedRequest(afterImageURL))) {}
+ println("PASS: speculative parser fetched the image after the scripts while the first script was held");
+
+ await fetch(`${server.baseURL}/unblock/${firstGate}`);
+
+ // Only the speculative parser can request the written image while the written script is held.
+ while (!(await hasRecordedRequest(writtenImageURL))) {}
+ println("PASS: speculative parser fetched the written image while the written script was held");
+
+ await fetch(`${server.baseURL}/unblock/${writtenGate}`);
+ await frameLoaded;
+ done();
+ });
+</script>