Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(parser): preserve reentrant insertion state and reaction order
ldm03dcfac52786a
diff --git a/moli-parser/src/html.rs b/moli-parser/src/html.rsindex d51e912c4..4091fb6d9 100644--- a/moli-parser/src/html.rs+++ b/moli-parser/src/html.rs@@ -67,7 +67,7 @@ struct ParserInputState {pub struct DocumentStream {inner: HtmlTreeSinkStream,- input: HtmlParserInputStream,+ input: RefCell<HtmlParserInputStream>,}#[derive(Debug, Default)]@@ -314,6 +314,9 @@ pub struct ParserBlockingStylesheetPause {#[derive(Debug, Clone)]pub enum ParserYield {+ /// A synchronous callback suspended or canceled this parser. The owner+ /// already holds the blocker; this yield transfers no new work.+ OwnerInterrupted,Script(Box<ParserScriptHandoff>),CustomElementConstruction(Box<ParserCustomElementConstructionHandoff>),BlockingStylesheet(ParserBlockingStylesheetPause),@@ -335,6 +338,9 @@ pub(super) struct ParseHandle {#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum ParseHandleIdentity {DomNode(NativeNodeId),+ // html5ever exposes only Script(handle) as an embedder yield. This marker+ // is translated to OwnerInterrupted before any DOM handle is inspected.+ OwnerInterrupted,// Standalone fragment parsing, like `Element.innerHTML` staging, only has a// context element name. Chromium keeps a real `context_element` next to the// `DocumentFragment` target; our detached staging parser uses this@@ -410,7 +416,7 @@ impl HtmlParser {}pub fn parse_dom_host(&self, final_url: Url, html: String) -> DomHost {- let mut stream = self.start_document(final_url);+ let stream = self.start_document(final_url);for chunk in html_chunks(&html) {stream.feed(chunk);}@@ -424,8 +430,7 @@ impl HtmlParser {) -> NativeDom {let target =ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots(final_url, false);- let mut stream =- HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled);+ let stream = HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled);for chunk in html_chunks(&html) {stream.feed(chunk);}@@ -481,7 +486,7 @@ impl HtmlParser {);let context_handle = ParseHandle::new_synthetic_fragment_context(Rc::new(context));let sink = DocumentSink::new(target);- let mut parser = HtmlParserSession::new_fragment(+ let parser = HtmlParserSession::new_fragment(sink,html_parse_opts_with_scripting(scripting_enabled),context_handle,@@ -524,7 +529,7 @@ impl HtmlParser {// SAFETY: `consumer` remains exclusively borrowed until the// constructor clears the sink bundle before returning.unsafe { ParserRuntimeDomSinks::from_consumer_without_element_creation(consumer) };- let mut stream = DocumentStream::new_live_fragment_root(+ let stream = DocumentStream::new_live_fragment_root(final_url,fragment_handle,owner_document_handle,@@ -552,7 +557,7 @@ impl DocumentStream {fn new_parser_stream(final_url: Url, scripting_enabled: bool) -> Self {Self {inner: new_parser_stream_html_tree_sink_stream(final_url, scripting_enabled),- input: HtmlParserInputStream::default(),+ input: RefCell::default(),}}@@ -567,7 +572,7 @@ impl DocumentStream {document_handle,scripting_enabled,),- input: HtmlParserInputStream::default(),+ input: RefCell::default(),}}@@ -594,7 +599,7 @@ impl DocumentStream {allow_declarative_shadow_roots,scripting_enabled,),- input: HtmlParserInputStream::default(),+ input: RefCell::default(),}}@@ -648,13 +653,13 @@ impl DocumentStream {)}- pub fn note_defined_autonomous_custom_element(&mut self, local_name: &str) {+ pub fn note_defined_autonomous_custom_element(&self, local_name: &str) {self.inner.note_defined_autonomous_custom_element(local_name);}pub fn drain_pending_custom_element_construction_handoffs(- &mut self,+ &self,) -> Vec<ParserCustomElementConstructionHandoff> {self.inner.drain_pending_custom_element_construction_handoffs()@@ -680,12 +685,12 @@ impl DocumentStream {self.inner.take_processed_insertion_meta_csp_count()}- pub fn feed(&mut self, chunk: &str) {+ pub fn feed(&self, chunk: &str) {self.inner.feed(chunk)}fn feed_with_runtime_dom_consumer_without_element_creation<T>(- &mut self,+ &self,chunk: &str,consumer: &mut T,) where@@ -696,7 +701,7 @@ impl DocumentStream {let sinks =unsafe { ParserRuntimeDomSinks::from_consumer_without_element_creation(consumer) };self.inner.enter_runtime_dom_sinks_parse_step(sinks);- let mut step = RuntimeDomSinksParserStep { stream: self };+ let step = RuntimeDomSinksParserStep { stream: self };step.feed(chunk);}@@ -705,9 +710,9 @@ impl DocumentStream {/// The tokenizer only receives a bounded prefix when the owner pumps the/// parser. Appending while a script or stylesheet blocks parsing therefore/// cannot advance the DOM commit frontier.- pub fn append_to_end(&mut self, chunk: String) {+ pub fn append_to_end(&self, chunk: String) {if !chunk.is_empty() {- self.input.end_segments.push_back(chunk);+ self.input.borrow_mut().end_segments.push_back(chunk);}}@@ -717,14 +722,20 @@ impl DocumentStream {/// continues writing while that input is blocked on a nested resource./// The input must remain after the blocked frame's unconsumed tail rather/// than becoming a newer nested insertion.- pub fn append_to_current_inserted_input(&mut self, chunk: &str) -> bool {+ pub fn append_to_current_inserted_input(&self, chunk: &str) -> bool {self.inner.append_to_current_inserted_input(chunk)}+ /// Insert at the active token's insertion point without opening a script+ /// frame. A parser reaction appends after the current frame's unread tail.+ pub fn append_at_current_insertion_point(&self, chunk: &str) {+ self.inner.append_at_current_insertion_point(chunk);+ }+pub fn has_pending_input(&self) -> bool {self.inner.has_script_input()|| self.inner.has_buffered_input()- || !self.input.end_segments.is_empty()+ || !self.input.borrow().end_segments.is_empty()}pub fn next_input_len(&self) -> usize {@@ -735,14 +746,14 @@ impl DocumentStream {.has_buffered_input().then(|| self.inner.buffered_input_len())})- .or_else(|| self.input.end_segments.front().map(String::len))+ .or_else(|| self.input.borrow().end_segments.front().map(String::len)).unwrap_or_default()}pub fn snapshot_pending_input(&self) -> String {let mut pending = self.inner.snapshot_script_input();pending.push_str(&self.inner.snapshot_buffered_input());- for segment in &self.input.end_segments {+ for segment in &self.input.borrow().end_segments {pending.push_str(segment);}pending@@ -750,10 +761,10 @@ impl DocumentStream {#[cfg(any(test, feature = "test-support"))]pub fn queued_end_segment_count_for_testing(&self) -> usize {- self.input.end_segments.len()+ self.input.borrow().end_segments.len()}- fn take_next_owned_input(&mut self, max_bytes: usize) -> (String, bool) {+ fn take_next_owned_input(&self, max_bytes: usize) -> (String, bool) {if let Some(input) = self.inner.take_next_script_input() {// One parser insertion is an atomic source segment. Splitting it// outside html5ever would let a remainder jump ahead of bytes the@@ -765,17 +776,17 @@ impl DocumentStream {return (String::new(), false);}- let Some(input) = self.input.end_segments.pop_front() else {+ let Some(input) = self.input.borrow_mut().end_segments.pop_front() else {return (String::new(), false);};let (prefix, remainder) = split_parser_input_prefix(input, max_bytes);if let Some(remainder) = remainder {- self.input.end_segments.push_front(remainder);+ self.input.borrow_mut().end_segments.push_front(remainder);}(prefix, false)}- pub fn pump_next_parser_step(&mut self, max_bytes: usize) -> ParserPumpOutcome {+ pub fn pump_next_parser_step(&self, max_bytes: usize) -> ParserPumpOutcome {let (chunk, inserted_source) = self.take_next_owned_input(max_bytes);if inserted_source {self.inner.pump_parser_inserted_step(&chunk)@@ -806,17 +817,17 @@ impl DocumentStream {/// Returning `ParserPumpStep::InputDrained` means:/// - the current input buffer has been consumed as far as html5ever can go for now/// - either there is no pending yield, or more bytes are needed before another boundary exists- pub fn pump_parser_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ pub fn pump_parser_step(&self, chunk: &str) -> ParserPumpOutcome {self.inner.pump_parser_step(chunk)}#[cfg(test)]- pub(crate) fn pump_parser_inserted_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ pub(crate) fn pump_parser_inserted_step(&self, chunk: &str) -> ParserPumpOutcome {self.inner.pump_parser_inserted_step(chunk)}pub fn pump_parser_step_with_runtime_dom_consumer<T>(- &mut self,+ &self,chunk: &str,consumer: &mut T,) -> ParserPumpOutcome@@ -833,7 +844,7 @@ impl DocumentStream {}pub fn pump_next_parser_step_with_runtime_dom_consumer<T>(- &mut self,+ &self,max_bytes: usize,consumer: &mut T,) -> ParserPumpOutcome@@ -847,12 +858,12 @@ impl DocumentStream {// parser-step Drop guard removes every erased callback before return.let sinks = unsafe { ParserRuntimeDomSinks::from_consumer(consumer) };self.inner.enter_runtime_dom_sinks_parse_step(sinks);- let mut step = RuntimeDomSinksParserStep { stream: self };+ let step = RuntimeDomSinksParserStep { stream: self };step.pump_next_parser_step(max_bytes)}pub fn pump_parser_step_with_runtime_dom_consumer_without_element_creation<T>(- &mut self,+ &self,chunk: &str,consumer: &mut T,) -> ParserPumpOutcome@@ -867,7 +878,7 @@ impl DocumentStream {}pub fn pump_parser_step_with_runtime_dom_consumers<T, E>(- &mut self,+ &self,chunk: &str,consumer: &mut T,element_consumer: &mut E,@@ -883,17 +894,17 @@ impl DocumentStream {}fn pump_parser_step_with_runtime_dom_sinks(- &mut self,+ &self,chunk: &str,sinks: ParserRuntimeDomSinks,) -> ParserPumpOutcome {self.inner.enter_runtime_dom_sinks_parse_step(sinks);- let mut step = RuntimeDomSinksParserStep { stream: self };+ let step = RuntimeDomSinksParserStep { stream: self };step.pump_parser_step(chunk)}pub fn pump_parser_inserted_step_with_runtime_dom_consumer<T>(- &mut self,+ &self,chunk: &str,consumer: &mut T,) -> ParserPumpOutcome@@ -910,12 +921,12 @@ impl DocumentStream {}fn pump_parser_inserted_step_with_runtime_dom_sinks(- &mut self,+ &self,chunk: &str,sinks: ParserRuntimeDomSinks,) -> ParserPumpOutcome {self.inner.enter_runtime_dom_sinks_parse_step(sinks);- let mut step = RuntimeDomSinksParserStep { stream: self };+ let step = RuntimeDomSinksParserStep { stream: self };step.pump_parser_inserted_step(chunk)}@@ -951,7 +962,7 @@ impl DocumentStream {}fn finish_with_runtime_dom_sinks(- mut self,+ self,sinks: ParserRuntimeDomSinks,) -> ParserFinishDiscoverySignals {self.inner.enter_runtime_dom_sinks_parse_step(sinks);@@ -974,23 +985,21 @@ impl DocumentStream {self.inner.snapshot_parser_stream_dom_host()}- pub fn take_parser_stream_null_custom_element_registry_elements(- &mut self,- ) -> Vec<NativeNodeId> {+ pub fn take_parser_stream_null_custom_element_registry_elements(&self) -> Vec<NativeNodeId> {self.inner.take_parser_stream_null_custom_element_registry_elements()}- pub fn take_parser_stream_dom_host(&mut self) -> DomHost {+ pub fn take_parser_stream_dom_host(&self) -> DomHost {self.inner.take_parser_stream_dom_host()}- pub fn restore_parser_stream_dom_host(&mut self, dom_host: DomHost) {+ pub fn restore_parser_stream_dom_host(&self, dom_host: DomHost) {self.inner.restore_parser_stream_dom_host(dom_host);}pub fn with_parser_stream_dom_host_for_bootstrap<R>(- &mut self,+ &self,f: impl FnOnce(DomHost) -> std::result::Result<R, Box<(anyhow::Error, DomHost)>>,) -> anyhow::Result<R> {let bootstrap_document = self.inner.take_parser_stream_dom_host();@@ -1006,29 +1015,29 @@ impl DocumentStream {}pub fn replace_parser_stream_document_from_snapshot(- &mut self,+ &self,document: ParserStreamDocumentSnapshot,) {self.inner.replace_parser_stream_document(document.into())}- pub fn drain_ready_parser_scripts(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_ready_parser_scripts(&self) -> Vec<NativeNodeId> {self.inner.drain_ready_parser_scripts()}- pub fn drain_discovered_async_prefetch_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_async_prefetch_candidates(&self) -> Vec<NativeNodeId> {self.inner.drain_discovered_async_prefetch_candidates()}- pub fn drain_discovered_modulepreload_link_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_modulepreload_link_candidates(&self) -> Vec<NativeNodeId> {self.inner.drain_discovered_modulepreload_link_candidates()}- pub fn drain_discovered_parser_meta_csp_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_parser_meta_csp_candidates(&self) -> Vec<NativeNodeId> {self.inner.drain_discovered_parser_meta_csp_candidates()}- pub fn mark_script_already_started(&mut self, node_id: NativeNodeId) {+ pub fn mark_script_already_started(&self, node_id: NativeNodeId) {// The streaming parser and the live runtime intentionally share DOM snapshots during// parse-time execution. When runtime code claims ownership of a parser-discovered script// without executing it immediately (phase 2 `defer` / external `async`), we still need@@ -1048,23 +1057,23 @@ impl DocumentStream {}struct RuntimeDomSinksParserStep<'a> {- stream: &'a mut DocumentStream,+ stream: &'a DocumentStream,}impl RuntimeDomSinksParserStep<'_> {- fn feed(&mut self, chunk: &str) {+ fn feed(&self, chunk: &str) {self.stream.inner.feed(chunk);}- fn pump_parser_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ fn pump_parser_step(&self, chunk: &str) -> ParserPumpOutcome {self.stream.pump_parser_step(chunk)}- fn pump_parser_inserted_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ fn pump_parser_inserted_step(&self, chunk: &str) -> ParserPumpOutcome {self.stream.inner.pump_parser_inserted_step(chunk)}- fn pump_next_parser_step(&mut self, max_bytes: usize) -> ParserPumpOutcome {+ fn pump_next_parser_step(&self, max_bytes: usize) -> ParserPumpOutcome {self.stream.pump_next_parser_step(max_bytes)}}@@ -1354,6 +1363,18 @@ impl Drop for ParserInputContext {}impl ParseHandle {+ pub(super) fn owner_interrupted() -> Self {+ Self {+ identity: ParseHandleIdentity::OwnerInterrupted,+ element_name: None,+ parser_flags: ParserElementFlags::default(),+ }+ }++ pub(super) fn is_owner_interrupted(&self) -> bool {+ self.identity == ParseHandleIdentity::OwnerInterrupted+ }+pub(super) fn new(node_id: NativeNodeId, element_name: Option<Rc<QualName>>) -> Self {Self {identity: ParseHandleIdentity::DomNode(node_id),@@ -1385,7 +1406,8 @@ impl ParseHandle {pub(super) fn dom_node_id(&self) -> Option<NativeNodeId> {match self.identity {ParseHandleIdentity::DomNode(node_id) => Some(node_id),- ParseHandleIdentity::SyntheticFragmentContext => None,+ ParseHandleIdentity::SyntheticFragmentContext+ | ParseHandleIdentity::OwnerInterrupted => None,}}@@ -1433,6 +1455,14 @@ impl DocumentSink {delivery.consume();}+ pub(super) fn finish_parser_dom_mutations(&self) -> std::ops::ControlFlow<()> {+ // Do not retain the target borrow while invoking JavaScript. The tree+ // builder calls this after updating its open-element stack, so nested+ // document.write() sees the completed token's insertion state.+ let finish = self.target.borrow().mutation_finisher();+ finish.map_or(std::ops::ControlFlow::Continue(()), |finish| finish())+ }+pub(super) fn new(target: ParserStreamHtmlTreeSinkTarget) -> Self {Self {target: RefCell::new(target),@@ -1837,7 +1867,7 @@ mod tests {}fn parse_test_document_with_scripting(html: &str, scripting_enabled: bool) -> NativeDom {- let mut stream = HtmlParser::with_scripting_enabled(scripting_enabled)+ let stream = HtmlParser::with_scripting_enabled(scripting_enabled).start_document(Url::parse("https://example.test/").expect("test url"));stream.feed(html);stream.finish()diff --git a/moli-parser/src/html_input.rs b/moli-parser/src/html_input.rsindex 684324874..5632df0a9 100644--- a/moli-parser/src/html_input.rs+++ b/moli-parser/src/html_input.rs@@ -22,6 +22,7 @@//! later runtime turn.use html5ever::{tendril::StrTendril, tokenizer::BufferQueue};+use std::rc::Rc;/// The tokenizer's current input plus suspended parent insertion frames.///@@ -29,8 +30,8 @@ use html5ever::{tendril::StrTendril, tokenizer::BufferQueue};/// is consumed from `current`, followed by `parents` in reverse order.#[derive(Default)]pub(super) struct InputStack {- current: BufferQueue,- parents: Vec<BufferQueue>,+ current: Rc<BufferQueue>,+ parents: Vec<Rc<BufferQueue>>,}impl InputStack {@@ -70,8 +71,12 @@ impl InputStack {}/// Return the queue that `html5ever` may consume in the current parser step.- pub(super) fn current(&self) -> &BufferQueue {- &self.current+ pub(super) fn current(&self) -> Rc<BufferQueue> {+ self.current.clone()+ }++ pub(super) fn is_current(&self, input: &Rc<BufferQueue>) -> bool {+ Rc::ptr_eq(&self.current, input)}/// Restore one parent after the current frame has been fully consumed.@@ -121,13 +126,14 @@ impl InputStack {/// nearest to farthest. No input is reparsed or otherwise transformed.pub(super) fn into_buffer(mut self) -> BufferQueue {while let Some(parent) = self.parents.pop() {- append_queue(parent, &self.current);+ append_queue(&parent, &self.current);}- self.current+ Rc::try_unwrap(self.current)+ .unwrap_or_else(|_| panic!("cannot finish an active tokenizer input"))}fn queues_in_consumption_order(&self) -> impl Iterator<Item = &BufferQueue> {- std::iter::once(&self.current).chain(self.parents.iter().rev())+ std::iter::once(self.current.as_ref()).chain(self.parents.iter().rev().map(Rc::as_ref))}}@@ -147,7 +153,7 @@ fn append_queue_snapshot(input: &BufferQueue, snapshot: &mut String) {}}-fn append_queue(source: BufferQueue, destination: &BufferQueue) {+fn append_queue(source: &BufferQueue, destination: &BufferQueue) {while let Some(chunk) = source.pop_front() {destination.push_back(chunk);}diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rsindex 52792b34f..a425a7a27 100644--- a/moli-parser/src/live_target.rs+++ b/moli-parser/src/live_target.rs@@ -26,12 +26,19 @@ use super::html_chunks;pub trait ParserMutationEffectConsumer {fn consume_parser_mutation_effects(&mut self, effects: DomMutationEffects);++ /// Run callbacks after the tree builder has completed the current token.+ /// Break if a callback suspended or canceled the owning parser session.+ fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {+ std::ops::ControlFlow::Continue(())+ }}#[derive(Clone, Copy)]struct ParserMutationEffectSink {data: NonNull<()>,consume: unsafe fn(NonNull<()>, DomMutationEffects),+ finish: unsafe fn(NonNull<()>) -> std::ops::ControlFlow<()>,}impl ParserMutationEffectSink {@@ -45,12 +52,25 @@ impl ParserMutationEffectSink {unsafe { data.cast::<T>().as_mut() }.consume_parser_mutation_effects(effects);}+ unsafe fn finish_impl<T: ParserMutationEffectConsumer>(+ data: NonNull<()>,+ ) -> std::ops::ControlFlow<()> {+ // SAFETY: the same scoped consumer owns both callbacks.+ unsafe { data.cast::<T>().as_mut() }.finish_parser_dom_mutations()+ }+Self {data: NonNull::from(consumer).cast(),consume: consume_impl::<T>,+ finish: finish_impl::<T>,}}+ fn finish(self) -> std::ops::ControlFlow<()> {+ // SAFETY: the parser step keeps the consumer alive until this callback returns.+ unsafe { (self.finish)(self.data) }+ }+fn consume(self, effects: DomMutationEffects) {// SAFETY: construction ties the raw pointer and callback to the same// consumer remains live for the current runtime-DOM sink step.@@ -1954,6 +1974,7 @@ pub(super) struct ParserStreamHtmlTreeSinkTarget {/// Runtime-owned read/mutation/effect sinks for the current parser step./// Present only while a runtime DOM sink step is active.runtime_dom_sinks: Option<ParserRuntimeDomSinks>,+ suspended_runtime_dom_sinks: Vec<ParserRuntimeDomSinks>,/// Set when html5ever resolves the next insertion point to template/// contents. The handle also identifies the inert owner Document to use/// when creating the next node.@@ -1984,6 +2005,13 @@ impl Drop for ParserRuntimeDomTargetStep<'_> {}impl ParserStreamHtmlTreeSinkTarget {+ pub(super) fn mutation_finisher(+ &self,+ ) -> Option<impl FnOnce() -> std::ops::ControlFlow<()> + use<>> {+ let sink = self.runtime_dom_sinks.as_ref()?.mutation_effect_sink();+ Some(move || sink.finish())+ }+fn new(final_url: Url) -> Self {Self::new_with_declarative_shadow_roots(final_url, true)}@@ -2000,6 +2028,7 @@ impl ParserStreamHtmlTreeSinkTarget {parser_owner_document_handle: Some(document_handle),parser_document_url: Some(final_url),runtime_dom_sinks: None,+ suspended_runtime_dom_sinks: Vec::new(),next_template_contents_insertion: None,open_template_element_depth: 0,pending_open_parser_element: None,@@ -2019,6 +2048,7 @@ impl ParserStreamHtmlTreeSinkTarget {parser_owner_document_handle: Some(document_handle),parser_document_url: Some(final_url),runtime_dom_sinks: None,+ suspended_runtime_dom_sinks: Vec::new(),next_template_contents_insertion: None,open_template_element_depth: 0,pending_open_parser_element: None,@@ -2055,6 +2085,7 @@ impl ParserStreamHtmlTreeSinkTarget {parser_owner_document_handle: Some(document_handle),parser_document_url: Some(final_url),runtime_dom_sinks: None,+ suspended_runtime_dom_sinks: Vec::new(),next_template_contents_insertion: None,open_template_element_depth: 0,pending_open_parser_element: None,@@ -2078,6 +2109,7 @@ impl ParserStreamHtmlTreeSinkTarget {parser_owner_document_handle: Some(owner_document_handle),parser_document_url: Some(final_url),runtime_dom_sinks: Some(runtime_dom_sinks),+ suspended_runtime_dom_sinks: Vec::new(),next_template_contents_insertion: None,open_template_element_depth: 0,pending_open_parser_element: None,@@ -3432,10 +3464,12 @@ impl ParserStreamHtmlTreeSinkTarget {pub(super) fn enter_runtime_dom_sinks_parse_step(&mut self, sinks: ParserRuntimeDomSinks) {assert!(- self.owned_dom_host.is_none() && self.runtime_dom_sinks.is_none(),- "parser target should not already hold an owned DOM backend or sink bundle when entering a runtime-DOM sink step"+ self.owned_dom_host.is_none(),+ "parser target should not hold an owned DOM backend when entering a runtime-DOM sink step");- self.runtime_dom_sinks = Some(sinks);+ if let Some(previous) = self.runtime_dom_sinks.replace(sinks) {+ self.suspended_runtime_dom_sinks.push(previous);+ }}#[cfg(test)]@@ -3462,7 +3496,7 @@ impl ParserStreamHtmlTreeSinkTarget {self.runtime_dom_sinks.is_some(),"parser target should hold runtime DOM sinks during a runtime-DOM sink step");- self.runtime_dom_sinks = None;+ self.runtime_dom_sinks = self.suspended_runtime_dom_sinks.pop();}pub(super) fn replace_parser_stream_document(&mut self, document: NativeDom) {@@ -3524,7 +3558,7 @@ pub(super) fn new_live_fragment_root_html_tree_sink_stream(allow_declarative_shadow_roots: bool,scripting_enabled: bool,) -> HtmlTreeSinkStream {- let mut stream = HtmlTreeSinkStream::from_fragment_target(+ let stream = HtmlTreeSinkStream::from_fragment_target(ParserStreamHtmlTreeSinkTarget::new_live_fragment_root(final_url,fragment_handle,@@ -3625,8 +3659,7 @@ fn parser_stream_html_tree_sink_target_builds_dom_and_records_parser_state() {let html = "<!doctype html><html><head><template id=t><span>inner</span></template><script>window.inline = true;</script><script async src=\"/async.js\"></script></head><body><div>hello</div></body></html>";let url = Url::parse("https://example.test/").expect("test url");- let mut live =- crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());+ let live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());for chunk in html_chunks(html) {live.feed(chunk);}@@ -3686,7 +3719,7 @@ fn parser_stream_async_prefetch_uses_shared_script_type_classification() {);let url = Url::parse("https://example.test/").expect("test url");- let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);for chunk in html_chunks(html) {live.feed(chunk);}@@ -3723,7 +3756,7 @@ fn parser_stream_discovers_modulepreload_link_candidates() {);let url = Url::parse("https://example.test/").expect("test url");- let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut modulepreload_candidates = Vec::new();for chunk in html_chunks(html) {let outcome = live.pump_parser_step(chunk);@@ -3757,8 +3790,7 @@ fn parser_stream_discovers_modulepreload_link_candidates() {fn parser_stream_html_tree_sink_target_matches_parser_for_parser_created_flag() {let html = "<!doctype html><html><body><script src=\"/app.js\"></script><style>@import url('/a.css');</style></body></html>";let url = Url::parse("https://example.test/").expect("test url");- let mut live =- crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());+ let live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());for chunk in html_chunks(html) {live.feed(chunk);}@@ -3783,7 +3815,7 @@ fn parser_stream_html_tree_sink_target_matches_parser_for_parser_created_flag()#[test]fn parser_stream_runtime_dom_sinks_pump_preserves_runtime_mutation_effects() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -3822,7 +3854,7 @@ fn parser_stream_runtime_dom_sinks_pump_preserves_runtime_mutation_effects() {#[test]fn parser_stream_runtime_dom_consumer_is_cleared_when_pump_unwinds() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -3919,7 +3951,7 @@ fn parser_stream_runtime_dom_sinks_routes_parser_state_writes_through_sink() {#[test]fn parser_stream_runtime_dom_sinks_routes_declarative_shadow_attach_through_sink() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -4011,7 +4043,7 @@ fn parser_stream_runtime_dom_sinks_routes_tree_adjacency_reads_through_sink() {#[test]fn parser_stream_runtime_dom_sinks_routes_script_planning_reads_through_sink() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -4075,7 +4107,7 @@ fn parser_stream_runtime_dom_sinks_routes_script_planning_reads_through_sink() {#[test]fn parser_stream_runtime_dom_sinks_routes_stylesheet_blocking_reads_through_sink() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -4122,7 +4154,7 @@ fn parser_stream_live_document_root_writes_detached_document() {let child_document = dom_host.create_detached_html_document_with_url(child_url.clone());let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();- let mut stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(+ let stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(child_url,child_document,);@@ -4181,7 +4213,7 @@ fn parser_stream_live_fragment_root_writes_fragment() {effects: &mut effects,panic_on_mutation: false,};- let mut stream = crate::DocumentStream::new_live_fragment_root_for_testing(+ let stream = crate::DocumentStream::new_live_fragment_root_for_testing(url,fragment,document,@@ -4305,7 +4337,7 @@ fn live_fragment_parser_uses_template_contents_owner_document() {#[test]fn parser_stream_element_creation_sink_can_own_token_attributes() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();@@ -4351,7 +4383,7 @@ fn parser_stream_element_creation_sink_can_own_token_attributes() {#[test]fn parser_stream_element_creation_request_reports_intended_parent() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);let mut dom_host = stream.take_parser_stream_dom_host();let document = dom_host.document_handle();let ptr = &mut dom_host as *mut DomHost;@@ -4438,7 +4470,7 @@ fn parser_stream_element_creation_sink_uses_live_document_root_handle() {let child_document = dom_host.create_detached_html_document_with_url(child_url.clone());let ptr = &mut dom_host as *mut DomHost;let mut effects = DomMutationEffects::default();- let mut stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(+ let stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(child_url,child_document,);@@ -4479,7 +4511,7 @@ fn parser_stream_element_creation_sink_uses_live_document_root_handle() {#[test]fn parser_stream_owned_bootstrap_builds_dom_without_mutation_owner() {let url = Url::parse("https://example.test/").expect("test url");- let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);stream.feed("<!doctype html><html><body><div id='a'></div><script src='/app.js'></script></body></html>",@@ -4503,7 +4535,7 @@ fn parser_stream_owned_bootstrap_builds_dom_without_mutation_owner() {fn parser_stream_does_not_prefetch_whitespace_type_async_script() {let html = "<!doctype html><html><head><script async src=\"/data.js\" type=\" \"></script></head><body></body></html>";let url = Url::parse("https://example.test/").expect("test url");- let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);+ let live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);for chunk in html_chunks(html) {live.feed(chunk);}diff --git a/moli-parser/src/session.rs b/moli-parser/src/session.rsindex c60fbedcb..ebb9dc58a 100644--- a/moli-parser/src/session.rs+++ b/moli-parser/src/session.rs@@ -1,4 +1,4 @@-use std::rc::Rc;+use std::{cell::RefCell, rc::Rc};use html5ever::{LocalName, Namespace, QualName};use html5ever::{@@ -25,11 +25,12 @@ pub(super) struct HtmlTreeSinkSession {pub(super) struct HtmlParserSession {tokenizer: Tokenizer<EmbedderPausingTreeBuilder>,- input: InputStack,+ input: RefCell<InputStack>,}pub(super) enum HtmlParserSessionResult {InputDrained,+ OwnerInterrupted,Script(ParseHandle),}@@ -59,10 +60,12 @@ impl EmbedderPausingTreeBuilder {}}-impl TokenSink for EmbedderPausingTreeBuilder {- type Handle = ParseHandle;-- fn process_token(&self, token: Token, line_number: u64) -> TokenSinkResult<Self::Handle> {+impl EmbedderPausingTreeBuilder {+ fn process_token_before_callbacks(+ &self,+ token: Token,+ line_number: u64,+ ) -> TokenSinkResult<ParseHandle> {let in_foreign_content = self.inner.adjusted_current_node_present_but_not_in_html_namespace();@@ -122,9 +125,24 @@ impl TokenSink for EmbedderPausingTreeBuilder {}TokenSinkResult::Continue}+}++impl TokenSink for EmbedderPausingTreeBuilder {+ type Handle = ParseHandle;++ fn process_token(&self, token: Token, line_number: u64) -> TokenSinkResult<Self::Handle> {+ let result = self.process_token_before_callbacks(token, line_number);+ if self.sink().finish_parser_dom_mutations().is_break() {+ // A nested parser invocation already handed its blocker to the+ // owner. Stop this outer feed before it consumes another token.+ return TokenSinkResult::Script(ParseHandle::owner_interrupted());+ }+ result+ }fn end(&self) {- self.inner.end()+ self.inner.end();+ let _ = self.sink().finish_parser_dom_mutations();}fn adjusted_current_node_present_but_not_in_html_namespace(&self) -> bool {@@ -138,7 +156,7 @@ impl HtmlParserSession {let tree_builder = EmbedderPausingTreeBuilder::new(sink, opts.tree_builder);Self {tokenizer: Tokenizer::new(tree_builder, opts.tokenizer),- input: InputStack::default(),+ input: RefCell::default(),}}@@ -160,14 +178,15 @@ impl HtmlParserSession {};Self {tokenizer: Tokenizer::new(tree_builder, tokenizer_options),- input: InputStack::default(),+ input: RefCell::default(),}}- pub(super) fn process(&mut self, input: StrTendril) {- self.input.push_back(input);+ pub(super) fn process(&self, input: StrTendril) {+ self.input.borrow_mut().push_back(input);+ let input = self.input.borrow().current();while let HtmlParserSessionResult::Script(_) =- feed_with_definitive_encoding(&self.tokenizer, self.input.current())+ feed_with_definitive_encoding(&self.tokenizer, &input){// Non-pump callers intentionally parse through embedder pauses. They have no// runtime owner to notify, so parser-side custom-element handoffs and@@ -176,11 +195,11 @@ impl HtmlParserSession {}}- pub(super) fn push_back(&mut self, input: StrTendril) {- self.input.push_back(input);+ pub(super) fn push_back(&self, input: StrTendril) {+ self.input.borrow_mut().push_back(input);}- pub(super) fn begin_inserted_input(&mut self, input: StrTendril) {+ pub(super) fn begin_inserted_input(&self, input: StrTendril) {if input.is_empty() {return;}@@ -189,31 +208,39 @@ impl HtmlParserSession {// restored. Prefer permanent unknown locations over reporting// plausible but incorrect document lines.self.tokenizer.sink.sink().mark_source_positions_unknown();- self.input.begin_inserted(input);+ self.input.borrow_mut().begin_inserted(input);}- pub(super) fn append_to_current_inserted_input(&mut self, input: StrTendril) -> bool {- self.input.append_to_current_inserted(input)+ pub(super) fn append_to_current_inserted_input(&self, input: StrTendril) -> bool {+ self.input.borrow_mut().append_to_current_inserted(input)+ }++ pub(super) fn append_at_current_insertion_point(&self, input: StrTendril) {+ self.tokenizer.sink.sink().mark_source_positions_unknown();+ self.input.borrow_mut().push_back(input);}pub(super) fn has_buffered_input(&self) -> bool {- self.input.has_input()+ self.input.borrow().has_input()}pub(super) fn buffered_input_len(&self) -> usize {- self.input.len()+ self.input.borrow().len()}pub(super) fn snapshot_buffered_input(&self) -> String {- self.input.snapshot()+ self.input.borrow().snapshot()}- pub(super) fn feed(&mut self) -> HtmlParserSessionResult {- let result = feed_with_definitive_encoding(&self.tokenizer, self.input.current());- if matches!(result, HtmlParserSessionResult::InputDrained) {+ pub(super) fn feed(&self) -> HtmlParserSessionResult {+ let input = self.input.borrow().current();+ let result = feed_with_definitive_encoding(&self.tokenizer, &input);+ if matches!(result, HtmlParserSessionResult::InputDrained)+ && self.input.borrow().is_current(&input)+ {// The restored parent is intentionally consumed by the next parser// step so each insertion depth keeps an explicit input boundary.- self.input.restore_parent_if_current_empty();+ self.input.borrow_mut().restore_parent_if_current_empty();}result}@@ -224,7 +251,7 @@ impl HtmlParserSession {pub(super) fn finish(self) -> ParserStreamHtmlTreeSinkTarget {let Self { tokenizer, input } = self;- let input_buffer = input.into_buffer();+ let input_buffer = input.into_inner().into_buffer();while let HtmlParserSessionResult::Script(_) =feed_with_definitive_encoding(&tokenizer, &input_buffer){@@ -245,7 +272,7 @@ impl HtmlParserSession {pub(super) fn finish_live_runtime_dom_sink_parser(self) -> ParserFinishDiscoverySignals {let Self { tokenizer, input } = self;- let input_buffer = input.into_buffer();+ let input_buffer = input.into_inner().into_buffer();while let HtmlParserSessionResult::Script(_) =feed_with_definitive_encoding(&tokenizer, &input_buffer){@@ -299,7 +326,11 @@ fn feed_with_definitive_encoding(TokenizerResult::EncodingIndicator(_) => {}TokenizerResult::Done => return HtmlParserSessionResult::InputDrained,TokenizerResult::Script(handle) => {- return HtmlParserSessionResult::Script(handle);+ return if handle.is_owner_interrupted() {+ HtmlParserSessionResult::OwnerInterrupted+ } else {+ HtmlParserSessionResult::Script(handle)+ };}}}diff --git a/moli-parser/src/stream.rs b/moli-parser/src/stream.rsindex f5257061f..61fa5876d 100644--- a/moli-parser/src/stream.rs+++ b/moli-parser/src/stream.rs@@ -9,7 +9,10 @@ use moli_stylesheet_blocking::{DocumentBlockingStylesheetSignature, StylesheetBlockingReadView,collect_document_owned_blocking_stylesheets_before_in_view,};-use std::collections::HashMap;+use std::{+ cell::{Cell, RefCell},+ collections::HashMap,+};use crate::script_planning::{ParserPlanningReadView, PrepareScriptOutcome, PreparedImportMap, PreparedScript,@@ -34,12 +37,13 @@ use super::{pub(super) struct HtmlTreeSinkStream {parser: HtmlParserSession,script_input: ParserInputQueue,- parser_script_positions: HashMap<NativeNodeId, usize>,- next_parser_script_position: usize,+ parser_script_positions: RefCell<HashMap<NativeNodeId, usize>>,+ next_parser_script_position: Cell<usize>,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum RawParserStep {+ OwnerInterrupted,Script(NativeNodeId),CustomElementConstruction,BlockingStylesheet(NativeNodeId),@@ -433,8 +437,8 @@ impl HtmlTreeSinkStream {Self {parser: session.parser,script_input: session.script_input,- parser_script_positions: HashMap::new(),- next_parser_script_position: 0,+ parser_script_positions: RefCell::default(),+ next_parser_script_position: Cell::new(0),}}@@ -455,19 +459,20 @@ impl HtmlTreeSinkStream {Self {parser: session.parser,script_input: session.script_input,- parser_script_positions: HashMap::new(),- next_parser_script_position: 0,+ parser_script_positions: RefCell::default(),+ next_parser_script_position: Cell::new(0),}}- fn parser_script_position(&mut self, node_id: NativeNodeId) -> usize {+ fn parser_script_position(&self, node_id: NativeNodeId) -> usize {*self.parser_script_positions+ .borrow_mut().entry(node_id).or_insert_with(|| {- let position = self.next_parser_script_position;- self.next_parser_script_position =- self.next_parser_script_position.saturating_add(1);+ let position = self.next_parser_script_position.get();+ self.next_parser_script_position+ .set(position.saturating_add(1));position})}@@ -500,7 +505,7 @@ impl HtmlTreeSinkStream {self.script_input.take_processed_insertion_meta_csp_count()}- pub fn feed(&mut self, chunk: &str) {+ pub fn feed(&self, chunk: &str) {if chunk.is_empty() {return;}@@ -508,11 +513,11 @@ impl HtmlTreeSinkStream {self.parser.process(StrTendril::from(chunk));}- pub fn pump_parser_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ pub fn pump_parser_step(&self, chunk: &str) -> ParserPumpOutcome {self.pump_parser_step_with_source(chunk, false)}- pub fn pump_parser_inserted_step(&mut self, chunk: &str) -> ParserPumpOutcome {+ pub fn pump_parser_inserted_step(&self, chunk: &str) -> ParserPumpOutcome {if chunk.is_empty() {return ParserPumpOutcome {result: ParserPumpStep::InputDrained,@@ -524,13 +529,18 @@ impl HtmlTreeSinkStream {self.pump_parser_step_with_source(chunk, true)}- pub fn append_to_current_inserted_input(&mut self, chunk: &str) -> bool {+ pub fn append_to_current_inserted_input(&self, chunk: &str) -> bool {self.parser.append_to_current_inserted_input(StrTendril::from(chunk))}+ pub fn append_at_current_insertion_point(&self, chunk: &str) {+ self.parser+ .append_at_current_insertion_point(StrTendril::from(chunk));+ }+fn pump_parser_step_with_source(- &mut self,+ &self,chunk: &str,inserted_source: bool,) -> ParserPumpOutcome {@@ -550,6 +560,7 @@ impl HtmlTreeSinkStream {&& !paused_for_custom_element&& self.peek_pending_blocking_stylesheet_pause().is_some();let result = match tokenizer_result {+ HtmlParserSessionResult::OwnerInterrupted => RawParserStep::OwnerInterrupted,HtmlParserSessionResult::Script(handle) if paused_for_custom_element => {debug_assert_eq!(self.peek_pending_custom_element_construction_handoff_placeholder(),@@ -583,7 +594,8 @@ impl HtmlTreeSinkStream {.collect::<HashMap<_, _>>();let handoff_parser_position = match result {RawParserStep::Script(node_id) => Some(self.parser_script_position(node_id)),- RawParserStep::CustomElementConstruction+ RawParserStep::OwnerInterrupted+ | RawParserStep::CustomElementConstruction| RawParserStep::BlockingStylesheet(_)| RawParserStep::InputDrained => None,};@@ -607,7 +619,8 @@ impl HtmlTreeSinkStream {prepare_parser_script(&*target, node_id, handoff_parser_position),))}- RawParserStep::CustomElementConstruction+ RawParserStep::OwnerInterrupted+ | RawParserStep::CustomElementConstruction| RawParserStep::BlockingStylesheet(_)| RawParserStep::InputDrained => None,};@@ -660,6 +673,8 @@ impl HtmlTreeSinkStream {ParserPumpStep::Yield(ParserYield::BlockingStylesheet(ParserBlockingStylesheetPause { node_id },))+ } else if let RawParserStep::OwnerInterrupted = result {+ ParserPumpStep::Yield(ParserYield::OwnerInterrupted)} else if let Some(handoff) = self.pop_pending_custom_element_construction_handoff() {ParserPumpStep::Yield(ParserYield::CustomElementConstruction(Box::new(handoff)))} else {@@ -715,66 +730,64 @@ impl HtmlTreeSinkStream {self.parser.sink().snapshot_parser_stream_dom_host()}- pub fn take_parser_stream_null_custom_element_registry_elements(- &mut self,- ) -> Vec<NativeNodeId> {+ pub fn take_parser_stream_null_custom_element_registry_elements(&self) -> Vec<NativeNodeId> {self.parser.sink().take_parser_stream_null_custom_element_registry_elements()}- pub fn take_parser_stream_dom_host(&mut self) -> DomHost {+ pub fn take_parser_stream_dom_host(&self) -> DomHost {self.parser.sink().take_parser_stream_dom_host()}- pub fn restore_parser_stream_dom_host(&mut self, dom_host: DomHost) {+ pub fn restore_parser_stream_dom_host(&self, dom_host: DomHost) {self.parser.sink().restore_parser_stream_dom_host(dom_host);}- pub(super) fn enter_runtime_dom_sinks_parse_step(&mut self, sinks: ParserRuntimeDomSinks) {+ pub(super) fn enter_runtime_dom_sinks_parse_step(&self, sinks: ParserRuntimeDomSinks) {self.parser.sink().enter_runtime_dom_sinks_parse_step(sinks);}- pub fn clear_runtime_dom_sinks_after_parse_step(&mut self) {+ pub fn clear_runtime_dom_sinks_after_parse_step(&self) {self.parser.sink().clear_runtime_dom_sinks_after_parse_step()}- pub fn replace_parser_stream_document(&mut self, document: NativeDom) {+ pub fn replace_parser_stream_document(&self, document: NativeDom) {self.parser.sink().replace_parser_stream_document(document);}- pub fn drain_ready_parser_scripts(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_ready_parser_scripts(&self) -> Vec<NativeNodeId> {self.parser.sink().drain_ready_parser_scripts()}- pub fn drain_discovered_async_prefetch_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_async_prefetch_candidates(&self) -> Vec<NativeNodeId> {self.parser.sink().drain_discovered_async_prefetch_candidates()}- pub fn drain_discovered_modulepreload_link_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_modulepreload_link_candidates(&self) -> Vec<NativeNodeId> {self.parser.sink().drain_discovered_modulepreload_link_candidates()}- pub fn drain_discovered_parser_meta_csp_candidates(&mut self) -> Vec<NativeNodeId> {+ pub fn drain_discovered_parser_meta_csp_candidates(&self) -> Vec<NativeNodeId> {self.parser.sink().drain_discovered_parser_meta_csp_candidates()}- pub fn note_defined_autonomous_custom_element(&mut self, local_name: &str) {+ pub fn note_defined_autonomous_custom_element(&self, local_name: &str) {self.parser.sink().note_defined_autonomous_custom_element(local_name);}pub fn drain_pending_custom_element_construction_handoffs(- &mut self,+ &self,) -> Vec<crate::html::ParserCustomElementConstructionHandoff> {self.parser.sink()@@ -794,7 +807,7 @@ impl HtmlTreeSinkStream {}fn pop_pending_custom_element_construction_handoff(- &mut self,+ &self,) -> Option<crate::html::ParserCustomElementConstructionHandoff> {self.parser.sink()@@ -805,12 +818,12 @@ impl HtmlTreeSinkStream {self.parser.sink().pending_blocking_stylesheet_pause()}- fn pop_pending_blocking_stylesheet_pause(&mut self) -> Option<NativeNodeId> {+ fn pop_pending_blocking_stylesheet_pause(&self) -> Option<NativeNodeId> {self.parser.sink().pop_pending_blocking_stylesheet_pause()}fn drain_discovered_blocking_stylesheet_inputs(- &mut self,+ &self,) -> Vec<moli_stylesheet_blocking::DocumentOwnedBlockingStylesheetDiscoveryInput> {self.parser.sink()@@ -823,7 +836,7 @@ impl HtmlTreeSinkStream {self.parser.sink().captured_blocking_stylesheet_signatures()}- pub fn mark_script_already_started(&mut self, node_id: NativeNodeId) {+ pub fn mark_script_already_started(&self, node_id: NativeNodeId) {self.parser.sink().mark_script_already_started(node_id);}@@ -1271,7 +1284,7 @@ mod tests {#[test]fn parser_stream_feed_continues_past_definitive_encoding_indicator() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1289,7 +1302,7 @@ mod tests {#[test]fn parser_stream_pump_continues_past_definitive_encoding_indicator() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1309,7 +1322,7 @@ mod tests {#[test]fn parser_stream_finish_continues_past_definitive_encoding_indicator() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let outcome = stream.pump_parser_step(concat!(@@ -1468,7 +1481,7 @@ mod tests {#[test]fn parser_handoff_preserves_defer_modes_for_owner_acceptance() {- let mut classic_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let classic_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let classic = classic_stream@@ -1483,7 +1496,7 @@ mod tests {assert_eq!(script.kind, ScriptKind::Classic);assert_eq!(script.mode, ScriptMode::Defer);- let mut module_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let module_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let module = module_stream@@ -1501,7 +1514,7 @@ mod tests {#[test]fn parser_stream_assigns_stable_positions_to_shadow_root_scripts() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let first = stream@@ -1535,7 +1548,7 @@ mod tests {#[test]fn parser_stream_keeps_ordinary_template_scripts_inert() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let handoff = stream@@ -1570,7 +1583,7 @@ mod tests {#[test]fn parser_handoff_keeps_import_maps_out_of_executable_script_lanes() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let result = stream@@ -1590,7 +1603,7 @@ mod tests {if source.contains("\"x\":\"/x.js\"")));- let mut external_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let external_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let result = external_stream@@ -1650,7 +1663,7 @@ mod tests {#[test]fn empty_src_parser_script_handoff_is_unprepared_not_fetchable() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1675,7 +1688,7 @@ mod tests {#[test]fn invalid_src_parser_script_handoff_preserves_preparation_failure() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1703,7 +1716,7 @@ mod tests {#[test]fn parser_script_handoff_uses_html5ever_line_with_unknown_column_across_input_chunks() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1728,7 +1741,7 @@ mod tests {#[test]fn nonempty_parser_inserted_input_permanently_degrades_source_locations() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1775,7 +1788,7 @@ mod tests {#[test]fn blocked_nested_writes_keep_each_input_at_its_insertion_depth() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1801,7 +1814,7 @@ mod tests {#[test]fn parser_token_crossing_inserted_and_original_input_stays_unknown() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1848,7 +1861,7 @@ mod tests {#[test]fn parser_inserted_character_reference_chunks_degrade_without_disrupting_parsing() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);let markup =@@ -1881,7 +1894,7 @@ mod tests {#[test]fn parser_original_source_uses_html5ever_line_without_tracking_utf16_columns() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1903,7 +1916,7 @@ mod tests {#[test]fn empty_parser_inserted_input_preserves_following_line_location() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1935,7 +1948,7 @@ mod tests {#[test]fn parser_stream_surfaces_inline_svg_script_handoff() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -1973,7 +1986,7 @@ mod tests {#[test]fn parser_stream_surfaces_self_closing_external_svg_script_handoff() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -2000,7 +2013,7 @@ mod tests {#[test]fn parser_stream_does_not_execute_svg_script_popped_by_an_ancestor_end_tag() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -2021,7 +2034,7 @@ mod tests {#[test]fn data_block_handoff_consumes_parser_inserted_prepare_state() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -2053,7 +2066,7 @@ mod tests {#[test]fn parser_stream_records_custom_element_construction_handoff_candidates() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);stream.note_defined_autonomous_custom_element("x-ready");@@ -2094,7 +2107,7 @@ mod tests {#[test]fn parser_stream_surfaces_multiple_custom_element_handoffs_one_at_a_time() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);stream.note_defined_autonomous_custom_element("x-ready");@@ -2137,7 +2150,7 @@ mod tests {#[test]fn parser_stream_custom_element_handoff_pauses_before_following_sibling_tokens() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);stream.note_defined_autonomous_custom_element("x-ready");@@ -2168,7 +2181,7 @@ mod tests {#[test]fn parser_stream_consumes_blocking_stylesheet_pause_before_resuming_tokenizer() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -2222,7 +2235,7 @@ mod tests {#[test]fn parser_stream_feed_consumes_custom_element_handoff_without_runtime_owner() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);stream.note_defined_autonomous_custom_element("x-ready");@@ -2254,7 +2267,7 @@ mod tests {#[test]fn parser_stream_does_not_record_custom_element_handoff_without_runtime_definition() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page.html").expect("test url"),);@@ -2311,8 +2324,7 @@ mod tests {#[test]fn parser_stream_caches_document_url_before_runtime_dom_takeover() {let url = Url::parse("https://example.test/page.html").expect("test url");- let mut stream =- DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());let dom_host = stream.take_parser_stream_dom_host();let cached_url = stream.with_stylesheet_blocking_read_view(|view| view.final_url_clone());@@ -2327,7 +2339,7 @@ mod tests {#[test]fn parser_stream_reports_style_import_blocker_before_classic_handoff() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page").expect("test url"),);@@ -2358,7 +2370,7 @@ mod tests {#[test]fn parser_stream_reports_split_connected_meta_csp_once_and_ignores_template_contents() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page").expect("test url"),);@@ -2392,7 +2404,7 @@ mod tests {#[test]fn parser_stream_reports_style_import_blocker_on_runtime_dom_sinks() {- let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(Url::parse("https://example.test/page").expect("test url"),);let mut dom_host = stream.take_parser_stream_dom_host();diff --git a/moli-parser/src/stylesheet_blocking.rs b/moli-parser/src/stylesheet_blocking.rsindex 44b704975..19722d5e9 100644--- a/moli-parser/src/stylesheet_blocking.rs+++ b/moli-parser/src/stylesheet_blocking.rs@@ -95,7 +95,7 @@ mod tests {#[test]fn parser_created_link_blocker_is_captured_before_link_processing_state_is_consumed() {let parser = HtmlParser::SCRIPTING_ENABLED;- let mut stream = parser.start_document(url::Url::parse("https://example.com/").unwrap());+ let stream = parser.start_document(url::Url::parse("https://example.com/").unwrap());stream.append_to_end("<!doctype html><html><head><link rel=stylesheet href='/slow.css'><script>window.x = 1;</script></head></html>".to_owned(),);diff --git a/moli-parser/src/xml_stream.rs b/moli-parser/src/xml_stream.rsindex 937bdb9c9..ff57d39b3 100644--- a/moli-parser/src/xml_stream.rs+++ b/moli-parser/src/xml_stream.rs@@ -29,7 +29,9 @@ use crate::{ParserPlanningReadView, ParserPumpOutcome, ParserPumpStep, ParserScriptHandoff, ParserYield,PreparedScript,html::ParseHandle,- live_target::{ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget},+ live_target::{+ ParserMutationEffectDelivery, ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget,+ },stream::prepare_parser_script_handoff_for_static_document,xml_tree_viewer::transform_parser_target_to_xml_tree_view,};@@ -84,6 +86,20 @@ enum RawXmlParserStep {InputDrained,}+impl XmlStreamDocumentSink {+ fn mutate_target(+ &self,+ mutation: impl FnOnce(&mut ParserStreamHtmlTreeSinkTarget) -> ParserMutationEffectDelivery,+ ) {+ let delivery = mutation(&mut self.target.borrow_mut().common);+ delivery.consume();+ let finish = self.target.borrow().common.mutation_finisher();+ if let Some(finish) = finish {+ let _ = finish();+ }+ }+}+impl XmlDocumentStream {/// Starts a raw XML stream. This is suitable for parser tests and inert/// consumers; executable top-level navigation uses@@ -647,11 +663,7 @@ impl TreeSink for XmlStreamDocumentSink {HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))}};- self.target- .borrow_mut()- .common- .append(parent.inner.node_id(), child)- .consume();+ self.mutate_target(|target| target.append(parent.inner.node_id(), child));}fn append_before_sibling(&self, sibling: &Self::Handle, child: XmlNodeOrText<Self::Handle>) {@@ -662,11 +674,7 @@ impl TreeSink for XmlStreamDocumentSink {HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))}};- self.target- .borrow_mut()- .common- .append_before_sibling(sibling.inner.node_id(), child)- .consume();+ self.mutate_target(|target| target.append_before_sibling(sibling.inner.node_id(), child));}fn append_based_on_parent_node(@@ -682,15 +690,13 @@ impl TreeSink for XmlStreamDocumentSink {HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))}};- self.target- .borrow_mut()- .common- .append_based_on_parent_node(+ self.mutate_target(|target| {+ target.append_based_on_parent_node(element.inner.node_id(),prev_element.inner.node_id(),child,)- .consume();+ });}fn append_doctype_to_document(@@ -699,15 +705,13 @@ impl TreeSink for XmlStreamDocumentSink {public_id: StrTendril,system_id: StrTendril,) {- self.target- .borrow_mut()- .common- .append_doctype(+ self.mutate_target(|target| {+ target.append_doctype(name.to_string(),public_id.to_string(),system_id.to_string(),)- .consume();+ });}fn mark_script_already_started(&self, node: &Self::Handle) {@@ -756,19 +760,13 @@ impl TreeSink for XmlStreamDocumentSink {}fn remove_from_parent(&self, target: &Self::Handle) {- self.target- .borrow_mut()- .common- .remove_from_parent(target.inner.node_id())- .consume();+ self.mutate_target(|parser| parser.remove_from_parent(target.inner.node_id()));}fn reparent_children(&self, node: &Self::Handle, new_parent: &Self::Handle) {- self.target- .borrow_mut()- .common- .reparent_children(node.inner.node_id(), new_parent.inner.node_id())- .consume();+ self.mutate_target(|target| {+ target.reparent_children(node.inner.node_id(), new_parent.inner.node_id())+ });}}diff --git a/moli-renderer-v8/src/custom_elements.rs b/moli-renderer-v8/src/custom_elements.rsindex 2832dd66a..506e3b4af 100644--- a/moli-renderer-v8/src/custom_elements.rs+++ b/moli-renderer-v8/src/custom_elements.rs@@ -65,6 +65,8 @@ pub(crate) use form_lifecycle::{dispatch_form_association_callback_if_needed, dispatch_form_disabled_callback_if_needed,enqueue_form_association_callback_if_needed,};+mod form_owner_mutation;+pub(crate) use form_owner_mutation::form_owner_mutation_effects_touch_html_form;mod form_lifecycle_scans;pub(crate) use form_lifecycle_scans::{dispatch_form_association_callbacks_for_all, dispatch_form_disabled_callbacks_in_subtree,diff --git a/moli-renderer-v8/src/custom_elements/form_owner_mutation.rs b/moli-renderer-v8/src/custom_elements/form_owner_mutation.rsnew file mode 100644index 000000000..2d1cc8970--- /dev/null+++ b/moli-renderer-v8/src/custom_elements/form_owner_mutation.rs@@ -0,0 +1,47 @@+use crate::{+ document_runtime::DomHandle,+ dom::native::{DomHost, DomMutationEffects},+};++pub(crate) fn form_owner_mutation_effects_touch_html_form(+ dom_host: &DomHost,+ effects: &DomMutationEffects,+) -> bool {+ effects+ .tree()+ .connected_roots()+ .iter()+ .chain(effects.tree().disconnected_roots())+ .copied()+ .any(|root| subtree_contains_html_form(dom_host, root))+ || effects+ .style()+ .child_list_mutations()+ .iter()+ .any(|mutation| {+ mutation+ .added_nodes()+ .iter()+ .chain(mutation.removed_nodes())+ .copied()+ .any(|root| subtree_contains_html_form(dom_host, root))+ })+}++fn subtree_contains_html_form(dom_host: &DomHost, root: DomHandle) -> bool {+ let mut stack = vec![root];+ while let Some(handle) = stack.pop() {+ if dom_host.is_html_element_named(handle, "form") {+ return true;+ }+ let mut child = dom_host.first_child(handle);+ while let Some(current) = child {+ stack.push(current);+ child = dom_host.next_sibling(current);+ }+ if let Some(shadow_root) = dom_host.shadow_root_handle(handle) {+ stack.push(shadow_root);+ }+ }+ false+}diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rsindex a18ae6d74..bf360f508 100644--- a/moli-renderer-v8/src/document_runtime.rs+++ b/moli-renderer-v8/src/document_runtime.rs@@ -202,7 +202,7 @@ impl std::fmt::Debug for ParserInsertionController {}impl ParserInsertionController {- fn for_stream(stream: &ParserStreamHandle) -> Self {+ pub(crate) fn for_stream(stream: &ParserStreamHandle) -> Self {let input_session = stream.borrow().script_input_session();Self {input_session,@@ -225,18 +225,6 @@ impl ParserInsertionController {let stream = stream.borrow();operation(&stream)}-- pub(crate) fn with_parser_stream_mut<R>(- &self,- operation: impl FnOnce(&mut crate::parser::DocumentStream) -> R,- ) -> R {- let stream = self- .parser_stream- .upgrade()- .expect("synchronous parser insertion permission outlived its parser session");- let mut stream = stream.borrow_mut();- operation(&mut stream)- }}/// The explicit bridge between parser-connected script execution and the@@ -2091,7 +2079,7 @@ mod tests {#[test]fn parser_roundtrip_through_live_runtime_keeps_style_import_text_before_later_script() {let parser = HtmlParser::SCRIPTING_ENABLED;- let mut stream = parser.start_document(Url::parse("https://example.com/").unwrap());+ let stream = parser.start_document(Url::parse("https://example.com/").unwrap());let html = "<!doctype html><html><head><script>window.start = 1;</script><style>@import url('/slow.css');</style><script>window.afterStyle = 1;</script><script src='/blocking.js'></script></head><body><div id='late'>late</div></body></html>";let crate::parser::ParserPumpStep::Yield(crate::parser::ParserYield::Script(_)) =@@ -2150,7 +2138,7 @@ mod tests {#[test]fn parser_roundtrip_after_live_dom_mutation_keeps_later_body_hidden() {let parser = HtmlParser::SCRIPTING_ENABLED;- let mut stream = parser.start_document(Url::parse("https://example.com/").unwrap());+ let stream = parser.start_document(Url::parse("https://example.com/").unwrap());let html = "<!doctype html><html><head><script>window.start = 1;</script><script>window.after = 1;</script></head><body><div id='late'>late</div></body></html>";let crate::parser::ParserPumpStep::Yield(crate::parser::ParserYield::Script(_)) =diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rsindex 41f31ad8b..daa76683a 100644--- a/moli-renderer-v8/src/document_runtime/document_write.rs+++ b/moli-renderer-v8/src/document_runtime/document_write.rs@@ -80,6 +80,13 @@ impl ParserMutationEffectConsumer for DocumentWriteParserMutationOwner<'_, '_, 'effects,);}+ fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {+ if self.targets_live_document() {+ self.runtime+ .run_pending_parser_post_step_runtime_work(self.scope, self.host_ptr);+ }+ std::ops::ControlFlow::Continue(())+ }}impl ParserDomReadConsumer for DocumentWriteParserMutationOwner<'_, '_, '_> {@@ -185,8 +192,6 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>self.host_ptr,mutation,);- self.runtime- .run_pending_parser_post_step_runtime_work(self.scope, self.host_ptr);}fn create_parser_element_without_attributes(@@ -1717,7 +1722,7 @@ impl DocumentRuntime {&mut self,scope: &mut v8::PinScope<'_, '_>,host_ptr: *mut JsContextHost,- stream: &mut DocumentStream,+ stream: &DocumentStream,input: DocumentWriteParserPumpInput<'_>,) -> DocumentWriteParserPumpStep {let outcome =@@ -2360,7 +2365,7 @@ impl DocumentRuntime {} else {DocumentWriteParserPumpInput::Ordinary(chunk.as_str())};- insertion_controller.with_parser_stream_mut(|stream| {+ insertion_controller.with_parser_stream(|stream| {self.pump_document_write_parser_step(scope, host_ptr, stream, input)})};@@ -2374,9 +2379,7 @@ impl DocumentRuntime {},} = parser_step;let discovered_parser_meta_csp_candidates = insertion_controller- .with_parser_stream_mut(- DocumentStream::drain_discovered_parser_meta_csp_candidates,- );+ .with_parser_stream(DocumentStream::drain_discovered_parser_meta_csp_candidates);for handle in &discovered_parser_meta_csp_candidates {self.process_parser_meta_content_security_policy(*handle);}@@ -2402,7 +2405,8 @@ impl DocumentRuntime {);match result {- ParserPumpStep::InputDrained => {+ ParserPumpStep::InputDrained+ | ParserPumpStep::Yield(ParserYield::OwnerInterrupted) => {return true;}ParserPumpStep::Yield(ParserYield::CustomElementConstruction(_handoff)) => {diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rsindex 605425618..86ec4dad8 100644--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs@@ -123,35 +123,15 @@ impl DocumentRuntime {&connected_roots,);}- if self.form_owner_mutation_effects_touch_html_form(&form_owner_effects) {+ if crate::custom_elements::form_owner_mutation_effects_touch_html_form(+ self.dom_host(),+ &form_owner_effects,+ ) {self.ensure_parser_custom_element_reaction_queue(host_ptr);crate::custom_elements::enqueue_form_association_callbacks_for_all(scope, host_ptr);}}- fn form_owner_mutation_effects_touch_html_form(&self, effects: &DomMutationEffects) -> bool {- let dom_host = self.dom_host();- effects- .tree()- .connected_roots()- .iter()- .chain(effects.tree().disconnected_roots())- .copied()- .any(|root| subtree_contains_html_form(dom_host, root))- || effects- .style()- .child_list_mutations()- .iter()- .any(|mutation| {- mutation- .added_nodes()- .iter()- .chain(mutation.removed_nodes())- .copied()- .any(|root| subtree_contains_html_form(dom_host, root))- })- }-pub(crate) fn parser_runtime_dom_node_exists(&mut self, node_id: DomHandle) -> bool {self.dom_host_mut_for_active_parser_step().node(node_id)@@ -873,24 +853,6 @@ pub(super) fn sync_style_sources_from_dom_mutation_effects(unsafe { &mut *host_ptr }.apply_stylesheet_owner_changes(effects.stylesheet_owners().changes());}-fn subtree_contains_html_form(dom_host: &DomHost, root: DomHandle) -> bool {- let mut stack = vec![root];- while let Some(handle) = stack.pop() {- if dom_host.is_html_element_named(handle, "form") {- return true;- }- let mut child = dom_host.first_child(handle);- while let Some(current) = child {- stack.push(current);- child = dom_host.next_sibling(current);- }- if let Some(shadow_root) = dom_host.shadow_root_handle(handle) {- stack.push(shadow_root);- }- }- false-}-#[cfg(test)]mod tests {use super::*;diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rsindex cfda37405..86fccc943 100644--- a/moli-renderer-v8/src/lib.rs+++ b/moli-renderer-v8/src/lib.rs@@ -152,7 +152,7 @@ pub(crate) fn parse_html_test_fixture_with_parser_outputs(Vec<parser::ParserScriptHandoff>,Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,) {- let mut stream = parser::HtmlParser::SCRIPTING_ENABLED.start_document(final_url);+ let stream = parser::HtmlParser::SCRIPTING_ENABLED.start_document(final_url);stream.append_to_end(html);let mut scripts = Vec::new();let mut blocking_stylesheets = Vec::new();diff --git a/moli-renderer-v8/src/live_document_parser.rs b/moli-renderer-v8/src/live_document_parser.rsindex af12ae5cd..9eacbd703 100644--- a/moli-renderer-v8/src/live_document_parser.rs+++ b/moli-renderer-v8/src/live_document_parser.rs@@ -15,6 +15,9 @@ use std::{};use url::Url;+mod insertion;+pub(crate) use insertion::ParserInsertionHandle;+pub(crate) type DocumentParserStreamHandle = Rc<RefCell<DocumentStream>>;type XmlDocumentParserStreamHandle = Rc<RefCell<XmlDocumentStream>>;@@ -32,7 +35,7 @@ pub(crate) trait LiveDocumentParserOwner:#[cfg(test)]fn pump_live_document_parser_step(- stream: &mut DocumentStream,+ stream: &DocumentStream,chunk: &str,owner: &mut impl LiveDocumentParserOwner,) -> ParserPumpOutcome {@@ -40,7 +43,7 @@ fn pump_live_document_parser_step(}fn pump_next_live_document_parser_step(- stream: &mut DocumentStream,+ stream: &DocumentStream,max_bytes: usize,owner: &mut impl LiveDocumentParserOwner,) -> ParserPumpOutcome {@@ -108,7 +111,7 @@ impl LiveDocumentParserStepAdvance {#[cfg(test)]fn advance_live_document_parser_step<Driver>(- stream: &mut DocumentStream,+ stream: &DocumentStream,parser_step: &str,driver: &mut Driver,) -> LiveDocumentParserStepAdvance@@ -121,7 +124,7 @@ where}fn advance_next_live_document_parser_step<Driver>(- stream: &mut DocumentStream,+ stream: &DocumentStream,max_bytes: usize,driver: &mut Driver,) -> LiveDocumentParserStepAdvance@@ -150,7 +153,11 @@ fn live_document_parser_advance_from_outcome(blocking_stylesheet_inputs: discovered_blocking_stylesheet_inputs,};let outcome = match result {- ParserPumpStep::InputDrained => LiveDocumentParserStepOutcome::InputBoundary,+ // An interrupted outer feed has no new handoff to deliver. Its owning+ // session already records the suspension/cancellation from reentry.+ ParserPumpStep::InputDrained | ParserPumpStep::Yield(ParserYield::OwnerInterrupted) => {+ LiveDocumentParserStepOutcome::InputBoundary+ }ParserPumpStep::Yield(ParserYield::CustomElementConstruction(handoff)) => {LiveDocumentParserStepOutcome::CustomElementConstructionHandoff(handoff)}@@ -302,6 +309,7 @@ impl DocumentParserLifecycleState {#[derive(Debug)]struct DocumentParserSessionControl {+ lifetime: DocumentParserLifetime,session_id: ParserSessionId,next_suspension_id: u64,pump_session_nesting_level: usize,@@ -314,10 +322,16 @@ struct DocumentParserSessionControl {pub(crate) struct DocumentParserSessionControlHandle(Rc<RefCell<DocumentParserSessionControl>>);impl DocumentParserSessionControlHandle {+ #[cfg(test)]pub(crate) fn new() -> Self {+ Self::with_lifetime(DocumentParserLifetime::Finite)+ }++ fn with_lifetime(lifetime: DocumentParserLifetime) -> Self {let session_id =ParserSessionId(NEXT_DOCUMENT_PARSER_SESSION_ID.fetch_add(1, Ordering::Relaxed));Self(Rc::new(RefCell::new(DocumentParserSessionControl {+ lifetime,session_id,next_suspension_id: 1,pump_session_nesting_level: 0,@@ -327,6 +341,22 @@ impl DocumentParserSessionControlHandle {})))}+ pub(crate) fn lifetime(&self) -> DocumentParserLifetime {+ self.0.borrow().lifetime+ }++ pub(crate) fn request_close(&self) -> DocumentParserCloseDisposition {+ self.0.borrow_mut().lifetime = DocumentParserLifetime::Closing;+ self.request_finish();+ if self.run_state() == DocumentParserRunState::Ready+ && self.parser_script_nesting_level() == 0+ {+ DocumentParserCloseDisposition::DrainNow+ } else {+ DocumentParserCloseDisposition::DeferredUntilReady+ }+ }+pub(crate) fn session_id(&self) -> ParserSessionId {self.0.borrow().session_id}@@ -586,8 +616,7 @@ impl ExecutableDocumentParserBackend {pub(crate) struct DocumentParserSession {backend: Option<ExecutableDocumentParserBackend>,- discovery_signals: LiveDocumentParserDiscoverySignals,- lifetime: DocumentParserLifetime,+ discovery_signals: Rc<RefCell<LiveDocumentParserDiscoverySignals>>,control: DocumentParserSessionControlHandle,}@@ -602,7 +631,7 @@ impl std::fmt::Debug for DocumentParserSession {.as_ref().map(ExecutableDocumentParserBackend::name),)- .field("lifetime", &self.lifetime)+ .field("lifetime", &self.lifetime()).field("session_id", &self.control.session_id()).field("run_state", &self.control.run_state()).field(@@ -623,7 +652,7 @@ struct DocumentParserDriver;impl DocumentParserDriver {#[cfg(test)]fn advance_step(- stream: &mut DocumentStream,+ stream: &DocumentStream,parser_step: &str,owner: &mut impl LiveDocumentParserOwner,) -> LiveDocumentParserStepAdvance {@@ -631,7 +660,7 @@ impl DocumentParserDriver {}fn advance_next_step(- stream: &mut DocumentStream,+ stream: &DocumentStream,max_bytes: usize,owner: &mut impl LiveDocumentParserOwner,) -> LiveDocumentParserStepAdvance {@@ -639,7 +668,7 @@ impl DocumentParserDriver {}fn note_defined_autonomous_custom_elements(- stream: &mut DocumentStream,+ stream: &DocumentStream,names: impl IntoIterator<Item = String>,) {for name in names {@@ -660,9 +689,7 @@ impl DocumentParserDriver {}#[cfg(test)]- fn take_null_custom_element_registry_elements(- stream: &mut DocumentStream,- ) -> Vec<NativeNodeId> {+ fn take_null_custom_element_registry_elements(stream: &DocumentStream) -> Vec<NativeNodeId> {stream.take_parser_stream_null_custom_element_registry_elements()}@@ -728,9 +755,8 @@ impl DocumentParserSession {backend: Some(ExecutableDocumentParserBackend::Html(new_document_parser_stream_handle(stream),)),- discovery_signals: LiveDocumentParserDiscoverySignals::default(),- lifetime,- control: DocumentParserSessionControlHandle::new(),+ discovery_signals: Rc::default(),+ control: DocumentParserSessionControlHandle::with_lifetime(lifetime),}}@@ -739,9 +765,8 @@ impl DocumentParserSession {backend: Some(ExecutableDocumentParserBackend::Xml(Rc::new(RefCell::new(stream,)))),- discovery_signals: LiveDocumentParserDiscoverySignals::default(),- lifetime,- control: DocumentParserSessionControlHandle::new(),+ discovery_signals: Rc::default(),+ control: DocumentParserSessionControlHandle::with_lifetime(lifetime),}}@@ -751,6 +776,16 @@ impl DocumentParserSession {.expect("a finished parser session no longer owns a backend")}+ pub(crate) fn insertion_handle(&self) -> Option<ParserInsertionHandle> {+ Some(ParserInsertionHandle {+ controller: crate::document_runtime::ParserInsertionController::for_stream(+ &self.html_stream_handle()?,+ ),+ control: self.control.clone(),+ discovery_signals: self.discovery_signals.clone(),+ })+ }+pub(crate) fn run_state(&self) -> DocumentParserRunState {self.control.run_state()}@@ -789,6 +824,7 @@ impl DocumentParserSession {self.control.stop(reason);}+ #[cfg(test)]pub(crate) fn stream_handle(&self) -> DocumentParserStreamHandle {self.html_stream_handle().expect("HTML parser stream requested from an XML document parser session")@@ -802,32 +838,20 @@ impl DocumentParserSession {}pub(crate) fn lifetime(&self) -> DocumentParserLifetime {- self.lifetime+ self.control.lifetime()}pub(crate) fn request_close(&mut self) -> DocumentParserCloseDisposition {- self.lifetime = DocumentParserLifetime::Closing;- self.control.request_finish();- if self.run_state() == DocumentParserRunState::Ready- && self.control.parser_script_nesting_level() == 0- {- DocumentParserCloseDisposition::DrainNow- } else {- DocumentParserCloseDisposition::DeferredUntilReady- }+ self.control.request_close()}pub(crate) fn finishes_on_empty_input(&self) -> bool {matches!(- self.lifetime,+ self.lifetime(),DocumentParserLifetime::Finite | DocumentParserLifetime::Closing)}- pub(crate) fn is_suspended(&self) -> bool {- matches!(self.run_state(), DocumentParserRunState::Suspended { .. })- }-pub(crate) fn suspension_cause(&self) -> Option<ParserSuspensionCause> {match self.run_state() {DocumentParserRunState::Suspended { cause, .. } => Some(cause),@@ -859,10 +883,7 @@ impl DocumentParserSession {names: impl IntoIterator<Item = String>,) {if let ExecutableDocumentParserBackend::Html(stream) = self.backend() {- DocumentParserDriver::note_defined_autonomous_custom_elements(- &mut stream.borrow_mut(),- names,- );+ DocumentParserDriver::note_defined_autonomous_custom_elements(&stream.borrow(), names);}}@@ -877,15 +898,6 @@ impl DocumentParserSession {}}- pub(crate) fn append_to_current_inserted_input(&mut self, source: &str) -> bool {- match self.backend() {- ExecutableDocumentParserBackend::Html(stream) => {- stream.borrow_mut().append_to_current_inserted_input(source)- }- ExecutableDocumentParserBackend::Xml(_) => false,- }- }-pub(crate) fn declare_eof(&mut self) {if let ExecutableDocumentParserBackend::Xml(stream) = self.backend() {stream.borrow_mut().declare_eof();@@ -975,7 +987,7 @@ impl DocumentParserSession {let _pump_guard = self.control.begin_pump();let advance = match self.backend() {ExecutableDocumentParserBackend::Html(stream) => {- DocumentParserDriver::advance_next_step(&mut stream.borrow_mut(), max_bytes, owner)+ DocumentParserDriver::advance_next_step(&stream.borrow(), max_bytes, owner)}ExecutableDocumentParserBackend::Xml(stream) => {let mut stream = stream.borrow_mut();@@ -986,7 +998,9 @@ impl DocumentParserSession {live_document_parser_advance_from_outcome(outcome, parser_meta_csp_candidates)}};- self.discovery_signals.extend(advance.discovery_signals);+ self.discovery_signals+ .borrow_mut()+ .extend(advance.discovery_signals);advance.outcome}@@ -1009,12 +1023,14 @@ impl DocumentParserSession {}};let (outcome, discovery_signals) = advance.split();- self.discovery_signals.extend(discovery_signals);+ self.discovery_signals+ .borrow_mut()+ .extend(discovery_signals);(outcome, null_custom_element_registry_elements)}pub(crate) fn take_discovery_signals(&mut self) -> LiveDocumentParserDiscoverySignals {- std::mem::take(&mut self.discovery_signals)+ std::mem::take(&mut *self.discovery_signals.borrow_mut())}pub(crate) fn with_parser_stream_dom_host_for_bootstrap<R>(@@ -1067,7 +1083,7 @@ impl DocumentParserSession {"a live document parser may only finish after all parser-owned input is drained");self.control.begin_finish();- let mut discovery_signals = std::mem::take(&mut self.discovery_signals);+ let mut discovery_signals = std::mem::take(&mut *self.discovery_signals.borrow_mut());let backend = self.backend.take()@@ -1087,26 +1103,11 @@ impl DocumentParserSession {}#[cfg(test)]- fn with_reentrant_stream_step<R>(&self, op: impl FnOnce(&mut DocumentStream) -> R) -> R {+ fn with_reentrant_stream_step<R>(&self, op: impl FnOnce(&DocumentStream) -> R) -> R {let stream = self.html_stream_handle().expect("reentrant insertion step requires an HTML parser stream");- let stream_ptr = stream.as_ref().as_ptr();- // SAFETY: The Rc keeps the DocumentStream allocation alive for this- // synchronous parser step, and phase-one parser turns run on the- // renderer owner thread. We intentionally avoid a RefCell guard here- // because TreeSink structural mutations synchronously deliver effects- // to a runtime mutation owner. Holding RefMut<DocumentStream> across- // that boundary would make parser-created custom element construction- // fail before the DOM-specific reentry rules can run.- //- // While this operation is active, callbacks must not reenter the same- // parser stream. Parser-connected scripts still yield through- // ParserScriptHandoff and are not run by the parser-tree-sink mutation- // owner. Custom element construction must enter the dynamic markup- // insertion guard before invoking page JS, so document.write/open/close- // throw before they can borrow this stream.- unsafe { op(&mut *stream_ptr) }+ op(&stream.borrow())}#[cfg(test)]diff --git a/moli-renderer-v8/src/live_document_parser/insertion.rs b/moli-renderer-v8/src/live_document_parser/insertion.rsnew file mode 100644index 000000000..7bcffdaa1--- /dev/null+++ b/moli-renderer-v8/src/live_document_parser/insertion.rs@@ -0,0 +1,91 @@+use super::{+ DocumentParserCloseDisposition, DocumentParserLifetime, DocumentParserRunState,+ DocumentParserSessionControlHandle, LiveDocumentParserDiscoverySignals,+ LiveDocumentParserOwner, LiveDocumentParserStepOutcome, ParserStopReason,+ ParserSuspensionCause, advance_next_live_document_parser_step,+};+use std::{cell::RefCell, rc::Rc};++/// Synchronous access to the owning session's input and control state.+/// This handle cannot finish a parser, replace its backend, or outlive its+/// owner's cancellation. It never owns a separate input queue or lifetime.+#[derive(Clone)]+pub(crate) struct ParserInsertionHandle {+ pub(super) controller: crate::document_runtime::ParserInsertionController,+ pub(super) control: DocumentParserSessionControlHandle,+ pub(super) discovery_signals: Rc<RefCell<LiveDocumentParserDiscoverySignals>>,+}++impl ParserInsertionHandle {+ pub(crate) fn control_handle(&self) -> DocumentParserSessionControlHandle {+ self.control.clone()+ }++ pub(crate) fn run_state(&self) -> DocumentParserRunState {+ self.control.run_state()+ }++ pub(crate) fn lifetime(&self) -> DocumentParserLifetime {+ self.control.lifetime()+ }++ pub(crate) fn request_close(&self) -> DocumentParserCloseDisposition {+ self.control.request_close()+ }++ pub(crate) fn is_suspended(&self) -> bool {+ matches!(self.run_state(), DocumentParserRunState::Suspended { .. })+ }++ pub(crate) fn suspend(&self, cause: ParserSuspensionCause) {+ let _ = self.control.suspend(cause);+ }++ pub(crate) fn stop(&self, reason: ParserStopReason) {+ self.control.stop(reason);+ }++ pub(crate) fn enqueue_script_input_html(&self, chunk: String) {+ self.controller+ .input_session()+ .enqueue_script_input_html(chunk);+ }++ pub(crate) fn append_to_current_inserted_input(&self, chunk: &str) -> bool {+ self.controller+ .with_parser_stream(|stream| stream.append_to_current_inserted_input(chunk))+ }++ pub(crate) fn append_at_current_insertion_point(&self, chunk: &str) {+ self.controller+ .with_parser_stream(|stream| stream.append_at_current_insertion_point(chunk));+ }++ pub(crate) fn queue_arrived_chunk(&self, chunk: String) {+ self.controller+ .with_parser_stream(|stream| stream.append_to_end(chunk));+ }++ pub(crate) fn input_is_empty(&self) -> bool {+ self.controller+ .with_parser_stream(|stream| !stream.has_pending_input())+ }++ pub(crate) fn advance_queued_or_resume_step(+ &self,+ owner: &mut impl LiveDocumentParserOwner,+ ) -> LiveDocumentParserStepOutcome {+ let _pump = self.control.begin_pump();+ let advance = self+ .controller+ .with_parser_stream(|stream| advance_next_live_document_parser_step(stream, 0, owner));+ self.discovery_signals+ .borrow_mut()+ .extend(advance.discovery_signals);+ advance.outcome+ }++ pub(crate) fn take_discovery_signals(&self) -> LiveDocumentParserDiscoverySignals {+ std::mem::take(&mut *self.discovery_signals.borrow_mut())+ }+}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rsindex 64b4c0b06..07f85fedc 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs@@ -930,28 +930,43 @@ pub(in crate::native_bridge::context_host) fn dispatch_child_document_readiness_document: v8::Local<'s, v8::Object>,ready_state: DocumentReadyState,) {- set_child_document_ready_state(scope, document, ready_state);- let _ =- dispatch_detached_simple_event(scope, document, "readystatechange", false, false, false);+ if set_child_document_ready_state(scope, document, ready_state) {+ let _ = dispatch_detached_simple_event(+ scope,+ document,+ "readystatechange",+ false,+ false,+ false,+ );+ }}fn set_child_document_ready_state<'s>(scope: &mut v8::PinScope<'s, '_>,document: v8::Local<'s, v8::Object>,ready_state: DocumentReadyState,-) {+) -> bool {if let Some(state) = get_private_object(scope, document, DETACHED_STATE_SLOT) {if let Some(value) = v8_string(scope, ready_state.as_str()) {- let _ = state.set(scope, v8str(scope, "readyState").into(), value.into());+ let key = v8str(scope, "readyState").into();+ if state+ .get(scope, key)+ .is_some_and(|old| old.strict_equals(value.into()))+ {+ return false;+ }+ return state.set(scope, key, value.into()) == Some(true);}- return;+ return false;}if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)&& let Ok((object_host_ptr, document_handle)) =crate::native_bridge::node::node_runtime_and_handle_from_object(scope, document)&& object_host_ptr == host_ptr{- let _ = unsafe { &mut *host_ptr }+ return unsafe { &mut *host_ptr }.set_dom_document_ready_state_for_handle(document_handle, ready_state);}+ false}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rsindex 99acba783..787759578 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs@@ -58,6 +58,9 @@ struct ChildFrameLiveParserOwner<'a, 'scope, 'pin> {host: &'a mut JsContextHost,scope: &'a mut v8::PinScope<'scope, 'pin>,child_document_handle: DomHandle,+ document_owner: Option<FrameDocumentOwner>,+ parser_control: Option<crate::live_document_parser::DocumentParserSessionControlHandle>,+ reaction_queue_active: bool,}impl<'a, 'scope, 'pin> ChildFrameLiveParserOwner<'a, 'scope, 'pin> {@@ -66,10 +69,37 @@ impl<'a, 'scope, 'pin> ChildFrameLiveParserOwner<'a, 'scope, 'pin> {scope: &'a mut v8::PinScope<'scope, 'pin>,child_document_handle: DomHandle,) -> Self {+ let document_owner = host+ .child_browsing_context_host_for_document_handle(child_document_handle)+ .and_then(|child| host.frame_owner_store.current_child_document_owner(child));+ let parser_control = document_owner+ .and_then(|owner| host.child_document_parsers.insertion_handle(owner))+ .map(|insertion| insertion.control_handle());Self {host,scope,child_document_handle,+ document_owner,+ parser_control,+ reaction_queue_active: false,+ }+ }++ fn targets_current_document(&self) -> bool {+ self.host+ .child_browsing_context_host_for_document_handle(self.child_document_handle)+ .and_then(|child| {+ self.host+ .frame_owner_store+ .current_child_document_owner(child)+ })+ == self.document_owner+ }++ fn ensure_reaction_queue(&mut self) {+ if !self.reaction_queue_active {+ custom_elements::push_parser_custom_element_reaction_queue(self.host);+ self.reaction_queue_active = true;}}@@ -84,9 +114,6 @@ impl<'a, 'scope, 'pin> ChildFrameLiveParserOwner<'a, 'scope, 'pin> {self.host.dom_host(),effects,);- // Parser insertions enqueue reactions without introducing a checkpoint.- // document.write/close own their CEReactions scope; otherwise the backup- // queue runs at the next script or custom-element construction boundary.for &root in effects.tree().disconnected_roots() {custom_elements::enqueue_disconnected_callbacks_for_subtree(self.scope, host_ptr, root);}@@ -95,6 +122,12 @@ impl<'a, 'scope, 'pin> ChildFrameLiveParserOwner<'a, 'scope, 'pin> {host_ptr,effects.tree().connected_roots(),);+ if custom_elements::form_owner_mutation_effects_touch_html_form(+ self.host.dom_host(),+ effects,+ ) {+ custom_elements::enqueue_form_association_callbacks_for_all(self.scope, host_ptr);+ }self.host.sync_owner_style_sheet_texts_for_document_tree_scopes(self.child_document_handle);self.host@@ -154,8 +187,29 @@ impl StylesheetBlockingReadView for ChildFrameLiveParserOwner<'_, '_, '_> {impl ParserMutationEffectConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {fn consume_parser_mutation_effects(&mut self, effects: DomMutationEffects) {+ if !self.targets_current_document() {+ return;+ }+ self.ensure_reaction_queue();self.apply_child_parser_mutation_effects(&effects);}++ fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {+ if std::mem::take(&mut self.reaction_queue_active) {+ custom_elements::flush_parser_custom_element_reaction_queue(self.scope, self.host);+ }+ if !self.targets_current_document()+ || self.parser_control.as_ref().is_some_and(|control| {+ !matches!(+ control.run_state(),+ DocumentParserRunState::Ready | DocumentParserRunState::Pumping { .. }+ )+ })+ {+ return std::ops::ControlFlow::Break(());+ }+ std::ops::ControlFlow::Continue(())+ }}impl ParserDomReadConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {@@ -277,6 +331,13 @@ impl ParserDomReadConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {fn apply_parser_dom_mutation(&mut self, mutation: ParserDomMutation) {+ if !self.targets_current_document() {+ return;+ }+ // The tree sink invokes this queue after releasing its structural+ // borrow, before returning to the tree builder. Nested document.write+ // can then use the insertion point preceding this element's children.+ self.ensure_reaction_queue();let effects = mutation.apply_to_dom_host(self.host.dom_host_mut());self.apply_child_parser_mutation_effects(&effects);}@@ -438,6 +499,9 @@ impl ParserElementCreationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {&mut self,request: ParserElementCreationRequest<'_>,) -> Option<DomHandle> {+ if !self.targets_current_document() {+ return None;+ }let document_has_body = self.document_body_handle_for_document(request.document_handle).is_some();@@ -552,6 +616,34 @@ impl JsContextHost {true}+ fn advance_child_parser_step(+ &mut self,+ scope: &mut v8::PinScope<'_, '_>,+ child_handle: DomHandle,+ document_handle: DomHandle,+ parser: &mut DocumentParserSession,+ ) -> LiveDocumentParserStepOutcome {+ let owner = self+ .frame_owner_store+ .current_child_document_owner(child_handle)+ .expect("active child parser must own a document");+ let _active = parser+ .insertion_handle()+ .map(|handle| self.child_document_parsers.enter_active(owner, handle));+ let outcome = {+ let mut parser_owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);+ parser.advance_queued_or_resume_step(&mut parser_owner)+ };+ if self+ .frame_owner_store+ .current_child_document_owner(child_handle)+ != Some(owner)+ {+ parser.stop(ParserStopReason::DocumentReplacement);+ }+ outcome+ }+fn drive_live_child_document_parser(&mut self,scope: &mut v8::PinScope<'_, '_>,@@ -564,16 +656,27 @@ impl JsContextHost {parser.stop(ParserStopReason::DocumentReplacement);return ParserProgress::Stopped;}- let outcome = {- let mut owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);- parser.advance_queued_or_resume_step(&mut owner)- };+ let outcome =+ self.advance_child_parser_step(scope, child_handle, document_handle, parser);+ if matches!(parser.run_state(), DocumentParserRunState::Stopped(_)) {+ return ParserProgress::Stopped;+ }+ // Reentry may suspend the parser while this step is active. Admit+ // resources discovered by the outer step before parking it too.let discovery_signals = parser.take_discovery_signals();self.queue_live_child_parser_discovery_signals(child_handle,document_handle,discovery_signals,);+ if let Some(cause) = parser.suspension_cause() {+ return match cause {+ ParserSuspensionCause::ParserCreatedStylesheet { .. } => {+ ParserProgress::BlockedOnStylesheetPause+ }+ _ => ParserProgress::BlockedOnParserScript { ready_work: None },+ };+ }match outcome {LiveDocumentParserStepOutcome::InputBoundary => {if parser.input_is_empty() {@@ -1096,6 +1199,10 @@ impl JsContextHost {self.child_browsing_context_scripting_enabled(child_handle),);self.child_document_parsers.replace(owner, parser);+ let _ = self.set_dom_document_ready_state_for_handle(+ document_handle,+ crate::dom::native::DocumentReadyState::Loading,+ );}pub(in crate::native_bridge::context_host) fn child_document_parser_is_active(@@ -1122,93 +1229,102 @@ impl JsContextHost {else {return false;};- let Some(mut entry) = self.child_document_parsers.take(owner) else {+ let Some(insertion) = self.child_document_parsers.insertion_handle(owner) else {return !close_requested;};+ // Document.close() only supplies EOF to a script-created parser. A+ // navigation/srcdoc parser keeps its own input and completion owner.+ if close_requested && insertion.lifetime() == DocumentParserLifetime::Finite {+ return true;+ }let executing_parser_script =chunk.is_some() && self.child_document_is_executing_parser_script(document_handle);+ let nested_insertion = matches!(+ insertion.run_state(),+ DocumentParserRunState::Pumping { .. }+ );let parser_insertion_only = chunk.is_some()&& !close_requested- && (entry.lifetime() == DocumentParserLifetime::Finite || executing_parser_script);- let parser_ready_to_advance = if close_requested {- entry.request_close() == DocumentParserCloseDisposition::DrainNow+ && (insertion.lifetime() == DocumentParserLifetime::Finite+ || executing_parser_script+ || nested_insertion);+ let ready = if close_requested {+ insertion.request_close() == DocumentParserCloseDisposition::DrainNow} else {- entry.run_state() == DocumentParserRunState::Ready+ matches!(+ insertion.run_state(),+ DocumentParserRunState::Ready | DocumentParserRunState::Pumping { .. }+ )};if let Some(chunk) = chunk {- if parser_ready_to_advance {- entry- .stream_handle()- .borrow()- .script_input_session()- .enqueue_script_input_html(chunk);+ if nested_insertion && !executing_parser_script {+ // A reaction runs inside token consumption, not at a script+ // handoff. Keep the current insertion point: existing input+ // before it is consumed before this write's characters.+ insertion.append_at_current_insertion_point(&chunk);+ } else if ready || parser_insertion_only && !executing_parser_script {+ insertion.enqueue_script_input_html(chunk);} else if executing_parser_script {- if !entry.append_to_current_inserted_input(&chunk) {- tracing::warn!(- ?child_handle,- ?document_handle,- "child parser script write had no active inserted input frame"- );- entry- .stream_handle()- .borrow()- .script_input_session()- .enqueue_script_input_html(chunk);+ if !insertion.append_to_current_inserted_input(&chunk) {+ insertion.enqueue_script_input_html(chunk);}- } else if parser_insertion_only {- entry- .stream_handle()- .borrow()- .script_input_session()- .enqueue_script_input_html(chunk);} else {- // A write from outside the blocked child parser belongs after- // every input frame already owned by that parser. Treating it- // as a fresh script insertion would move it ahead of buffered- // tails from nested document.write() calls.- entry.queue_arrived_chunk(chunk);+ // Writes made outside the suspended parser belong after its+ // buffered insertion tails, in the owning session's input.+ insertion.queue_arrived_chunk(chunk);}}- if !parser_ready_to_advance {- self.child_document_parsers.replace(owner, entry);+ if !ready {return true;}loop {- if !self.live_child_parser_document_is_current(child_handle, document_handle) {- entry.stop(ParserStopReason::DocumentReplacement);+ if self+ .frame_owner_store+ .current_child_document_owner(child_handle)+ != Some(owner)+ || matches!(insertion.run_state(), DocumentParserRunState::Stopped(_))+ {+ insertion.stop(ParserStopReason::DocumentReplacement);return false;}+ if insertion.is_suspended() {+ return true;+ }let outcome = {let mut parser_owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);- entry.advance_queued_or_resume_step(&mut parser_owner)+ insertion.advance_queued_or_resume_step(&mut parser_owner)};- let discovery_signals = entry.take_discovery_signals();+ if matches!(insertion.run_state(), DocumentParserRunState::Stopped(_)) {+ return false;+ }self.queue_live_child_parser_discovery_signals(child_handle,document_handle,- discovery_signals,+ insertion.take_discovery_signals(),);+ if insertion.is_suspended() {+ return true;+ }match outcome {LiveDocumentParserStepOutcome::InputBoundary => {if parser_insertion_only {- // Script-inserted input parks after one boundary; the- // post-script resume drains the remaining stack in its- // own turn so following scripts keep their scheduler- // ordering.- self.child_document_parsers.replace(owner, entry);return true;}- if !entry.input_is_empty() {- // Draining one insertion frame restores its parent- // input inside the same feed and still reports an- // input boundary. Keep driving until the parser-owned- // input stack is truly empty before finishing or- // parking.+ if !insertion.input_is_empty() {continue;}- if entry.finishes_on_empty_input() {- if close_requested {+ if matches!(+ insertion.lifetime(),+ DocumentParserLifetime::Finite | DocumentParserLifetime::Closing+ ) {+ // Only the owning session may finish. All borrowed+ // insertion access must be gone before consuming it.+ drop(insertion);+ let Some(entry) = self.child_document_parsers.take(owner) else {+ return true;+ };+ if entry.lifetime() == DocumentParserLifetime::Closing {self.finish_child_document_write_parser_on_current_stack(scope,script_context,@@ -1226,94 +1342,61 @@ impl JsContextHost {entry,);}- } else {- self.child_document_parsers.replace(owner, entry);}return true;}LiveDocumentParserStepOutcome::CustomElementConstructionHandoff(handoff) => {- self.child_document_parsers.replace(owner, entry);let host_ptr = self as *mut JsContextHost;- let _ = crate::custom_elements::construct_parser_created_autonomous_element_from_handoff(- scope,- host_ptr,- &handoff,- );- crate::custom_elements::flush_parser_custom_element_handoff_replacements(+ let _ =+ custom_elements::construct_parser_created_autonomous_element_from_handoff(+ scope, host_ptr, &handoff,+ );+ custom_elements::flush_parser_custom_element_handoff_replacements(scope, host_ptr,);- let Some(next_entry) = self.child_document_parsers.take(owner) else {- return false;- };- entry = next_entry;}LiveDocumentParserStepOutcome::BlockingStylesheetPause(pause) => {- tracing::debug!(- child_handle = child_handle.index(),- stylesheet_node_id = pause.node_id.index(),- "child document.write parser paused on a body blocking stylesheet"- );if self.frame_document_blocking_stylesheets.has_pending(owner) {- Self::suspend_live_child_parser(- &mut entry,- ParserSuspensionCause::ParserCreatedStylesheet {- owner: pause.node_id,- },- );- self.child_document_parsers.replace(owner, entry);+ insertion.suspend(ParserSuspensionCause::ParserCreatedStylesheet {+ owner: pause.node_id,+ });return false;}}LiveDocumentParserStepOutcome::ScriptHandoff(handoff) => {- entry = match self.try_execute_child_document_write_inline_classic_handoff(+ if self.try_execute_child_document_write_inline_classic_handoff(scope,script_context,child_handle,document_handle,- owner,&handoff,- entry,) {- None => {- let Some(next_entry) = self.child_document_parsers.take(owner) else {- return false;- };- if next_entry.is_suspended() {- self.child_document_parsers.replace(owner, next_entry);- return true;+ continue;+ }+ match self.queue_live_child_parser_script_handoff(+ child_handle,+ document_handle,+ *handoff,+ ) {+ ScriptDisposition::Continue => {}+ ScriptDisposition::BlockedOnParserScript { cause, ready_work } => {+ insertion.suspend(cause);+ if let Some(ready_work) = ready_work {+ self.push_child_document_script_ready_input(*ready_work);}- next_entry+ return true;}- Some(mut entry) => {- let progress = self.queue_live_child_parser_script_handoff(+ ScriptDisposition::AdmissionFailed { script_handle } => {+ if !self.recover_current_child_parser_script_admission_failure(child_handle,document_handle,- *handoff,- );- match progress {- ScriptDisposition::Continue => entry,- ScriptDisposition::BlockedOnParserScript { cause, ready_work } => {- Self::suspend_live_child_parser(&mut entry, cause);- self.child_document_parsers.replace(owner, entry);- if let Some(ready_work) = ready_work {- self.push_child_document_script_ready_input(*ready_work);- }- return true;- }- ScriptDisposition::AdmissionFailed { script_handle } => {- if !self.recover_current_child_parser_script_admission_failure(- child_handle,- document_handle,- script_handle,- ) {- entry.stop(ParserStopReason::DocumentReplacement);- return false;- }- entry- }+ script_handle,+ ) {+ insertion.stop(ParserStopReason::DocumentReplacement);+ return false;}}- };+ }}}}@@ -1339,18 +1422,34 @@ impl JsContextHost {};let ready_work = self.apply_child_document_interactive_for_script_created_parser_close(scope, interactive);- let Some(work) = ready_work else {- return;- };// Blink runs the eligible defer head during parser close, then posts a// separate script task for the next item instead of draining the queue.- if let Some(next_work) = self.run_child_document_write_deferred_classic_on_current_stack(- scope,- script_context,- work,- ) {+ if let Some(work) = ready_work+ && let Some(next_work) = self+ .run_child_document_write_deferred_classic_on_current_stack(+ scope,+ script_context,+ work,+ )+ {self.push_child_document_script_ready_input(next_work);}+ // Document.close() makes a synchronously stopped script-created parser+ // complete before returning. DOMContentLoaded/load keep their queued+ // delivery, and must not repeat this readiness transition.+ if self+ .frame_owner_store+ .current_child_document_owner(child_handle)+ == Some(owner)+ && let Some(document) =+ self.child_browsing_context_document_wrapper(scope, child_handle)+ {+ super::lifecycle::dispatch_child_document_readiness_event(+ scope,+ document,+ crate::dom::native::DocumentReadyState::Complete,+ );+ }}fn run_child_document_write_deferred_classic_on_current_stack(@@ -1482,10 +1581,8 @@ impl JsContextHost {script_context: v8::Local<'_, v8::Context>,child_handle: DomHandle,document_handle: DomHandle,- owner: FrameDocumentOwner,handoff: &ParserScriptHandoff,- entry: DocumentParserSession,- ) -> Option<DocumentParserSession> {+ ) -> bool {let ParserScriptHandoff::BlockingClassic {node_id,start_line,@@ -1493,18 +1590,18 @@ impl JsContextHost {..} = handoffelse {- return Some(entry);+ return false;};let source = match (&script.kind, &script.source) {(ScriptKind::Classic, ScriptSource::Inline(source)) => source.clone(),- _ => return Some(entry),+ _ => return false,};let Some(mut job) = self.frame_owner_child_parser_classic_script_job(child_handle,Some(*node_id),source.clone(),) else {- return Some(entry);+ return false;};job.script_url = script.url.clone();job.base_url = script.base_url.clone();@@ -1512,7 +1609,6 @@ impl JsContextHost {if self.dom_host().containing_shadow_root(*node_id).is_some() {job.current_script = None;}- self.child_document_parsers.replace(owner, entry);let _ = self.dom_host_mut().set_script_already_started(*node_id, true);@@ -1533,7 +1629,7 @@ impl JsContextHost {};let Some(source) = source else {self.sync_child_browsing_context_subtree(scope, document_handle);- return None;+ return true;};job.source = FrameScriptSource::SourceText(source.clone());let current_script = self.push_frame_script_job_current_script(&job);@@ -1541,6 +1637,11 @@ impl JsContextHost {let entered_parser_script_nesting = parser_script_owner.is_some_and(|task_owner| {self.enter_child_parser_script_nesting(child_handle, task_owner)});+ let _parser_script_nesting = self+ .frame_owner_store+ .current_child_document_owner(child_handle)+ .and_then(|owner| self.child_document_parsers.insertion_handle(owner))+ .map(|insertion| insertion.control_handle().enter_parser_script_nesting());let result = {let script_scope = &mut v8::ContextScope::new(scope, script_context);crate::script_vm::execute_source_text_on_current_stack(@@ -1568,7 +1669,7 @@ impl JsContextHost {);}self.sync_child_browsing_context_subtree(scope, document_handle);- None+ true}pub(in crate::native_bridge::context_host) fn create_empty_live_child_html_document(diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rsindex 8e15266f7..1ba6ca0e1 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs@@ -3,23 +3,92 @@ use crate::live_document_parser::DocumentParserLifetime;use crate::{frame_owner_model::FrameDocumentOwner,live_document_parser::{- DocumentParserSession, ParserResumePermit, ParserStopReason, ParserSuspensionCause,+ DocumentParserRunState, DocumentParserSession, DocumentParserSessionControlHandle,+ ParserInsertionHandle, ParserResumePermit, ParserStopReason, ParserSuspensionCause,},};-use std::collections::HashMap;+use std::{cell::RefCell, collections::HashMap, rc::Rc};#[derive(Default)]pub(in crate::native_bridge::context_host) struct ChildDocumentParserStore {sessions: HashMap<FrameDocumentOwner, DocumentParserSession>,+ // A finite parser is owned by its driver while running. Expose only its+ // insertion capability for synchronous callbacks, until that step unwinds.+ active: Rc<RefCell<Vec<(FrameDocumentOwner, ParserInsertionHandle)>>>,+}++pub(in crate::native_bridge::context_host) struct ActiveChildParser {+ active: Rc<RefCell<Vec<(FrameDocumentOwner, ParserInsertionHandle)>>>,+ owner: FrameDocumentOwner,+}++impl Drop for ActiveChildParser {+ fn drop(&mut self) {+ let (owner, _) = self.active.borrow_mut().pop().expect("active parser scope");+ assert_eq!(+ owner, self.owner,+ "active parser scopes must unwind in order"+ );+ }}impl ChildDocumentParserStore {pub(in crate::native_bridge::context_host) fn clear(&mut self, owner: FrameDocumentOwner) {+ for (active_owner, handle) in self.active.borrow().iter() {+ if *active_owner == owner {+ handle.stop(ParserStopReason::DocumentReplacement);+ }+ }if let Some(mut parser) = self.sessions.remove(&owner) {parser.stop(ParserStopReason::DocumentReplacement);}}+ pub(in crate::native_bridge::context_host) fn enter_active(+ &self,+ owner: FrameDocumentOwner,+ handle: ParserInsertionHandle,+ ) -> ActiveChildParser {+ self.active.borrow_mut().push((owner, handle));+ ActiveChildParser {+ active: self.active.clone(),+ owner,+ }+ }++ pub(in crate::native_bridge::context_host) fn insertion_handle(+ &self,+ owner: FrameDocumentOwner,+ ) -> Option<ParserInsertionHandle> {+ self.sessions+ .get(&owner)+ .and_then(DocumentParserSession::insertion_handle)+ .or_else(|| {+ self.active+ .borrow()+ .iter()+ .rev()+ .find_map(|(active_owner, handle)| {+ (*active_owner == owner+ && !matches!(handle.run_state(), DocumentParserRunState::Stopped(_)))+ .then(|| handle.clone())+ })+ })+ }++ fn control_handle(+ &self,+ owner: FrameDocumentOwner,+ ) -> Option<DocumentParserSessionControlHandle> {+ self.sessions+ .get(&owner)+ .map(DocumentParserSession::control_handle)+ .or_else(|| {+ self.insertion_handle(owner)+ .map(|handle| handle.control_handle())+ })+ }+pub(in crate::native_bridge::context_host) fn replace(&mut self,owner: FrameDocumentOwner,@@ -54,7 +123,7 @@ impl ChildDocumentParserStore {&self,owner: FrameDocumentOwner,) -> bool {- self.sessions.contains_key(&owner)+ self.sessions.contains_key(&owner) || self.insertion_handle(owner).is_some()}pub(in crate::native_bridge::context_host) fn parser_script_resume_permit(@@ -62,16 +131,16 @@ impl ChildDocumentParserStore {owner: FrameDocumentOwner,script: crate::document_runtime::DomHandle,) -> Option<ParserResumePermit> {- let parser = self.sessions.get(&owner)?;+ let parser = self.control_handle(owner)?;if !matches!(- parser.suspension_cause(),- Some(+ parser.run_state(),+ DocumentParserRunState::Suspended { cause:ParserSuspensionCause::ParserClassicSource {script: suspended_script,} | ParserSuspensionCause::ParserClassicStylesheets {script: suspended_script,}- ) if suspended_script == script+ , .. } if suspended_script == script) {return None;}@@ -83,8 +152,7 @@ impl ChildDocumentParserStore {owner: FrameDocumentOwner,permit: ParserResumePermit,) -> Option<bool> {- self.sessions- .get_mut(&owner)+ self.control_handle(owner).map(|parser| parser.resume(permit))}@@ -92,12 +160,15 @@ impl ChildDocumentParserStore {&self,owner: FrameDocumentOwner,) -> bool {- self.sessions- .get(&owner)- .and_then(DocumentParserSession::suspension_cause)- .is_some_and(|cause| {- matches!(cause, ParserSuspensionCause::ParserCreatedStylesheet { .. })- })+ self.control_handle(owner).is_some_and(|control| {+ matches!(+ control.run_state(),+ DocumentParserRunState::Suspended {+ cause: ParserSuspensionCause::ParserCreatedStylesheet { .. },+ ..+ }+ )+ })}#[cfg(test)]@@ -163,4 +234,47 @@ mod tests {assert!(entry.finishes_on_empty_input());assert!(store.is_complete_for(owner));}++ #[test]+ fn active_child_parser_retains_writes_and_close_while_suspended() {+ let owner = FrameDocumentOwner::new(LocalWindowId(1), DocumentId(2));+ let mut parser = DocumentParserSession::start_open_live_document(+ Url::parse("https://child-parser-store.test/").unwrap(),+ NativeNodeId::new(1),+ true,+ );+ let store = ChildDocumentParserStore::default();+ let active = store.enter_active(owner, parser.insertion_handle().unwrap());+ let permit = parser.suspend(ParserSuspensionCause::ParserClassicSource {+ script: NativeNodeId::new(2),+ });+ let insertion = store.insertion_handle(owner).unwrap();+ insertion.queue_arrived_chunk("<p>first</p>".to_owned());+ insertion.queue_arrived_chunk("<p>second</p>".to_owned());+ assert_eq!(+ insertion.request_close(),+ crate::live_document_parser::DocumentParserCloseDisposition::DeferredUntilReady+ );+ drop(insertion);+ drop(active);++ assert_eq!(parser.snapshot_pending_input(), "<p>first</p><p>second</p>");+ assert_eq!(parser.lifetime(), DocumentParserLifetime::Closing);+ assert!(parser.resume(permit));+ assert_eq!(parser.run_state(), DocumentParserRunState::Ready);+ }++ #[test]+ fn replacing_document_cancels_active_child_parser_access() {+ let owner = FrameDocumentOwner::new(LocalWindowId(1), DocumentId(2));+ let parser = test_parser();+ let mut store = ChildDocumentParserStore::default();+ let _active = store.enter_active(owner, parser.insertion_handle().unwrap());+ store.clear(owner);+ assert!(!store.contains(owner));+ assert_eq!(+ parser.run_state(),+ DocumentParserRunState::Stopped(ParserStopReason::DocumentReplacement)+ );+ }}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rsindex 589cc348b..00ba4db29 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs@@ -432,14 +432,6 @@ fn child_document_close_callback<'s>(rv.set_undefined();return;}- if host.child_document_parser_is_active(handle)- && host- .child_current_script_handle_for_document(document_handle)- .is_some()- {- rv.set_undefined();- return;- }let script_context = match unsafe { &mut *host_ptr }.ensure_prebootstrapped_child_default_context(scope, handle){diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rsindex b64b3a71c..d3fac9339 100644--- a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs+++ b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs@@ -54,6 +54,12 @@ impl ParserMutationEffectConsumer for PhaseOneParserOwner<'_> {.vm.apply_parser_stream_mutation_effects_to_live_dom_host_in_default_context(effects);}+ fn finish_parser_dom_mutations(&mut self) -> std::ops::ControlFlow<()> {+ let _ = self+ .vm+ .run_pending_parser_post_step_runtime_work_in_default_context();+ std::ops::ControlFlow::Continue(())+ }}impl ParserDomReadConsumer for PhaseOneParserOwner<'_> {@@ -194,9 +200,6 @@ impl ParserDomMutationConsumer for PhaseOneParserOwner<'_> {let _ = self.vm.apply_parser_dom_mutation_to_live_dom_host_in_default_context(mutation);- let _ = self- .vm- .run_pending_parser_post_step_runtime_work_in_default_context();}fn create_parser_element_without_attributes(diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/parser.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/parser.rsindex dc403be2f..38081b023 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/parser.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/parser.rs@@ -41,7 +41,7 @@ fn child_parser_write_constructs_elements_and_runs_reactions_synchronously() {let expected = serde_json::json!({"custom": true,"button": true,- "log": ["construct:true", "title:null:parsed", "button", "connected", "button-connected"]+ "log": ["construct:true", "title:null:parsed", "connected", "button", "button-connected"]});assert_eq!(serde_json::from_str::<serde_json::Value>(&result).unwrap(),@@ -49,6 +49,363 @@ fn child_parser_write_constructs_elements_and_runs_reactions_synchronously() {);}+#[test]+fn child_parser_write_invokes_connected_before_children_and_next_constructor() {+ let mut vm = new_storage_test_vm("https://child-parser-insertion-reactions.test/");+ let result = vm+ .eval(+ r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = [];+ class A extends w.HTMLElement {+ constructor() { super(); log.push('ctor:a'); }+ connectedCallback() { log.push('connected:a:' + this.childNodes.length); }+ }+ class B extends w.HTMLElement {+ constructor() { super(); log.push('ctor:b'); }+ connectedCallback() { log.push('connected:b:' + this.childNodes.length); }+ }+ w.customElements.define('x-a', A);+ w.customElements.define('x-b', B);+ d.write('<x-a>hello <b>world</b></x-a><x-b></x-b>');+ const result = {log, text:d.querySelector('x-a').textContent};+ d.close(); frame.remove();+ return JSON.stringify(result);+ })()+ "#,+ )+ .unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["ctor:a", "connected:a:0", "ctor:b", "connected:b:0"],+ "text": "hello world"+ })+ );+}++#[test]+fn child_parser_write_associates_existing_face_when_form_is_inserted() {+ let mut vm = new_storage_test_vm("https://child-parser-form-reactions.test/");+ let result = vm+ .eval(+ r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = [];+ let internals;+ class Face extends w.HTMLElement {+ static formAssociated = true;+ constructor() { super(); internals = this.attachInternals(); log.push('ctor'); }+ connectedCallback() { log.push('connected:' + (internals.form?.id || 'null')); }+ formAssociatedCallback(form) { log.push('form:' + (form?.id || 'null')); }+ }+ class Tail extends w.HTMLElement {+ constructor() { super(); log.push('tail'); }+ }+ w.customElements.define('x-face', Face);+ w.customElements.define('x-tail', Tail);+ d.write('<x-face form=owner></x-face><form id=owner></form><x-tail></x-tail>');+ const result = {log:log.slice(), owner:internals.form?.id};+ d.close(); frame.remove();+ return JSON.stringify(result);+ })()+ "#,+ )+ .unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["ctor", "connected:null", "form:owner", "tail"],+ "owner": "owner"+ })+ );+}++#[test]+fn child_parser_connected_callback_can_write_at_current_insertion_point() {+ let mut vm = new_storage_test_vm("https://child-parser-connected-write.test/");+ let result = vm+ .eval(+ r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = [];+ class A extends w.HTMLElement {+ connectedCallback() {+ log.push('connected:' + this.childNodes.length);+ d.write('<i id=nested>nested</i>');+ log.push('after-nested-write:' + !!d.getElementById('nested'));+ }+ }+ w.customElements.define('x-a', A);+ d.write('<x-a><b id=original>original</b></x-a>');+ const a = d.querySelector('x-a'), nested = d.getElementById('nested');+ const result = {log, nestedParent:nested?.parentElement.localName,+ children:Array.from(a.children, node => node.id)};+ d.close(); frame.remove();+ return JSON.stringify(result);+ })()+ "#,+ )+ .unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["connected:0", "after-nested-write:true"],+ "nestedParent": "body", "children": ["original"]+ })+ );+}++#[test]+fn child_parser_connected_write_preserves_script_and_parent_input_order() {+ let mut vm = new_storage_test_vm("https://child-parser-connected-script.test/");+ let result = vm.eval(r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = w.log = [];+ class A extends w.HTMLElement {+ connectedCallback() {+ log.push('connected');+ d.write('<i id=first></i><script>log.push("script");document.write("<u id=inner></u>")</script><i id=last></i>');+ log.push('returned:' + !!d.getElementById('last'));+ }+ }+ w.customElements.define('x-a', A);+ d.write('<x-a><b id=original></b></x-a>');+ const result = {log, body:Array.from(d.body.children, n => n.localName + ':' + n.id),+ children:Array.from(d.querySelector('x-a').children, n => n.id)};+ d.close(); frame.remove();+ return JSON.stringify(result);+ })()+ "#).unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["connected", "script", "returned:true"],+ "body": ["x-a:", "i:first", "script:", "u:inner", "i:last"],+ "children": ["original"]+ })+ );+}++#[tokio::test]+async fn child_parser_connected_write_resumes_after_external_script_load() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let (release, released) = tokio::sync::oneshot::channel();+ let server = tokio::spawn(async move {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut buffer = [0; 1024];+ while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {+ let read = stream.read(&mut buffer).await.unwrap();+ assert_ne!(read, 0, "external script request must complete");+ request.extend_from_slice(&buffer[..read]);+ }+ assert!(request.starts_with(b"GET /blocked.js "));+ released.await.unwrap();+ let body = "externalRuns++; trace.push('external');";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ stream.write_all(response.as_bytes()).await.unwrap();+ });+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let mut vm = new_page_task_executor_test_vm_with_loader(&format!("http://{address}/"), &loader);+ vm.eval(+ r#"+ globalThis.childParserLoaded = false;+ globalThis.childParserFrame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(childParserFrame);+ const w = childParserFrame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ w.externalRuns = 0; w.tailConstructions = 0; w.outerScriptRuns = 0; w.trace = [];+ class A extends w.HTMLElement {+ connectedCallback() {+ d.write('<script src="/blocked.js"></script><i id=inner></i>');+ d.write('<p id=queued>queued while loading</p>');+ }+ }+ class B extends w.HTMLElement { constructor() { super(); w.tailConstructions++; } }+ w.customElements.define('x-a', A);+ w.customElements.define('x-b', B);+ childParserFrame.onload = () => { childParserLoaded = true; };+ d.write('<x-a></x-a><script>outerScriptRuns++;trace.push("outer")</script><x-b></x-b>');+ d.close();+ 'queued';+ "#,+ )+ .unwrap();+ assert_eq!(vm.eval(r#"JSON.stringify({scripts:w.outerScriptRuns, inner:!!d.getElementById('inner'), queued:!!d.getElementById('queued')})"#).unwrap(),+ r#"{"scripts":1,"inner":false,"queued":false}"#,+ "every active parser feed must stop behind the unreleased external script");+ release.send(()).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(childParserLoaded)",+ "true",+ "nested parser external script",+ )+ .await;+ assert_eq!(+ vm.eval(+ r#"JSON.stringify({runs:w.externalRuns, outerScripts:w.outerScriptRuns, constructors:w.tailConstructions,+ innerParent:d.getElementById('inner').parentElement.localName,+ outer:!!d.querySelector('x-b'), queued:d.getElementById('queued').textContent, trace:w.trace})"#+ )+ .unwrap(),+ r#"{"runs":1,"outerScripts":1,"constructors":1,"innerParent":"body","outer":true,"queued":"queued while loading","trace":["outer","external"]}"#+ );+ server.await.unwrap();+}++#[test]+fn child_parser_inline_close_waits_for_script_to_return() {+ let mut vm = new_storage_test_vm("https://child-parser-inline-close.test/");+ let result = vm.eval(r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ w.log = [];+ class Tail extends w.HTMLElement {+ constructor() { super(); w.log.push('tail'); }+ }+ w.customElements.define('x-tail', Tail);+ d.write('<script>document.close();log.push(document.readyState+":"+!!document.querySelector("x-tail"))</script><x-tail></x-tail>');+ return JSON.stringify({log:w.log, state:d.readyState, tail:!!d.querySelector('x-tail')});+ })()+ "#).unwrap();+ assert_eq!(+ result,+ r#"{"log":["loading:false","tail"],"state":"complete","tail":true}"#+ );+}++#[tokio::test]+async fn child_parser_nested_close_dispatches_readiness_once() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let mut vm = new_page_task_executor_test_vm_with_loader(+ "https://child-parser-close-readiness.test/",+ &loader,+ );+ vm.eval(+ r#"+ globalThis.childParserLoaded = false;+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open();+ globalThis.readiness = [d.readyState];+ d.addEventListener('readystatechange', () => readiness.push(d.readyState));+ class Close extends w.HTMLElement { connectedCallback() { d.close(); } }+ w.customElements.define('x-close', Close);+ frame.onload = () => { childParserLoaded = true; };+ d.write('<!doctype html><body><x-close></x-close><p>tail</p>');+ JSON.stringify(readiness);+ "#,+ )+ .map(|result| assert_eq!(result, r#"["loading","interactive","complete"]"#))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(childParserLoaded)",+ "true",+ "closed parser load",+ )+ .await;+ assert_eq!(+ vm.eval("JSON.stringify(readiness)").unwrap(),+ r#"["loading","interactive","complete"]"#+ );+}++#[test]+fn child_parser_connected_close_finishes_after_outer_insertion() {+ let mut vm = new_storage_test_vm("https://child-parser-connected-close.test/");+ let result = vm+ .eval(+ r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = [];+ class A extends w.HTMLElement {+ connectedCallback() { log.push('connected'); d.close(); log.push('after-close'); }+ }+ class B extends w.HTMLElement { constructor() { super(); log.push('tail'); } }+ w.customElements.define('x-a', A);+ w.customElements.define('x-b', B);+ d.write('<x-a></x-a><x-b></x-b>');+ return JSON.stringify({log, tail:!!d.querySelector('x-b'), state:d.readyState});+ })()+ "#,+ )+ .unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["connected", "after-close", "tail"], "tail": true, "state": "complete"+ })+ );+}++#[test]+fn child_parser_connected_callback_can_replace_document_before_next_constructor() {+ let mut vm = new_storage_test_vm("https://child-parser-connected-open.test/");+ let result = vm.eval(r#"+ (() => {+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ const w = frame.contentWindow, d = w.document;+ d.open(); d.write('<!doctype html><body>');+ const log = [];+ class A extends w.HTMLElement {+ connectedCallback() {+ log.push('connected');+ d.open(); d.write('<!doctype html><body><p id=replaced>replacement</p>'); d.close();+ }+ }+ class Tail extends w.HTMLElement { constructor() { super(); log.push('tail'); } }+ w.customElements.define('x-a', A);+ w.customElements.define('x-tail', Tail);+ d.write('<x-a></x-a><x-tail></x-tail>');+ const result = {log, replaced:!!d.getElementById('replaced'), tail:!!d.querySelector('x-tail')};+ d.close(); frame.remove();+ return JSON.stringify(result);+ })()+ "#).unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "log": ["connected"], "replaced": true, "tail": false+ })+ );+}+#[test]fn child_parser_write_preserves_outer_javascript_microtask_boundary() {let mut vm = new_storage_test_vm("https://child-parser-microtasks.test/");@@ -64,7 +421,10 @@ fn child_parser_write_preserves_outer_javascript_microtask_boundary() {super(); childParserLog.push('constructor');Promise.resolve().then(() => childParserLog.push('constructor-microtask'));}- connectedCallback() { childParserLog.push('connected'); }+ connectedCallback() {+ childParserLog.push('connected');+ Promise.resolve().then(() => childParserLog.push('connected-microtask'));+ }}w.customElements.define('child-written', Written);Promise.resolve().then(() => childParserLog.push('earlier-microtask'));@@ -78,7 +438,55 @@ fn child_parser_write_preserves_outer_javascript_microtask_boundary() {assert_eq!(result, r#"["constructor","connected","after-write"]"#);assert_eq!(vm.eval("JSON.stringify(childParserLog)").unwrap(),- r#"["constructor","connected","after-write","earlier-microtask","constructor-microtask"]"#+ r#"["constructor","connected","after-write","earlier-microtask","constructor-microtask","connected-microtask"]"#+ );+}++#[tokio::test]+async fn child_parser_srcdoc_invokes_insertion_reactions_before_following_tokens() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();+ let mut vm = new_page_task_executor_test_vm_with_loader(+ "https://child-parser-srcdoc-reactions.test/",+ &loader,+ );+ let html = r#"<!doctype html><body><script>+ window.log = [];+ class Face extends HTMLElement {+ static formAssociated = true;+ constructor() { super(); this.internals = this.attachInternals(); log.push('ctor:a'); }+ connectedCallback() { log.push('connected:a:' + this.childNodes.length); }+ formAssociatedCallback(form) { log.push('form:' + form.id); }+ }+ class B extends HTMLElement {+ constructor() { super(); log.push('ctor:b'); }+ connectedCallback() { log.push('connected:b:' + this.childNodes.length); }+ }+ customElements.define('x-face', Face);+ customElements.define('x-b', B);+ </script><x-face form=owner>hello <b>world</b></x-face><form id=owner></form><x-b></x-b>"#;+ vm.eval(&format!(+ r#"+ globalThis.childParserLoaded = false;+ globalThis.childParserFrame = document.createElement('iframe');+ childParserFrame.onload = () => {{ childParserLoaded = true; }};+ childParserFrame.srcdoc = {html:?};+ (document.body || document.documentElement || document).appendChild(childParserFrame);+ 'queued';+ "#+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(childParserLoaded)",+ "true",+ "child srcdoc reaction order",+ )+ .await;+ assert_eq!(+ vm.eval("JSON.stringify(childParserFrame.contentWindow.log)")+ .unwrap(),+ r#"["ctor:a","connected:a:0","form:owner","ctor:b","connected:b:0"]"#);}diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex 64d35b1ce..cf35192fb 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -611,8 +611,7 @@ fn new_streamed_parser_page_task_executor_test_vm(markup: &str,loader: &ResourceRequestClient,) -> crate::runtime::PageVmTaskExecutorTestHarness {- let mut stream =- HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test URL"));+ let stream = HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test URL"));stream.feed(markup);let page = crate::runtime::PageVmTaskExecutorTestHarness::new_with_dom_host(stream.take_parser_stream_dom_host(),@@ -14331,8 +14330,7 @@ async fn in_flight_connected_modulepreload_does_not_delay_window_load() {fn new_streamed_parser_test_vm(url: &str, markup: &str) -> StandaloneScriptVmHarness {let _js_runtime = crate::JsRuntime::initialize();- let mut stream =- HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test url"));+ let stream = HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test url"));stream.feed(markup);let dom_host = stream.take_parser_stream_dom_host();let page_task_queue = crate::page_task_queue::PageTaskQueueTestHarness::new();