Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

perf(parser): keep XML namespaces in token stream

ldm0360040422501
diff --git a/moli-parser/src/xml.rs b/moli-parser/src/xml.rs
index b2dacfeb3..fffe24513 100644
--- a/moli-parser/src/xml.rs
+++ b/moli-parser/src/xml.rs
@@ -1,7 +1,6 @@
use std::{
borrow::Cow,
cell::{Cell, RefCell},
- collections::VecDeque,
ops::{Deref, DerefMut},
rc::Rc,
};
@@ -14,15 +13,10 @@ use xml5ever::{
tendril::{StrTendril as XmlStrTendril, TendrilSink as XmlTendrilSink},
tree_builder::{NodeOrText as XmlNodeOrText, TreeSink as XmlTreeSinkBase, XmlTreeSink},
};
-use xmlparser::{
- ElementEnd as XmlElementEnd, Token as XmlTokenizerToken, Tokenizer as XmlTokenizer,
-};
use super::{html_chunks, xml_tree_viewer::transform_document_to_xml_tree_view};
use moli_dom::native::{Attribute as NativeAttribute, DomHost, NativeDom, NativeNodeId, Node};
-pub(super) const XMLNS_NAMESPACE: &str = "http://www.w3.org/2000/xmlns/";
-
#[derive(Debug, Clone, Default)]
pub struct XmlParser;
@@ -65,13 +59,6 @@ impl DerefMut for XmlDomHost<'_> {
struct XmlLiveTreeSinkTarget<'a> {
dom_host: XmlDomHost<'a>,
document_handle: NativeNodeId,
- namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
- source_has_unclosed_element_at_eof: bool,
-}
-
-pub(super) struct XmlNamespaceDeclaration {
- pub(super) ordinary_attributes_before: usize,
- pub(super) attribute: NativeAttribute,
}
impl XmlParser {
@@ -92,13 +79,7 @@ impl XmlParser {
xml: String,
present_unstyled_xml: bool,
) -> NativeDom {
- let source_has_unclosed_element_at_eof = xml_source_has_unclosed_element_at_eof(&xml);
- let namespace_declarations = xml_namespace_declarations(&xml);
- let sink = XmlDocumentSink::new(XmlLiveTreeSinkTarget::new_owned(
- final_url,
- namespace_declarations,
- source_has_unclosed_element_at_eof,
- ));
+ let sink = XmlDocumentSink::new(XmlLiveTreeSinkTarget::new_owned(final_url));
let mut parser = parse_xml_document(sink, XmlParseOpts::default());
for chunk in html_chunks(&xml) {
parser.process(XmlStrTendril::from(chunk));
@@ -122,11 +103,7 @@ impl XmlParser {
document_handle: NativeNodeId,
xml: &str,
) -> Option<()> {
- let source_has_unclosed_element_at_eof = xml_source_has_unclosed_element_at_eof(xml);
- let namespace_declarations = xml_namespace_declarations(xml);
- let target = XmlLiveTreeSinkTarget::new_borrowed(dom_host, document_handle)?
- .with_namespace_declarations(namespace_declarations)
- .with_source_has_unclosed_element_at_eof(source_has_unclosed_element_at_eof);
+ let target = XmlLiveTreeSinkTarget::new_borrowed(dom_host, document_handle)?;
let sink = XmlDocumentSink::new(target);
let mut parser = parse_xml_document(sink, XmlParseOpts::default());
for chunk in html_chunks(&xml) {
@@ -137,164 +114,6 @@ impl XmlParser {
}
}
-// xml5ever 0.39 transitions from its Main tree-building phase directly to End
-// on EOF and therefore does not report a still-open element. Keep this check
-// deliberately narrower than a second well-formedness parser: tokenizer errors
-// and mismatched tags defer to xml5ever's own parse-error reporting.
-pub(super) fn xml_source_has_unclosed_element_at_eof(source: &str) -> bool {
- let mut open_elements = Vec::<(String, String)>::new();
- let mut pending_element = None::<(String, String)>;
-
- for token in XmlTokenizer::from(source) {
- let Ok(token) = token else {
- return false;
- };
- match token {
- XmlTokenizerToken::ElementStart { prefix, local, .. } => {
- if pending_element.is_some() {
- return false;
- }
- pending_element = Some((prefix.as_str().to_owned(), local.as_str().to_owned()));
- }
- XmlTokenizerToken::ElementEnd {
- end: XmlElementEnd::Open,
- ..
- } => {
- let Some(element) = pending_element.take() else {
- return false;
- };
- open_elements.push(element);
- }
- XmlTokenizerToken::ElementEnd {
- end: XmlElementEnd::Empty,
- ..
- } => {
- if pending_element.take().is_none() {
- return false;
- }
- }
- XmlTokenizerToken::ElementEnd {
- end: XmlElementEnd::Close(prefix, local),
- ..
- } => {
- let closes_current =
- open_elements
- .pop()
- .is_some_and(|(open_prefix, open_local)| {
- open_prefix == prefix.as_str() && open_local == local.as_str()
- });
- if pending_element.is_some() || !closes_current {
- return false;
- }
- }
- _ => {}
- }
- }
-
- pending_element.is_some() || !open_elements.is_empty()
-}
-
-/// xml5ever consumes namespace declarations while resolving qualified names,
-/// so its tree sink never receives the declarations as attributes. The DOM,
-/// however, exposes `xmlns` declarations as Attr nodes in the XMLNS namespace.
-/// Capture them in element-creation order and merge them at the tree-sink
-/// boundary.
-pub(super) fn xml_namespace_declarations(xml: &str) -> VecDeque<Vec<XmlNamespaceDeclaration>> {
- let mut declarations = VecDeque::new();
- let mut current = None::<(usize, Vec<XmlNamespaceDeclaration>)>;
-
- for token in XmlTokenizer::from(xml) {
- let Ok(token) = token else {
- break;
- };
- match token {
- XmlTokenizerToken::ElementStart { .. } => current = Some((0, Vec::new())),
- XmlTokenizerToken::Attribute {
- prefix,
- local,
- value,
- ..
- } => {
- let is_default_declaration =
- prefix.as_str().is_empty() && local.as_str() == "xmlns";
- let is_prefixed_declaration = prefix.as_str() == "xmlns";
- if !is_default_declaration && !is_prefixed_declaration {
- if let Some((ordinary_attributes, _)) = current.as_mut() {
- *ordinary_attributes += 1;
- }
- continue;
- }
- let Some((ordinary_attributes_before, declarations)) = current.as_mut() else {
- continue;
- };
- declarations.push(XmlNamespaceDeclaration {
- ordinary_attributes_before: *ordinary_attributes_before,
- attribute: NativeAttribute::new(
- local.as_str().to_owned(),
- XMLNS_NAMESPACE.to_owned(),
- is_prefixed_declaration.then(|| "xmlns".to_owned()),
- decode_xml_attribute_value(value.as_str()),
- ),
- });
- }
- XmlTokenizerToken::ElementEnd {
- end: XmlElementEnd::Open | XmlElementEnd::Empty,
- ..
- } => {
- if let Some((_, current_declarations)) = current.take() {
- declarations.push_back(current_declarations);
- }
- }
- _ => {}
- }
- }
-
- declarations
-}
-
-fn decode_xml_attribute_value(value: &str) -> String {
- let mut decoded = String::with_capacity(value.len());
- let mut remaining = value;
-
- while let Some(entity_start) = remaining.find('&') {
- decoded.push_str(&remaining[..entity_start]);
- let entity = &remaining[(entity_start + 1)..];
- let Some(entity_end) = entity.find(';') else {
- decoded.push_str(&remaining[entity_start..]);
- return decoded;
- };
- let name = &entity[..entity_end];
- let replacement = match name {
- "amp" => Some('&'),
- "apos" => Some('\''),
- "gt" => Some('>'),
- "lt" => Some('<'),
- "quot" => Some('"'),
- _ => name
- .strip_prefix("#x")
- .or_else(|| name.strip_prefix("#X"))
- .and_then(|digits| u32::from_str_radix(digits, 16).ok())
- .and_then(char::from_u32)
- .or_else(|| {
- name.strip_prefix('#')
- .and_then(|digits| digits.parse::<u32>().ok())
- .and_then(char::from_u32)
- }),
- };
- if let Some(replacement) = replacement {
- decoded.push(replacement);
- } else {
- decoded.push('&');
- decoded.push_str(name);
- decoded.push(';');
- }
- remaining = &entity[(entity_end + 1)..];
- }
-
- decoded.push_str(remaining);
- decoded
-}
-
impl XmlParseHandle {
pub(super) fn new(node_id: NativeNodeId, element_name: Option<Rc<XmlQualName>>) -> Self {
Self {
@@ -322,23 +141,16 @@ impl<'a> XmlDocumentSink<'a> {
}
impl XmlLiveTreeSinkTarget<'static> {
- fn new_owned(
- final_url: Url,
- namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
- source_has_unclosed_element_at_eof: bool,
- ) -> Self {
+ fn new_owned(final_url: Url) -> Self {
let dom_host = DomHost::from_dom(NativeDom::new_xml(final_url));
let document_handle = dom_host.document_handle();
Self {
dom_host: XmlDomHost::Owned(Box::new(dom_host)),
document_handle,
- namespace_declarations,
- source_has_unclosed_element_at_eof,
}
}
- fn finish_document(mut self) -> NativeDom {
- self.record_unclosed_source_element_error();
+ fn finish_document(self) -> NativeDom {
let XmlDomHost::Owned(dom_host) = self.dom_host else {
unreachable!("owned XML parsing must finish with an owned DOM host")
};
@@ -359,38 +171,10 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
Some(Self {
dom_host: XmlDomHost::Borrowed(dom_host),
document_handle,
- namespace_declarations: VecDeque::new(),
- source_has_unclosed_element_at_eof: false,
})
}
- fn with_namespace_declarations(
- mut self,
- namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
- ) -> Self {
- self.namespace_declarations = namespace_declarations;
- self
- }
-
- fn with_source_has_unclosed_element_at_eof(
- mut self,
- source_has_unclosed_element_at_eof: bool,
- ) -> Self {
- self.source_has_unclosed_element_at_eof = source_has_unclosed_element_at_eof;
- self
- }
-
- fn finish_live_tree(mut self) {
- self.record_unclosed_source_element_error();
- }
-
- fn record_unclosed_source_element_error(&mut self) {
- if self.source_has_unclosed_element_at_eof && self.dom_host.dom().parse_errors().is_empty()
- {
- self.dom_host
- .push_parse_error("Unexpected EOF with an unclosed XML element".to_owned());
- }
- }
+ fn finish_live_tree(self) {}
fn document_handle(&self) -> XmlParseHandle {
XmlParseHandle::new(self.document_handle, None)
@@ -398,7 +182,7 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
fn create_element(&mut self, name: XmlQualName, attrs: Vec<XmlAttribute>) -> XmlParseHandle {
let element_name = Rc::new(name.clone());
- let mut attributes = attrs
+ let attributes = attrs
.into_iter()
.map(|attribute| {
NativeAttribute::new(
@@ -413,19 +197,6 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
)
})
.collect::<Vec<_>>();
- for (declaration_index, declaration) in self
- .namespace_declarations
- .pop_front()
- .unwrap_or_default()
- .into_iter()
- .enumerate()
- {
- let insertion_index = declaration
- .ordinary_attributes_before
- .saturating_add(declaration_index)
- .min(attributes.len());
- attributes.insert(insertion_index, declaration.attribute);
- }
let node_id = self
.dom_host
.create_parser_element_without_attributes_for_document(
@@ -813,23 +584,10 @@ impl XmlTreeSink for XmlDocumentSink<'_> {
#[cfg(test)]
mod tests {
- use super::{XmlParser, xml_source_has_unclosed_element_at_eof};
+ use super::XmlParser;
use moli_dom::native::{DomHost, NativeDom, NativeNodeId, Node, NodeType};
use url::Url;
- #[test]
- fn xml_eof_guard_only_reports_proven_unclosed_elements() {
- assert!(xml_source_has_unclosed_element_at_eof("<root>"));
- assert!(xml_source_has_unclosed_element_at_eof("<root><child/>"));
- assert!(!xml_source_has_unclosed_element_at_eof("<root/>"));
- assert!(!xml_source_has_unclosed_element_at_eof(
- "<root></mismatched>"
- ));
- assert!(!xml_source_has_unclosed_element_at_eof(
- "<root attr='unterminated></root>"
- ));
- }
-
#[test]
fn xml_parser_preserves_namespace_declarations_as_dom_attributes() {
let dom = XmlParser.parse(
@@ -862,11 +620,17 @@ mod tests {
"data-after"
]
);
- assert_eq!(root_attributes[1].namespace(), super::XMLNS_NAMESPACE);
+ assert_eq!(
+ root_attributes[1].namespace(),
+ "http://www.w3.org/2000/xmlns/"
+ );
assert_eq!(root_attributes[1].prefix(), None);
assert_eq!(root_attributes[1].local_name(), "xmlns");
assert_eq!(root_attributes[1].value(), "urn:catalog&items");
- assert_eq!(root_attributes[3].namespace(), super::XMLNS_NAMESPACE);
+ assert_eq!(
+ root_attributes[3].namespace(),
+ "http://www.w3.org/2000/xmlns/"
+ );
assert_eq!(root_attributes[3].prefix(), Some("xmlns"));
assert_eq!(root_attributes[3].local_name(), "m");
assert_eq!(root_attributes[3].value(), "urn:meta");
diff --git a/moli-parser/src/xml_stream.rs b/moli-parser/src/xml_stream.rs
index 6769a0d79..937bdb9c9 100644
--- a/moli-parser/src/xml_stream.rs
+++ b/moli-parser/src/xml_stream.rs
@@ -14,8 +14,7 @@ use html5ever::{
use moli_dom::native::{DomHost, NativeDom, NativeNodeId};
use url::Url;
use xml5ever::{
- Attribute as XmlAttribute, ExpandedName, LocalName as XmlLocalName, Namespace as XmlNamespace,
- Prefix as XmlPrefix, QualName as XmlQualName, TokenizerResult,
+ Attribute as XmlAttribute, ExpandedName, QualName as XmlQualName, TokenizerResult,
buffer_queue::BufferQueue,
driver::XmlParseOpts,
interface::{ElementFlags as XmlElementFlags, QuirksMode as XmlQuirksMode},
@@ -32,9 +31,6 @@ use crate::{
html::ParseHandle,
live_target::{ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget},
stream::prepare_parser_script_handoff_for_static_document,
- xml::{
- XmlNamespaceDeclaration, xml_namespace_declarations, xml_source_has_unclosed_element_at_eof,
- },
xml_tree_viewer::transform_parser_target_to_xml_tree_view,
};
@@ -47,8 +43,6 @@ use crate::{
pub struct XmlDocumentStream {
parser: XmlParserSession,
input: XmlParserInputStream,
- raw_source: String,
- scanned_namespace_element_count: usize,
eof_declared: bool,
}
@@ -73,8 +67,6 @@ struct XmlStreamDocumentSink {
struct XmlParserStreamTarget {
common: ParserStreamHtmlTreeSinkTarget,
- namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
- source_has_unclosed_element_at_eof: bool,
present_unstyled_top_level_document: bool,
}
@@ -117,15 +109,11 @@ impl XmlDocumentStream {
) -> Self {
let target = XmlParserStreamTarget {
common,
- namespace_declarations: VecDeque::new(),
- source_has_unclosed_element_at_eof: false,
present_unstyled_top_level_document,
};
Self {
parser: XmlParserSession::new(target, XmlParseOpts::default()),
input: XmlParserInputStream::default(),
- raw_source: String::new(),
- scanned_namespace_element_count: 0,
eof_declared: false,
}
}
@@ -137,8 +125,6 @@ impl XmlDocumentStream {
if chunk.is_empty() {
return;
}
- self.raw_source.push_str(&chunk);
- self.refresh_namespace_declarations();
self.input.end_segments.push_back(chunk);
}
@@ -148,12 +134,6 @@ impl XmlDocumentStream {
return;
}
self.eof_declared = true;
- self.refresh_namespace_declarations();
- self.parser
- .sink()
- .borrow_mut()
- .source_has_unclosed_element_at_eof =
- xml_source_has_unclosed_element_at_eof(&self.raw_source);
}
pub fn has_pending_input(&self) -> bool {
@@ -325,25 +305,6 @@ impl XmlDocumentStream {
self.parser.finish_owned().finish_dom_host().into_dom()
}
- fn refresh_namespace_declarations(&mut self) {
- let declarations = xml_namespace_declarations(&self.raw_source);
- if declarations.len() <= self.scanned_namespace_element_count {
- return;
- }
- let newly_complete = declarations
- .into_iter()
- .skip(self.scanned_namespace_element_count)
- .collect::<VecDeque<_>>();
- self.scanned_namespace_element_count = self
- .scanned_namespace_element_count
- .saturating_add(newly_complete.len());
- self.parser
- .sink()
- .borrow_mut()
- .namespace_declarations
- .extend(newly_complete);
- }
-
fn take_next_owned_input(&mut self, max_bytes: usize) -> String {
if self.parser.has_buffered_input() {
return String::new();
@@ -502,7 +463,6 @@ impl XmlParserSession {
debug_assert!(input_buffer.is_empty());
tokenizer.end();
let mut target = tokenizer.sink.inner.sink.finish();
- target.record_unclosed_source_element_error();
target.present_unstyled_top_level_document_if_needed();
target.common
}
@@ -515,7 +475,6 @@ impl XmlParserSession {
debug_assert!(input_buffer.is_empty());
tokenizer.end();
let mut target = tokenizer.sink.inner.sink.target.borrow_mut();
- target.record_unclosed_source_element_error();
target.present_unstyled_top_level_document_if_needed();
ParserFinishDiscoverySignals {
parser_created_null_registry_elements: target
@@ -563,38 +522,6 @@ impl TokenSink for EmbedderPausingXmlTreeBuilder {
}
impl XmlParserStreamTarget {
- fn merge_namespace_declarations(&mut self, attributes: &mut Vec<XmlAttribute>) {
- for (declaration_index, declaration) in self
- .namespace_declarations
- .pop_front()
- .unwrap_or_default()
- .into_iter()
- .enumerate()
- {
- let attribute = &declaration.attribute;
- let xml_attribute = XmlAttribute {
- name: XmlQualName::new(
- attribute.prefix().map(XmlPrefix::from),
- XmlNamespace::from(attribute.namespace()),
- XmlLocalName::from(attribute.local_name()),
- ),
- value: StrTendril::from(attribute.value()),
- };
- let insertion_index = declaration
- .ordinary_attributes_before
- .saturating_add(declaration_index)
- .min(attributes.len());
- attributes.insert(insertion_index, xml_attribute);
- }
- }
-
- fn record_unclosed_source_element_error(&mut self) {
- if self.source_has_unclosed_element_at_eof {
- self.common
- .push_parse_error("Unexpected EOF with an unclosed XML element".to_owned());
- }
- }
-
fn present_unstyled_top_level_document_if_needed(&mut self) {
if self.present_unstyled_top_level_document {
transform_parser_target_to_xml_tree_view(&mut self.common);
@@ -670,11 +597,10 @@ impl TreeSink for XmlStreamDocumentSink {
fn create_element(
&self,
name: XmlQualName,
- mut attrs: Vec<XmlAttribute>,
+ attrs: Vec<XmlAttribute>,
flags: XmlElementFlags,
) -> Self::Handle {
let mut target = self.target.borrow_mut();
- target.merge_namespace_declarations(&mut attrs);
let element_name = Rc::new(name.clone());
let html_name = xml_name_to_html(&name);
let html_attrs = attrs.into_iter().map(xml_attribute_to_html).collect();
@@ -1041,6 +967,42 @@ mod tests {
);
}
+ #[test]
+ fn incremental_xml_preserves_namespaces_across_many_single_byte_chunks() {
+ let mut source = String::from("<root>");
+ for index in 0..512 {
+ source.push_str(&format!(
+ "<p:item xmlns:p='urn:item:{index}' data-index='{index}'/>"
+ ));
+ }
+ source.push_str("</root>");
+
+ let mut stream = XmlDocumentStream::new(test_url());
+ for byte in source.bytes() {
+ stream.append_to_end(char::from(byte).to_string());
+ }
+ let document = stream.finish();
+ let items = document
+ .nodes()
+ .filter_map(Node::as_element)
+ .filter(|element| element.local_name() == "item")
+ .collect::<Vec<_>>();
+ assert_eq!(items.len(), 512);
+ for (index, item) in items.into_iter().enumerate() {
+ assert_eq!(item.namespace(), format!("urn:item:{index}"));
+ let attributes = item.attributes();
+ assert_eq!(
+ attributes
+ .iter()
+ .map(|attribute| attribute.name())
+ .collect::<Vec<_>>(),
+ ["xmlns:p", "data-index"]
+ );
+ assert_eq!(attributes[0].namespace(), "http://www.w3.org/2000/xmlns/");
+ assert_eq!(attributes[0].value(), format!("urn:item:{index}"));
+ }
+ }
+
#[test]
fn incremental_xml_keeps_cdata_syntax_in_comment_and_pi() {
let mut stream = XmlDocumentStream::new(test_url());
diff --git a/vendor/xml5ever-0.39.0/MOLI_VENDORING.md b/vendor/xml5ever-0.39.0/MOLI_VENDORING.md
index f24addd40..a68a2c197 100644
--- a/vendor/xml5ever-0.39.0/MOLI_VENDORING.md
+++ b/vendor/xml5ever-0.39.0/MOLI_VENDORING.md
@@ -2,7 +2,8 @@
This directory contains the source of the crates.io `xml5ever` 0.39.0 release.
It is patched locally because Moli needs the tokenizer to preserve CDATA as a
-distinct token and the XML tree builder to surface CDATA nodes to its sink.
+distinct token, the XML tree builder to surface CDATA nodes to its sink, and
+namespace declarations to remain available as DOM attributes after binding.
The upstream source is licensed under MIT or Apache-2.0; see `LICENSE-MIT` and
`LICENSE-APACHE` in this directory.
diff --git a/vendor/xml5ever-0.39.0/src/tokenizer/mod.rs b/vendor/xml5ever-0.39.0/src/tokenizer/mod.rs
index 515e7654b..09d091974 100644
--- a/vendor/xml5ever-0.39.0/src/tokenizer/mod.rs
+++ b/vendor/xml5ever-0.39.0/src/tokenizer/mod.rs
@@ -21,7 +21,7 @@ use crate::macros::time;
use crate::tendril::StrTendril;
use crate::{buffer_queue, Attribute, QualName, SmallCharSet};
use log::debug;
-use markup5ever::{local_name, namespace_prefix, ns, small_char_set, TokenizerResult};
+use markup5ever::{ns, small_char_set, TokenizerResult};
use std::borrow::Cow::{self, Borrowed};
use std::cell::{Cell, RefCell, RefMut};
use std::collections::BTreeMap;
@@ -1307,13 +1307,10 @@ impl<Sink: TokenSink> XmlTokenizer<Sink> {
value: replace(&mut self.current_attr_value.borrow_mut(), StrTendril::new()),
};
- if qname.local == local_name!("xmlns")
- || qname.prefix == Some(namespace_prefix!("xmlns"))
- {
- self.current_tag_attrs.borrow_mut().insert(0, attr);
- } else {
- self.current_tag_attrs.borrow_mut().push(attr);
- }
+ // Keep source order. The tree builder performs a declaration-only
+ // pass before binding any qualified names, so declarations do not
+ // need to be moved ahead of ordinary attributes here.
+ self.current_tag_attrs.borrow_mut().push(attr);
}
}
diff --git a/vendor/xml5ever-0.39.0/src/tree_builder/mod.rs b/vendor/xml5ever-0.39.0/src/tree_builder/mod.rs
index 381ba8e0c..1b1d6af60 100644
--- a/vendor/xml5ever-0.39.0/src/tree_builder/mod.rs
+++ b/vendor/xml5ever-0.39.0/src/tree_builder/mod.rs
@@ -257,9 +257,10 @@ where
fn declare_ns(&self, attr: &mut Attribute) {
if let Err(msg) = self.current_namespace.borrow_mut().insert_ns(attr) {
self.sink.parse_error(msg);
- } else {
- attr.name.ns = ns!(xmlns);
}
+ // Namespace declarations are real DOM attributes. Keep their XMLNS
+ // namespace identity even when the declaration itself is invalid.
+ attr.name.ns = ns!(xmlns);
}
fn find_uri(&self, prefix: &Option<Prefix>) -> Result<Option<Namespace>, Cow<'static, str>> {
@@ -342,12 +343,17 @@ where
self.declare_ns(attr);
}
- // Then we bind those namespace declarations to attributes
- for attr in tag.attrs.iter_mut().filter(|attr| {
- attr.name.prefix != Some(namespace_prefix!("xmlns"))
- && attr.name.local != local_name!("xmlns")
- }) {
- if self.bind_attr_qname(&mut present_attrs, &mut attr.name) {
+ // Bind ordinary attributes and retain namespace declarations in their
+ // original order. Tree sinks need the declarations as Attr nodes even
+ // though the namespace resolver has already consumed their values.
+ for attr in tag.attrs.iter_mut() {
+ let is_namespace_declaration = attr.name.ns == ns!(xmlns);
+ let keep = if is_namespace_declaration {
+ Self::check_duplicate_attr(&mut present_attrs, &attr.name)
+ } else {
+ self.bind_attr_qname(&mut present_attrs, &mut attr.name)
+ };
+ if keep {
new_attr.push(attr.clone());
}
}
@@ -432,7 +438,12 @@ where
}
fn end(&self) {
- for node in self.open_elems.borrow_mut().drain(..).rev() {
+ let mut open_elems = self.open_elems.borrow_mut();
+ if !open_elems.is_empty() {
+ self.sink
+ .parse_error(Borrowed("Unexpected EOF with an unclosed XML element"));
+ }
+ for node in open_elems.drain(..).rev() {
self.sink.pop(&node);
}
}