Truly independent web browser
LibXML: Add an XML parser written in Rust
Andreas Kling2e926121f05e
diff --git a/Cargo.lock b/Cargo.lockindex a8cd6bb8a06..321c25c439c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2150,6 +2150,16 @@ dependencies = ["rustc-demangle",]+[[package]]+name = "libxml_rust"+version = "0.1.0"+dependencies = [+ "ak",+ "cbindgen",+ "ladybird_allocator",+ "rustc-demangle",+]+[[package]]name = "linux-raw-sys"version = "0.12.1"diff --git a/Cargo.toml b/Cargo.tomlindex 0f1d4e729a1..15bcd81e691 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -26,6 +26,7 @@ members = ["Libraries/LibWeb/Rust","Libraries/LibWeb/HTML/Parser/Rust","Libraries/LibWebRTC/Rust",+ "Libraries/LibXML/Rust","Libraries/RustAllocator","Services/Compositor/Rust","Services/WebRTCClient",diff --git a/Libraries/LibXML/Rust/Cargo.toml b/Libraries/LibXML/Rust/Cargo.tomlnew file mode 100644index 00000000000..60b2f330fc3--- /dev/null+++ b/Libraries/LibXML/Rust/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "libxml_rust"+version = "0.1.0"+edition = "2024"++[lib]+crate-type = ["staticlib", "rlib"]++# After changing dependencies, regenerate the Flatpak sources:+# python3 Meta/CMake/flatpak/generate-cargo-sources.py+[dependencies]+ak = { path = "../../../AK/Rust" }+ladybird_allocator = { path = "../../RustAllocator", optional = true }+rustc-demangle = "0.1"++[features]+default = []+allocator = ["dep:ladybird_allocator"]++[build-dependencies]+cbindgen = "0.29"++[lints]+workspace = truediff --git a/Libraries/LibXML/Rust/build.rs b/Libraries/LibXML/Rust/build.rsnew file mode 100644index 00000000000..5c6f8f8c952--- /dev/null+++ b/Libraries/LibXML/Rust/build.rs@@ -0,0 +1,31 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::env;+use std::error::Error;+use std::path::PathBuf;++fn main() -> Result<(), Box<dyn Error>> {+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);+ let out_dir = PathBuf::from(env::var("OUT_DIR")?);++ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=cbindgen.toml");+ println!("cargo:rerun-if-changed=src");++ cbindgen::generate(manifest_dir).map_or_else(+ |error| match error {+ cbindgen::Error::ParseSyntaxError { .. } => {}+ e => panic!("{e:?}"),+ },+ |bindings| {+ let header_path = out_dir.join("RustFFI.h");+ bindings.write_to_file(&header_path);+ },+ );++ Ok(())+}diff --git a/Libraries/LibXML/Rust/cbindgen.toml b/Libraries/LibXML/Rust/cbindgen.tomlnew file mode 100644index 00000000000..d3438e9c61e--- /dev/null+++ b/Libraries/LibXML/Rust/cbindgen.toml@@ -0,0 +1,29 @@+language = "C++"+header = """/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */"""+pragma_once = true+include_version = true+namespaces = ["XML", "FFI"]+line_length = 120+tab_width = 4+no_includes = true+sys_includes = ["stdint.h", "stddef.h"]+usize_is_size_t = true++[parse]+parse_deps = false++[parse.expand]+all_features = false++[export]+# The crate's constants are its own business: the interface is what ffi.rs declares.+item_types = ["enums", "structs", "typedefs", "opaque", "functions"]+# No function takes or returns these, so they have to be asked for.+include = ["XmlRowKind", "XmlRowKindBits", "XmlAttributeFlag", "XmlValueFlag"]++[export.mangle]+rename_types = "PascalCase"diff --git a/Libraries/LibXML/Rust/examples/xmlalloc.rs b/Libraries/LibXML/Rust/examples/xmlalloc.rsnew file mode 100644index 00000000000..732feab99aa--- /dev/null+++ b/Libraries/LibXML/Rust/examples/xmlalloc.rs@@ -0,0 +1,82 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Counts the heap allocations parsing each document named on the command line takes: how many calls, the most+//! bytes allocated at once, and how many bytes the finished document holds on to. The row count is there to judge+//! how well the parser guesses the size of its result from the size of the source.++use std::alloc::GlobalAlloc;+use std::alloc::Layout;+use std::alloc::System;+use std::sync::atomic::AtomicUsize;+use std::sync::atomic::Ordering::Relaxed;++struct Counting;++static CALLS: AtomicUsize = AtomicUsize::new(0);+static REALLOCS: AtomicUsize = AtomicUsize::new(0);+static LIVE: AtomicUsize = AtomicUsize::new(0);+static PEAK: AtomicUsize = AtomicUsize::new(0);++fn grow(size: usize) {+ let live = LIVE.fetch_add(size, Relaxed) + size;+ PEAK.fetch_max(live, Relaxed);+}++// SAFETY: Every request is passed on to the system allocator unchanged.+unsafe impl GlobalAlloc for Counting {+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {+ CALLS.fetch_add(1, Relaxed);+ grow(layout.size());+ // SAFETY: The caller upholds the contract of alloc.+ unsafe { System.alloc(layout) }+ }++ unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {+ LIVE.fetch_sub(layout.size(), Relaxed);+ // SAFETY: The caller upholds the contract of dealloc.+ unsafe { System.dealloc(pointer, layout) }+ }++ unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {+ REALLOCS.fetch_add(1, Relaxed);+ LIVE.fetch_sub(layout.size(), Relaxed);+ grow(new_size);+ // SAFETY: The caller upholds the contract of realloc.+ unsafe { System.realloc(pointer, layout, new_size) }+ }+}++#[global_allocator]+static ALLOCATOR: Counting = Counting;++fn main() {+ let options = libxml_rust::Options {+ preserve_comments: true,+ preserve_cdata: true,+ resolve_html_entity: None,+ };+ println!(+ "{:>10} {:>9} {:>7} {:>8} {:>10} {:>10} path",+ "bytes", "rows", "allocs", "reallocs", "peak", "retained"+ );+ for path in std::env::args().skip(1) {+ let source = std::fs::read(&path).unwrap();+ let (calls, reallocs, live) = (CALLS.load(Relaxed), REALLOCS.load(Relaxed), LIVE.load(Relaxed));+ PEAK.store(live, Relaxed);+ let document = libxml_rust::parse(&source, options);+ let peak = PEAK.load(Relaxed) - live;+ let retained = LIVE.load(Relaxed) - live;+ let allocs = CALLS.load(Relaxed) - calls;+ let reallocs = REALLOCS.load(Relaxed) - reallocs;+ let rows = document.tape.len();+ drop(document);+ println!(+ "{:>10} {rows:>9} {allocs:>7} {reallocs:>8} {peak:>10} {retained:>10} {path}",+ source.len()+ );+ }+}diff --git a/Libraries/LibXML/Rust/examples/xmlcheck.rs b/Libraries/LibXML/Rust/examples/xmlcheck.rsnew file mode 100644index 00000000000..185c396229b--- /dev/null+++ b/Libraries/LibXML/Rust/examples/xmlcheck.rs@@ -0,0 +1,45 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Parses each document whose path is a line of standard input and prints the path with "ok", or with the first+//! error and whether it is fatal. Every result is also put through the verifier.++use std::io::BufRead;+use std::io::Write;++fn main() {+ let options = libxml_rust::Options {+ preserve_comments: true,+ preserve_cdata: true,+ resolve_html_entity: None,+ };+ let stdout = std::io::stdout();+ let mut out = std::io::BufWriter::new(stdout.lock());+ for path in std::io::stdin().lock().lines() {+ let path = path.unwrap();+ let Ok(source) = std::fs::read(&path) else {+ writeln!(out, "{path}\tunreadable").unwrap();+ continue;+ };+ let document = libxml_rust::parse(&source, options);+ if let Err(problem) = libxml_rust::verify::verify(&document, &source) {+ writeln!(out, "{path}\tinvalid\t{problem}").unwrap();+ continue;+ }+ match document.errors.first() {+ None => writeln!(out, "{path}\tok").unwrap(),+ Some(error) => {+ let severity = if error.fatal { "fatal" } else { "error" };+ writeln!(+ out,+ "{path}\t{severity}\t{}:{}: {}",+ error.line, error.column, error.message+ )+ .unwrap();+ }+ }+ }+}diff --git a/Libraries/LibXML/Rust/examples/xmldump.rs b/Libraries/LibXML/Rust/examples/xmldump.rsnew file mode 100644index 00000000000..ca84b5f994f--- /dev/null+++ b/Libraries/LibXML/Rust/examples/xmldump.rs@@ -0,0 +1,20 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Prints the events of the documents named on the command line.++fn main() {+ let options = libxml_rust::Options {+ preserve_comments: true,+ preserve_cdata: true,+ resolve_html_entity: None,+ };+ for path in std::env::args().skip(1) {+ let source = std::fs::read(&path).unwrap();+ let document = libxml_rust::parse(&source, options);+ print!("{}", libxml_rust::dump::dump(&document, &source, true));+ }+}diff --git a/Libraries/LibXML/Rust/examples/xmlfuzz.rs b/Libraries/LibXML/Rust/examples/xmlfuzz.rsnew file mode 100644index 00000000000..4f5d9a3f7f9--- /dev/null+++ b/Libraries/LibXML/Rust/examples/xmlfuzz.rs@@ -0,0 +1,228 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Parses the files named on the command line (directories are walked) and then mutations of them, and checks+//! every resulting document with `verify`. A document that fails the check, or a panic, is a bug in the parser.+//!+//! usage: xmlfuzz [--mutations N] [--max-size BYTES] PATH...++use std::path::Path;++use libxml_rust::Options;+use libxml_rust::verify::verify;++struct Random(u64);++impl Random {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }++ fn below(&mut self, bound: usize) -> usize {+ if bound == 0 {+ 0+ } else {+ (self.next() % bound as u64) as usize+ }+ }+}++const FRAGMENTS: &[&[u8]] = &[+ b"<",+ b">",+ b"/>",+ b"</",+ b"&",+ b";",+ b"\"",+ b"'",+ b"=",+ b"]]>",+ b"<!--",+ b"-->",+ b"--",+ b"<![CDATA[",+ b"<?",+ b"?>",+ b"&#x",+ b"&#",+ b"&",+ b"<",+ b"&e;",+ b"%e;",+ b"xmlns",+ b"xmlns:",+ b"xml:",+ b":",+ b"<!DOCTYPE a [",+ b"]>",+ b"<!ENTITY e \"",+ b"<!ENTITY % e \"",+ b"<!ATTLIST a b CDATA \"",+ b"<!ELEMENT a ANY>",+ b"<?xml version=\"1.0\"?>",+ b"\r",+ b"\r\n",+ b"\t",+ b"\0",+ b"\x0C",+ b"\x80",+ b"\xC3",+ b"\xC3\xA5",+ b"\xE4\xB8\xAD",+ b"\xED\xA0\x80",+ b"\xEF\xBF\xBE",+ b"\xEF\xBF\xBF",+ b"\xF0\x9F\x98\x80",+ b"\xF4\x90\x80\x80",+ b"\xFF",+ b"\xEF\xBB\xBF",+ b" ",+ b"a",+ b"<a>",+ b"</a>",+];++fn mutate(random: &mut Random, source: &[u8]) -> Vec<u8> {+ let mut bytes = source.to_vec();+ for _ in 0..1 + random.below(4) {+ let at = random.below(bytes.len() + 1);+ match random.below(7) {+ 0 if !bytes.is_empty() => {+ let at = at.min(bytes.len() - 1);+ bytes[at] ^= 1 << random.below(8);+ }+ 1 if !bytes.is_empty() => {+ let at = at.min(bytes.len() - 1);+ bytes[at] = random.next() as u8;+ }+ 2 => {+ let fragment = FRAGMENTS[random.below(FRAGMENTS.len())];+ bytes.splice(at..at, fragment.iter().copied());+ }+ 3 => {+ let end = (at + random.below(64)).min(bytes.len());+ bytes.drain(at..end);+ }+ 4 => {+ let end = (at + random.below(256)).min(bytes.len());+ let copy = bytes[at..end].to_vec();+ let to = random.below(bytes.len() + 1);+ bytes.splice(to..to, copy);+ }+ 5 => bytes.truncate(at),+ _ => {+ // Swap two delimiters, which keeps a document nearly well-formed.+ if let Some(found) = bytes[at..]+ .iter()+ .position(|&byte| matches!(byte, b'<' | b'>' | b'"' | b'&'))+ {+ bytes[at + found] = b"<>\"&'/"[random.below(6)];+ }+ }+ }+ }+ bytes+}++fn collect(path: &Path, out: &mut Vec<std::path::PathBuf>) {+ if path.is_dir() {+ let mut entries: Vec<_> = std::fs::read_dir(path)+ .unwrap_or_else(|error| panic!("{}: {error}", path.display()))+ .map(|entry| entry.unwrap_or_else(|error| panic!("{}: {error}", path.display())))+ // A link to a directory isn't followed, so that a link back up the tree can't make this go on forever.+ .filter(|entry| !entry.file_type().is_ok_and(|kind| kind.is_symlink()) || !entry.path().is_dir())+ .map(|entry| entry.path())+ .collect();+ entries.sort();+ for entry in entries {+ collect(&entry, out);+ }+ } else if std::fs::symlink_metadata(path)+ .unwrap_or_else(|error| panic!("{}: {error}", path.display()))+ .is_file()+ {+ out.push(path.to_path_buf());+ }+}++fn check(source: &[u8], options: Options, what: &dyn Fn() -> String) -> bool {+ let document = libxml_rust::parse(source, options);+ if let Err(problem) = verify(&document, source) {+ println!("FAILED: {problem}\n in {}", what());+ return false;+ }+ true+}++fn main() {+ let mut mutations = 20;+ let mut max_size = 256 * 1024;+ let mut paths = Vec::new();+ let mut args = std::env::args().skip(1);+ while let Some(arg) = args.next() {+ match arg.as_str() {+ "--mutations" => mutations = args.next().unwrap().parse().unwrap(),+ "--max-size" => max_size = args.next().unwrap().parse().unwrap(),+ _ => collect(Path::new(&arg), &mut paths),+ }+ }++ let resolver = |name: &[u8], out: &mut Vec<u8>| -> bool {+ if name == b"nbsp" {+ out.extend_from_slice("\u{a0}".as_bytes());+ return true;+ }+ false+ };+ let all_options = [+ Options {+ preserve_comments: true,+ preserve_cdata: true,+ resolve_html_entity: None,+ },+ Options {+ preserve_comments: false,+ preserve_cdata: false,+ resolve_html_entity: Some(&resolver),+ },+ ];++ let mut random = Random(0x9E37_79B9_7F4A_7C15);+ let (mut documents, mut failures) = (0u64, 0u64);+ for path in &paths {+ let source = std::fs::read(path).unwrap_or_else(|error| panic!("{}: {error}", path.display()));+ documents += 1;+ if !check(&source, all_options[0], &|| path.display().to_string()) {+ failures += 1;+ }+ if source.len() > max_size {+ continue;+ }+ for index in 0..mutations {+ let seed = random.0;+ let mutated = mutate(&mut random, &source);+ documents += 1;+ let options = all_options[index % 2];+ if !check(&mutated, options, &|| {+ format!("{} mutation {index} (state {seed:#x})", path.display())+ }) {+ failures += 1;+ let out = format!("xmlfuzz-failure-{failures}.xml");+ let _ = std::fs::write(&out, &mutated);+ println!(" written to {out}");+ }+ }+ }+ println!("{documents} documents, {failures} failures");+ // Nothing checked is no better than something failing: a mistyped path must not pass for a clean run.+ if failures != 0 || documents == 0 {+ std::process::exit(1);+ }+}diff --git a/Libraries/LibXML/Rust/src/chars.rs b/Libraries/LibXML/Rust/src/chars.rsnew file mode 100644index 00000000000..c653225f211--- /dev/null+++ b/Libraries/LibXML/Rust/src/chars.rs@@ -0,0 +1,188 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Character classes of XML 1.0 (fifth edition) and strict UTF-8 decoding.++/// S ::= (#x20 | #x9 | #xD | #xA)++pub const SPACE: u8 = 1 << 0;+/// An ASCII NameStartChar, including the colon.+pub const NAME_START: u8 = 1 << 1;+/// An ASCII NameChar, including the colon.+pub const NAME: u8 = 1 << 2;+/// PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]+pub const PUBID: u8 = 1 << 3;+/// An ASCII character that can't appear anywhere in a document: the C0 controls other than tab, LF and CR.+pub const INVALID: u8 = 1 << 4;+pub const DIGIT: u8 = 1 << 5;+pub const HEX: u8 = 1 << 6;++pub static CLASS: [u8; 256] = build_class_table();++const fn build_class_table() -> [u8; 256] {+ let mut table = [0u8; 256];+ let mut i = 0;+ while i < 128 {+ let c = i as u8;+ let mut class = 0;+ if matches!(c, b' ' | b'\t' | b'\r' | b'\n') {+ class |= SPACE;+ }+ if c.is_ascii_alphabetic() || c == b'_' || c == b':' {+ class |= NAME_START | NAME;+ }+ if c.is_ascii_digit() || c == b'-' || c == b'.' {+ class |= NAME;+ }+ if c.is_ascii_alphanumeric()+ || matches!(+ c,+ b' ' | b'\r'+ | b'\n'+ | b'-'+ | b'\''+ | b'('+ | b')'+ | b'+'+ | b','+ | b'.'+ | b'/'+ | b':'+ | b'='+ | b'?'+ | b';'+ | b'!'+ | b'*'+ | b'#'+ | b'@'+ | b'$'+ | b'_'+ | b'%'+ )+ {+ class |= PUBID;+ }+ if c < 0x20 && !matches!(c, b'\t' | b'\r' | b'\n') {+ class |= INVALID;+ }+ if c.is_ascii_digit() {+ class |= DIGIT;+ }+ if c.is_ascii_hexdigit() {+ class |= HEX;+ }+ table[i] = class;+ i += 1;+ }+ table+}++#[inline(always)]+pub fn is_space(byte: u8) -> bool {+ CLASS[byte as usize] & SPACE != 0+}++/// Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]+#[inline]+pub fn is_char(c: u32) -> bool {+ if c < 0x20 {+ return matches!(c, 0x9 | 0xA | 0xD);+ }+ c <= 0xD7FF || (0xE000..=0xFFFD).contains(&c) || (0x10000..=0x10FFFF).contains(&c)+}++/// NameStartChar, for code points at or above U+0080.+pub fn is_name_start_char(c: u32) -> bool {+ matches!(c,+ 0xC0..=0xD6+ | 0xD8..=0xF6+ | 0xF8..=0x2FF+ | 0x370..=0x37D+ | 0x37F..=0x1FFF+ | 0x200C..=0x200D+ | 0x2070..=0x218F+ | 0x2C00..=0x2FEF+ | 0x3001..=0xD7FF+ | 0xF900..=0xFDCF+ | 0xFDF0..=0xFFFD+ | 0x10000..=0xEFFFF)+}++/// NameChar, for code points at or above U+0080.+pub fn is_name_char(c: u32) -> bool {+ is_name_start_char(c) || matches!(c, 0xB7 | 0x300..=0x36F | 0x203F..=0x2040)+}++/// Decodes the UTF-8 sequence that starts at `bytes[pos]`, which must be a byte at or above 0x80. Returns the code+/// point and its length, or None for anything that isn't well-formed UTF-8: a stray continuation byte, an overlong+/// form, a surrogate, a value past U+10FFFF, or a sequence cut off by the end of the input.+#[inline]+pub fn decode_utf8(bytes: &[u8], pos: usize) -> Option<(u32, usize)> {+ let b0 = bytes[pos] as u32;+ let continuation = |index: usize| -> Option<u32> {+ let byte = *bytes.get(index)? as u32;+ if byte & 0xC0 == 0x80 { Some(byte & 0x3F) } else { None }+ };+ if b0 < 0xC2 {+ return None;+ }+ if b0 < 0xE0 {+ let c1 = continuation(pos + 1)?;+ return Some(((b0 & 0x1F) << 6 | c1, 2));+ }+ if b0 < 0xF0 {+ let c1 = continuation(pos + 1)?;+ let c2 = continuation(pos + 2)?;+ let c = (b0 & 0x0F) << 12 | c1 << 6 | c2;+ if c < 0x800 || (0xD800..=0xDFFF).contains(&c) {+ return None;+ }+ return Some((c, 3));+ }+ if b0 < 0xF5 {+ let c1 = continuation(pos + 1)?;+ let c2 = continuation(pos + 2)?;+ let c3 = continuation(pos + 3)?;+ let c = (b0 & 0x07) << 18 | c1 << 12 | c2 << 6 | c3;+ if !(0x10000..=0x10FFFF).contains(&c) {+ return None;+ }+ return Some((c, 4));+ }+ None+}++/// Appends the UTF-8 encoding of `c`, which must be a Unicode scalar value.+pub fn encode_utf8(c: u32, out: &mut Vec<u8>) {+ let mut buffer = [0u8; 4];+ let c = char::from_u32(c).unwrap_or('\u{FFFD}');+ out.extend_from_slice(c.encode_utf8(&mut buffer).as_bytes());+}++/// Whether `bytes` is a Name. With `allow_colon` unset it has to be an NCName.+pub fn is_name(bytes: &[u8], allow_colon: bool) -> bool {+ let mut pos = 0;+ let mut first = true;+ while pos < bytes.len() {+ let byte = bytes[pos];+ if byte < 0x80 {+ let wanted = if first { NAME_START } else { NAME };+ if CLASS[byte as usize] & wanted == 0 || (byte == b':' && !allow_colon) {+ return false;+ }+ pos += 1;+ } else {+ let Some((c, length)) = decode_utf8(bytes, pos) else {+ return false;+ };+ if !(if first { is_name_start_char(c) } else { is_name_char(c) }) {+ return false;+ }+ pos += length;+ }+ first = false;+ }+ !first+}diff --git a/Libraries/LibXML/Rust/src/dtd.rs b/Libraries/LibXML/Rust/src/dtd.rsnew file mode 100644index 00000000000..b15b2e9f32c--- /dev/null+++ b/Libraries/LibXML/Rust/src/dtd.rs@@ -0,0 +1,774 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The document type declaration and its internal subset.+//!+//! Nothing here validates. The subset is read for the three things that change what a document means to a parser that+//! doesn't validate: the entities it declares, the attributes it defaults, and the attributes it gives a type other+//! than CDATA, whose values are normalized differently. Everything else is only checked for being well-formed. The+//! external subset and external parameter entities are never read.++use std::collections::HashMap;+use std::rc::Rc;++use crate::chars;+use crate::chars::CLASS;+use crate::names::IdMap;+use crate::names::flag;+use crate::parser::In;+use crate::parser::MAX_ENTITY_DEPTH;+use crate::parser::Parser;+use crate::parser::R;+use crate::parser::at;+use crate::parser::lossy;+use crate::parser::scan_name;+use crate::parser::scan_nmtoken;+use crate::parser::skip_spaces;+use crate::tape::NONE;+use crate::tape::kind;++/// How deep the groups of a content model can nest.+const MAX_CONTENT_MODEL_DEPTH: u32 = 256;++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum EntityKind {+ Internal,+ /// An external parsed entity. Its text is never read.+ External,+ /// An external entity with a notation: not XML, and not something a document can include.+ Unparsed,+}++pub(crate) struct Entity {+ pub kind: EntityKind,+ /// The replacement text of an internal entity.+ pub text: Rc<[u8]>,+ /// Set while the entity's text is being parsed, to catch an entity that includes itself.+ pub expanding: bool,+}++#[derive(Clone)]+pub(crate) struct AttributeDefinition {+ pub name: u32,+ /// The string operands of the default value.+ pub default: (u32, u32),+}++#[derive(Default)]+pub(crate) struct Dtd {+ pub general: HashMap<u32, Entity>,+ pub parameter: HashMap<u32, Entity>,+ /// The attribute definitions that have a default value, of each element type that has any, by the element's+ /// name.+ pub attlists: IdMap<Rc<Vec<AttributeDefinition>>>,+ /// Every (element, attribute) that has a definition, with whether its type is a tokenized one. This is what+ /// says which definition of an attribute came first, and it keeps an element with a great many attributes from+ /// costing a walk of a list for each of them.+ pub defined_attributes: HashMap<(u32, u32), bool>,+}++/// The public identifiers of the XHTML family of DTDs. A document with one of them can use the HTML character+/// entities, as if it had read the DTD.+fn is_xhtml_public_id(public_id: &[u8]) -> bool {+ matches!(+ public_id,+ b"-//W3C//DTD XHTML 1.0 Transitional//EN"+ | b"-//W3C//DTD XHTML 1.1//EN"+ | b"-//W3C//DTD XHTML 1.0 Strict//EN"+ | b"-//W3C//DTD XHTML 1.0 Frameset//EN"+ | b"-//W3C//DTD XHTML Basic 1.0//EN"+ | b"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"+ | b"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"+ | b"-//W3C//DTD MathML 2.0//EN"+ | b"-//WAPFORUM//DTD XHTML Mobile 1.0//EN"+ | b"-//WAPFORUM//DTD XHTML Mobile 1.1//EN"+ | b"-//WAPFORUM//DTD XHTML Mobile 1.2//EN"+ )+}++/// The public and system identifiers of an ExternalID, as ranges of the input.+#[derive(Default)]+struct ExternalId {+ public: Option<(usize, usize)>,+ system: Option<(usize, usize)>,+}++impl Parser<'_, '_> {+ fn dtd_mut(&mut self) -> &mut Dtd {+ self.dtd.get_or_insert_with(Default::default)+ }++ /// Skips white space that has to be there.+ fn required_spaces(&mut self, inp: In, pos: usize, message: &str) -> R<usize> {+ let after = skip_spaces(inp.bytes, pos);+ if after == pos {+ return self.fail(inp, pos, message);+ }+ Ok(after)+ }++ /// doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('[' intSubset ']' S?)? '>'+ pub(crate) fn doctype(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = self.required_spaces(inp, start + 9, "Space required after 'DOCTYPE'")?;+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "xmlParseDocTypeDecl : no DOCTYPE name !");+ }+ let name = self.intern_name(inp, pos, name_end);+ pos = skip_spaces(bytes, name_end);++ let (external_id, next) = self.external_id(inp, pos, true)?;+ pos = next;+ self.has_external_subset = external_id.public.is_some() || external_id.system.is_some();+ if let Some((public_start, public_end)) = external_id.public {+ self.is_xhtml = is_xhtml_public_id(&bytes[public_start..public_end]);+ }++ self.tape.push(kind::DOCTYPE, name, NONE);+ for id in [external_id.public, external_id.system] {+ match id {+ Some((id_start, id_end)) => {+ let id = &bytes[id_start..id_end];+ // A line end is a LF wherever it is, and the source can't be edited to make it one.+ let (offset, length) = if id.contains(&b'\r') {+ let mut normalized = Vec::with_capacity(id.len());+ let mut index = 0;+ while index < id.len() {+ if id[index] == b'\r' {+ normalized.push(b'\n');+ index += if id.get(index + 1) == Some(&b'\n') { 2 } else { 1 };+ } else {+ normalized.push(id[index]);+ index += 1;+ }+ }+ self.arena_push(&normalized)+ } else {+ self.string(inp, id_start, id_end)+ };+ self.tape.push(kind::VALUE, offset, length);+ }+ None => self.tape.push(kind::VALUE | kind::ABSENT, self.src.len() as u32, 0),+ }+ }++ pos = skip_spaces(bytes, pos);+ if at(bytes, pos) == b'[' {+ pos = self.subset(inp, pos + 1, true)?;+ pos = skip_spaces(bytes, pos);+ }+ if at(bytes, pos) != b'>' {+ return self.fail(inp, pos, "DOCTYPE improperly terminated");+ }+ Ok(pos + 1)+ }++ /// ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral+ ///+ /// A notation declaration can also have a public identifier alone, which `strict` rules out.+ fn external_id(&mut self, inp: In, pos: usize, strict: bool) -> R<(ExternalId, usize)> {+ let bytes = inp.bytes;+ let mut id = ExternalId::default();+ if bytes[pos.min(bytes.len())..].starts_with(b"SYSTEM") {+ let literal = self.required_spaces(inp, pos + 6, "Space required after 'SYSTEM'")?;+ let (literal_start, literal_end) = self.system_literal(inp, literal)?;+ id.system = Some((literal_start, literal_end));+ return Ok((id, literal_end + 1));+ }+ if bytes[pos.min(bytes.len())..].starts_with(b"PUBLIC") {+ let literal = self.required_spaces(inp, pos + 6, "Space required after 'PUBLIC'")?;+ let (literal_start, literal_end) = self.pubid_literal(inp, literal)?;+ id.public = Some((literal_start, literal_end));+ let after = skip_spaces(bytes, literal_end + 1);+ let quote = at(bytes, after);+ if !strict && quote != b'"' && quote != b'\'' {+ return Ok((id, literal_end + 1));+ }+ if after == literal_end + 1 {+ return self.fail(inp, after, "Space required after the Public Identifier");+ }+ let (literal_start, literal_end) = self.system_literal(inp, after)?;+ id.system = Some((literal_start, literal_end));+ return Ok((id, literal_end + 1));+ }+ Ok((id, pos))+ }++ /// SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")+ ///+ /// Returns where the literal's text starts and ends, the end being the closing quote.+ fn system_literal(&mut self, inp: In, pos: usize) -> R<(usize, usize)> {+ let bytes = inp.bytes;+ let quote = at(bytes, pos);+ if quote != b'"' && quote != b'\'' {+ return self.fail(inp, pos, "SystemLiteral \" or ' expected");+ }+ let start = pos + 1;+ let mut end = start;+ loop {+ if end >= bytes.len() {+ return self.fail(inp, pos, "Unfinished System or Public ID \" or ' expected");+ }+ let byte = bytes[end];+ if byte == quote {+ break;+ }+ if byte >= 0x80 {+ end += self.check_non_ascii(inp, end)?;+ } else if CLASS[byte as usize] & chars::INVALID != 0 {+ return self.fail(inp, end, "Unfinished System or Public ID \" or ' expected");+ } else {+ end += 1;+ }+ }+ Ok((start, end))+ }++ /// PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"+ fn pubid_literal(&mut self, inp: In, pos: usize) -> R<(usize, usize)> {+ let bytes = inp.bytes;+ let quote = at(bytes, pos);+ if quote != b'"' && quote != b'\'' {+ return self.fail(inp, pos, "PubidLiteral \" or ' expected");+ }+ let start = pos + 1;+ let mut end = start;+ while end < bytes.len() && bytes[end] != quote && CLASS[bytes[end] as usize] & chars::PUBID != 0 {+ end += 1;+ }+ if at(bytes, end) != quote {+ return self.fail(inp, end, "Unfinished PubidLiteral");+ }+ Ok((start, end))+ }++ /// intSubset ::= (markupdecl | PEReference | S)*+ ///+ /// For the subset itself (`top`), parses up to the closing bracket and returns where it ends. For the+ /// replacement text of a parameter entity, parses all of it: a declaration can't start in an entity and end+ /// outside of it.+ fn subset(&mut self, inp: In, mut pos: usize, top: bool) -> R<usize> {+ let bytes = inp.bytes;+ loop {+ pos = skip_spaces(bytes, pos);+ if pos >= bytes.len() {+ if top {+ return self.fail(inp, pos, "internal subset is not finished");+ }+ return Ok(pos);+ }+ match bytes[pos] {+ b']' if top => return Ok(pos + 1),+ b'%' => pos = self.parameter_entity_reference(inp, pos)?,+ b'<' => {+ let rest = &bytes[pos..];+ pos = if rest.starts_with(b"<!ELEMENT") {+ self.element_declaration(inp, pos)?+ } else if rest.starts_with(b"<!ATTLIST") {+ self.attlist_declaration(inp, pos)?+ } else if rest.starts_with(b"<!ENTITY") {+ self.entity_declaration(inp, pos)?+ } else if rest.starts_with(b"<!NOTATION") {+ self.notation_declaration(inp, pos)?+ } else if rest.starts_with(b"<!--") {+ self.comment(inp, pos, false)?+ } else if rest.starts_with(b"<?") {+ self.processing_instruction(inp, pos, false)?+ } else {+ return self.fail(inp, pos, "internal subset is not finished");+ };+ }+ _ => return self.fail(inp, pos, "internal subset is not finished"),+ }+ }+ }++ /// PEReference ::= '%' Name ';'+ ///+ /// Between declarations, a reference to a parameter entity stands for more declarations.+ fn parameter_entity_reference(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let name_start = start + 1;+ let name_end = scan_name(bytes, name_start);+ if name_end == name_start {+ return self.fail(inp, start, "PEReference: no name");+ }+ if at(bytes, name_end) != b';' {+ return self.fail(inp, name_end, "PEReference: expecting ';'");+ }+ let name = &bytes[name_start..name_end];+ let next = name_end + 1;+ self.has_parameter_entity_references = true;++ let found = self.names.find(name, self.storage()).and_then(|id| {+ let entity = self.dtd.as_ref()?.parameter.get(&id)?;+ Some((id, entity.kind, entity.text.clone(), entity.expanding))+ });+ let Some((id, entity_kind, text, expanding)) = found else {+ // The entity may be declared in something this parser doesn't read.+ if self.standalone {+ return self.fail(inp, start, format!("PEReference: %{}; not found", lossy(name)));+ }+ return Ok(next);+ };+ if entity_kind != EntityKind::Internal {+ return Ok(next);+ }+ if expanding {+ return self.fail(inp, start, "Detected an entity reference loop");+ }+ if self.entity_depth >= MAX_ENTITY_DEPTH {+ return self.fail(inp, start, "Maximum entity nesting depth exceeded");+ }+ self.account_for_expansion(inp, start, text.len())?;++ if let Some(entity) = self.dtd_mut().parameter.get_mut(&id) {+ entity.expanding = true;+ }+ self.entity_depth += 1;+ // An error in the entity's text is reported where the document refers to the entity.+ let saved_offset = self.entity_reference_offset;+ if inp.main {+ self.entity_reference_offset = start;+ }+ let result = self.subset(+ In {+ bytes: &text,+ main: false,+ },+ 0,+ false,+ );+ self.entity_reference_offset = saved_offset;+ self.entity_depth -= 1;+ if let Some(entity) = self.dtd_mut().parameter.get_mut(&id) {+ entity.expanding = false;+ }+ result?;+ Ok(next)+ }++ /// Checks that a declaration ends where it should.+ fn end_of_declaration(&mut self, inp: In, pos: usize, message: &str) -> R<usize> {+ let pos = skip_spaces(inp.bytes, pos);+ if at(inp.bytes, pos) != b'>' {+ return self.fail(inp, pos, message);+ }+ Ok(pos + 1)+ }++ /// elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'+ /// contentspec ::= 'EMPTY' | 'ANY' | Mixed | children+ fn element_declaration(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = self.required_spaces(inp, start + 9, "Space required after 'ELEMENT'")?;+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "xmlParseElementDecl: no name for Element");+ }+ pos = self.required_spaces(inp, name_end, "Space required after the element name")?;++ let rest = &bytes[pos..];+ if rest.starts_with(b"EMPTY") {+ pos += 5;+ } else if rest.starts_with(b"ANY") {+ pos += 3;+ } else if rest.starts_with(b"(") {+ let inside = skip_spaces(bytes, pos + 1);+ if bytes[inside..].starts_with(b"#PCDATA") {+ pos = self.mixed_content(inp, inside + 7)?;+ } else {+ pos = self.content_group(inp, inside, 1)?;+ if matches!(at(bytes, pos), b'?' | b'*' | b'+') {+ pos += 1;+ }+ }+ } else {+ return self.fail(inp, pos, "xmlParseElementDecl: 'EMPTY', 'ANY' or '(' expected");+ }+ self.end_of_declaration(inp, pos, "xmlParseElementDecl: expected '>' at the end")+ }++ /// Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')'+ ///+ /// `pos` is right after '#PCDATA'.+ fn mixed_content(&mut self, inp: In, mut pos: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut names = 0;+ loop {+ pos = skip_spaces(bytes, pos);+ match at(bytes, pos) {+ b')' => {+ pos += 1;+ break;+ }+ b'|' => {+ pos = skip_spaces(bytes, pos + 1);+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "xmlParseElementMixedContentDecl : Name expected");+ }+ names += 1;+ pos = name_end;+ }+ _ => return self.fail(inp, pos, "MixedContentDecl : '|' or ')*' expected"),+ }+ }+ if at(bytes, pos) == b'*' {+ return Ok(pos + 1);+ }+ if names > 0 {+ return self.fail(inp, pos, "MixedContentDecl : '|' or ')*' expected");+ }+ Ok(pos)+ }++ /// choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')'+ /// seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'+ /// cp ::= (Name | choice | seq) ('?' | '*' | '+')?+ ///+ /// `pos` is after the opening parenthesis and the white space that follows it. Returns where the closing+ /// parenthesis ends.+ fn content_group(&mut self, inp: In, mut pos: usize, depth: u32) -> R<usize> {+ let bytes = inp.bytes;+ if depth > MAX_CONTENT_MODEL_DEPTH {+ return self.fail(inp, pos, "xmlParseElementChildrenContentDecl : depth too deep");+ }+ let mut separator = 0u8;+ loop {+ // A content particle.+ if at(bytes, pos) == b'(' {+ let inside = skip_spaces(bytes, pos + 1);+ pos = self.content_group(inp, inside, depth + 1)?;+ } else {+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "ContentDecl : Name or '(' expected");+ }+ pos = name_end;+ }+ if matches!(at(bytes, pos), b'?' | b'*' | b'+') {+ pos += 1;+ }++ pos = skip_spaces(bytes, pos);+ let byte = at(bytes, pos);+ if byte == b')' {+ return Ok(pos + 1);+ }+ if byte != b',' && byte != b'|' {+ return self.fail(inp, pos, "ContentDecl : ',' '|' or ')' expected");+ }+ if separator == 0 {+ separator = byte;+ } else if separator != byte {+ let message = format!("xmlParseElementChildrenContentDecl : '{}' expected", separator as char);+ return self.fail(inp, pos, message);+ }+ pos = skip_spaces(bytes, pos + 1);+ }+ }++ /// AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'+ /// AttDef ::= S Name S AttType S DefaultDecl+ fn attlist_declaration(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = self.required_spaces(inp, start + 9, "Space required after '<!ATTLIST'")?;+ let element_end = scan_name(bytes, pos);+ if element_end == pos {+ return self.fail(inp, pos, "ATTLIST: no name for Element");+ }+ let element = self.intern_name(inp, pos, element_end);+ pos = element_end;++ loop {+ let after_spaces = skip_spaces(bytes, pos);+ if at(bytes, after_spaces) == b'>' {+ return Ok(after_spaces + 1);+ }+ if after_spaces == pos {+ return self.fail(inp, pos, "Space required after the attribute default value");+ }+ let name_end = scan_name(bytes, after_spaces);+ if name_end == after_spaces {+ return self.fail(inp, after_spaces, "ATTLIST: no name for Attribute");+ }+ let name = self.intern_name(inp, after_spaces, name_end);+ pos = self.required_spaces(inp, name_end, "Space required after the attribute name")?;++ let (tokenized, next) = self.attribute_type(inp, pos)?;+ pos = self.required_spaces(inp, next, "Space required after the attribute type")?;++ // DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)+ let rest = &bytes[pos..];+ let mut default = None;+ if rest.starts_with(b"#REQUIRED") {+ pos += 9;+ } else if rest.starts_with(b"#IMPLIED") {+ pos += 8;+ } else {+ if rest.starts_with(b"#FIXED") {+ pos = self.required_spaces(inp, pos + 6, "Space required after '#FIXED'")?;+ }+ let quote = at(bytes, pos);+ if quote != b'"' && quote != b'\'' {+ return self.fail(inp, pos, "Attribute default value declaration error");+ }+ let (offset, length, next) = self.attribute_value(inp, pos, tokenized)?;+ default = Some((offset, length));+ pos = next;+ }++ // The first definition of an attribute is the one that counts.+ let mut element_flags = 0;+ if default.is_some() {+ element_flags |= flag::HAS_DEFAULTS;+ }+ if tokenized {+ element_flags |= flag::HAS_TOKENIZED;+ }+ self.names.get_mut(element).flags |= element_flags;+ let dtd = self.dtd_mut();+ if let std::collections::hash_map::Entry::Vacant(entry) = dtd.defined_attributes.entry((element, name)) {+ entry.insert(tokenized);+ // Only a definition with a default is ever looked at again, and an element can have a great many+ // without one.+ if let Some(default) = default {+ Rc::make_mut(dtd.attlists.entry(element).or_default()).push(AttributeDefinition { name, default });+ }+ }+ }+ }++ /// AttType ::= StringType | TokenizedType | EnumeratedType+ ///+ /// Returns whether the type is anything other than CDATA, and where it ends.+ fn attribute_type(&mut self, inp: In, pos: usize) -> R<(bool, usize)> {+ let bytes = inp.bytes;+ let rest = &bytes[pos..];+ if rest.starts_with(b"CDATA") {+ return Ok((false, pos + 5));+ }+ // The longer of two keywords that start the same has to be tried first.+ for keyword in [+ &b"IDREFS"[..],+ b"IDREF",+ b"ID",+ b"ENTITY",+ b"ENTITIES",+ b"NMTOKENS",+ b"NMTOKEN",+ ] {+ if rest.starts_with(keyword) {+ return Ok((true, pos + keyword.len()));+ }+ }++ // EnumeratedType ::= NotationType | Enumeration+ // NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'+ // Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'+ let mut pos = pos;+ let is_notation = rest.starts_with(b"NOTATION");+ if is_notation {+ pos = self.required_spaces(inp, pos + 8, "Space required after 'NOTATION'")?;+ }+ if at(bytes, pos) != b'(' {+ let message = if is_notation {+ "'(' required to start 'NOTATION'"+ } else {+ "Invalid attribute type"+ };+ return self.fail(inp, pos, message);+ }+ pos += 1;+ loop {+ pos = skip_spaces(bytes, pos);+ let token_end = if is_notation {+ scan_name(bytes, pos)+ } else {+ scan_nmtoken(bytes, pos)+ };+ if token_end == pos {+ let message = if is_notation {+ "Name expected in NOTATION declaration"+ } else {+ "NmToken expected in ATTLIST enumeration"+ };+ return self.fail(inp, pos, message);+ }+ pos = skip_spaces(bytes, token_end);+ match at(bytes, pos) {+ b')' => return Ok((true, pos + 1)),+ b'|' => pos += 1,+ _ => {+ let message = if is_notation {+ "')' required to finish NOTATION declaration"+ } else {+ "')' required to finish ATTLIST enumeration"+ };+ return self.fail(inp, pos, message);+ }+ }+ }+ }++ /// EntityDecl ::= '<!ENTITY' S Name S EntityDef S? '>' | '<!ENTITY' S '%' S Name S PEDef S? '>'+ /// EntityDef ::= EntityValue | (ExternalID NDataDecl?)+ /// PEDef ::= EntityValue | ExternalID+ fn entity_declaration(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = self.required_spaces(inp, start + 8, "Space required after '<!ENTITY'")?;+ let is_parameter = at(bytes, pos) == b'%';+ if is_parameter {+ pos = self.required_spaces(inp, pos + 1, "Space required after '%'")?;+ }+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "xmlParseEntityDecl: no name");+ }+ let name_bytes = &bytes[pos..name_end];+ if name_bytes.contains(&b':') {+ let message = format!("colons are forbidden from entities names '{}'", lossy(name_bytes));+ self.namespace_error(inp, pos, message);+ }+ let name = self.intern_name(inp, pos, name_end);+ pos = self.required_spaces(inp, name_end, "Space required after the entity name")?;++ let entity;+ let quote = at(bytes, pos);+ if quote == b'"' || quote == b'\'' {+ let (text, next) = self.entity_value(inp, pos)?;+ entity = Entity {+ kind: EntityKind::Internal,+ text,+ expanding: false,+ };+ pos = next;+ } else {+ let (external_id, next) = self.external_id(inp, pos, true)?;+ let Some((system_start, system_end)) = external_id.system else {+ return self.fail(inp, pos, "Entity value required");+ };+ if bytes[system_start..system_end].contains(&b'#') {+ return self.fail(inp, system_start, "Fragment not allowed");+ }+ pos = next;+ let mut entity_kind = EntityKind::External;+ if !is_parameter {+ let after_spaces = skip_spaces(bytes, pos);+ if bytes[after_spaces..].starts_with(b"NDATA") {+ if after_spaces == pos {+ return self.fail(inp, pos, "Space required before 'NDATA'");+ }+ pos = self.required_spaces(inp, after_spaces + 5, "Space required after 'NDATA'")?;+ let notation_end = scan_name(bytes, pos);+ if notation_end == pos {+ return self.fail(inp, pos, "xmlParseEntityDecl: no notation name");+ }+ pos = notation_end;+ entity_kind = EntityKind::Unparsed;+ }+ }+ entity = Entity {+ kind: entity_kind,+ text: Rc::from(&b""[..]),+ expanding: false,+ };+ }++ let message = format!("xmlParseEntityDecl: entity {} not terminated", lossy(name_bytes));+ pos = self.end_of_declaration(inp, pos, &message)?;++ // The first declaration of an entity is the one that counts. The five predefined entities are what they are.+ let is_predefined = matches!(name_bytes, b"lt" | b"gt" | b"amp" | b"apos" | b"quot");+ let dtd = self.dtd_mut();+ if is_parameter {+ dtd.parameter.entry(name).or_insert(entity);+ } else if !is_predefined {+ dtd.general.entry(name).or_insert(entity);+ }+ Ok(pos)+ }++ /// EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' | "'" ([^%&'] | PEReference | Reference)* "'"+ ///+ /// Returns the entity's replacement text: the literal with its character references replaced. References to+ /// general entities stay as they are, to be followed when the entity is used.+ ///+ /// Line ends stay as they are too, and are normalized where the entity is used, as they are in libxml2. So a CR+ /// that is written as a character reference becomes a line end in content like one that is written out, and a+ /// CR LF pair is two spaces in an attribute value.+ fn entity_value(&mut self, inp: In, start: usize) -> R<(Rc<[u8]>, usize)> {+ let bytes = inp.bytes;+ let quote = bytes[start];+ let mut pos = start + 1;+ let mut text = Vec::new();+ loop {+ if pos >= bytes.len() {+ return self.fail(inp, start, "EntityValue: \" expected");+ }+ let byte = bytes[pos];+ if byte == quote {+ break;+ }+ match byte {+ b'&' => {+ if at(bytes, pos + 1) == b'#' {+ let (c, next) = self.character_reference(inp, pos)?;+ chars::encode_utf8(c, &mut text);+ pos = next;+ } else {+ let name_end = scan_name(bytes, pos + 1);+ if name_end == pos + 1 || at(bytes, name_end) != b';' {+ return self.fail(inp, pos, "EntityValue: '&' forbidden except for entities references");+ }+ text.extend_from_slice(&bytes[pos..=name_end]);+ pos = name_end + 1;+ }+ }+ // In the internal subset a parameter entity can only be referenced between declarations.+ b'%' => return self.fail(inp, pos, "PEReferences forbidden in internal subset"),+ _ if byte >= 0x80 => {+ let length = self.check_non_ascii(inp, pos)?;+ text.extend_from_slice(&bytes[pos..pos + length]);+ pos += length;+ }+ _ if CLASS[byte as usize] & chars::INVALID != 0 => {+ return self.fail(inp, pos, "invalid character in entity value");+ }+ _ => {+ text.push(byte);+ pos += 1;+ }+ }+ }+ Ok((Rc::from(text), pos + 1))+ }++ /// NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'+ fn notation_declaration(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = self.required_spaces(inp, start + 10, "Space required after '<!NOTATION'")?;+ let name_end = scan_name(bytes, pos);+ if name_end == pos {+ return self.fail(inp, pos, "NOTATION: Name expected here");+ }+ if bytes[pos..name_end].contains(&b':') {+ let message = format!(+ "colons are forbidden from notation names '{}'",+ lossy(&bytes[pos..name_end])+ );+ self.namespace_error(inp, pos, message);+ }+ pos = self.required_spaces(inp, name_end, "Space required after the NOTATION name'")?;+ let (external_id, next) = self.external_id(inp, pos, false)?;+ if external_id.public.is_none() && external_id.system.is_none() {+ return self.fail(inp, pos, "NOTATION: external identifier expected");+ }+ self.end_of_declaration(inp, next, "'>' required to close NOTATION declaration")+ }+}diff --git a/Libraries/LibXML/Rust/src/dump.rs b/Libraries/LibXML/Rust/src/dump.rsnew file mode 100644index 00000000000..2281ee794da--- /dev/null+++ b/Libraries/LibXML/Rust/src/dump.rs@@ -0,0 +1,142 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A tape as text, one event to a line, for tests and for comparing against another parser.++use std::fmt::Write;++use crate::Document;+use crate::tape::NONE;+use crate::tape::kind;++fn escape(bytes: &[u8], out: &mut String) {+ for &byte in bytes {+ match byte {+ b'\n' => out.push_str("\\n"),+ b'\r' => out.push_str("\\r"),+ b'\t' => out.push_str("\\t"),+ b'\\' => out.push_str("\\\\"),+ b'"' => out.push_str("\\\""),+ 0x20..=0x7E => out.push(byte as char),+ _ => {+ let _ = write!(out, "\\x{byte:02X}");+ }+ }+ }+}++/// Writes the events of `document`. Adjacent text is joined, since where a parser splits a run of text is up to it.+/// With `namespaces`, each element and attribute name is followed by its namespace name in braces.+pub fn dump(document: &Document, source: &[u8], namespaces: bool) -> String {+ let storage = document.storage(source);+ let tape = &document.tape;+ let mut out = String::new();+ let name = |id: u32, out: &mut String| escape(document.names.bytes(id, storage), out);+ let namespace = |id: u32, out: &mut String| {+ if namespaces && id != NONE {+ out.push('{');+ escape(document.names.bytes(id, storage), out);+ out.push('}');+ }+ };++ let mut errors = document.errors.iter().peekable();+ let mut in_text = false;+ let mut index = 0;+ loop {+ while let Some(error) = errors.peek() {+ if error.row as usize > index {+ break;+ }+ if in_text {+ out.push('\n');+ in_text = false;+ }+ let _ = writeln!(out, "{} {}", if error.fatal { "FATAL" } else { "ERROR" }, error.message);+ errors.next();+ }+ if index >= tape.len() {+ break;+ }+ let (row_kind, a, b) = tape.row(index);+ let is_text = row_kind & kind::MASK == kind::TEXT;+ if in_text && !is_text {+ out.push('\n');+ in_text = false;+ }+ match row_kind & kind::MASK {+ kind::START => {+ out.push_str("START ");+ name(a, &mut out);+ namespace(b, &mut out);+ index += 1;+ while index < tape.len() && tape.row(index).0 & kind::MASK == kind::ATTR {+ let (_, attribute, attribute_namespace) = tape.row(index);+ let (_, offset, length) = tape.row(index + 1);+ out.push(' ');+ name(attribute, &mut out);+ namespace(attribute_namespace, &mut out);+ out.push_str("=\"");+ escape(storage.get(offset, length), &mut out);+ out.push('"');+ index += 2;+ }+ out.push('\n');+ continue;+ }+ kind::END => {+ out.push_str("END ");+ name(a, &mut out);+ out.push('\n');+ }+ kind::TEXT => {+ if !in_text {+ out.push_str("TEXT ");+ in_text = true;+ }+ escape(storage.get(a, b), &mut out);+ }+ kind::CDATA => {+ out.push_str("CDATA ");+ escape(storage.get(a, b), &mut out);+ out.push('\n');+ }+ kind::COMMENT => {+ out.push_str("COMMENT ");+ escape(storage.get(a, b), &mut out);+ out.push('\n');+ }+ kind::PI => {+ let (_, offset, length) = tape.row(index + 1);+ out.push_str("PI ");+ name(a, &mut out);+ out.push(' ');+ escape(storage.get(offset, length), &mut out);+ out.push('\n');+ index += 1;+ }+ kind::DOCTYPE => {+ out.push_str("DOCTYPE ");+ name(a, &mut out);+ for id in [index + 1, index + 2] {+ let (value_kind, offset, length) = tape.row(id);+ if value_kind & kind::ABSENT != 0 {+ out.push_str(" -");+ } else {+ out.push_str(" \"");+ escape(storage.get(offset, length), &mut out);+ out.push('"');+ }+ }+ out.push('\n');+ index += 2;+ }+ _ => {}+ }+ index += 1;+ }+ out+}diff --git a/Libraries/LibXML/Rust/src/ffi.rs b/Libraries/LibXML/Rust/src/ffi.rsnew file mode 100644index 00000000000..18308c7f427--- /dev/null+++ b/Libraries/LibXML/Rust/src/ffi.rs@@ -0,0 +1,244 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The C interface. `rust_xml_parse` returns an opaque document, `rust_xml_document_view` hands out pointers to its+//! columns, and `rust_xml_document_free` releases it. The view is plain data: reading a document from C++ is loops+//! over arrays, with no call back into Rust per row.++use std::ffi::c_void;++use crate::Document;+use crate::Options;+use crate::rust_panic::abort_on_panic;+use crate::tape::kind;++/// What the low bits of a row's kind byte say. See `tape`.+#[repr(u8)]+pub enum XmlRowKind {+ Start = 1,+ Attribute = 2,+ Value = 3,+ End = 4,+ Text = 5,+ Cdata = 6,+ Comment = 7,+ ProcessingInstruction = 8,+ Doctype = 9,+}++/// The bits of a kind byte that hold the kind.+#[repr(u8)]+pub enum XmlRowKindBits {+ Mask = 0x0F,+}++/// The flags in the kind byte of an attribute row.+#[repr(u8)]+pub enum XmlAttributeFlag {+ /// The attribute wasn't in the tag, its value is the default the DTD declares.+ Defaulted = 0x40,+ /// The attribute is a namespace declaration.+ NamespaceDeclaration = 0x80,+}++/// The flags in the kind byte of a value row.+#[repr(u8)]+pub enum XmlValueFlag {+ /// On an id of a doctype: there is no such id, as opposed to an empty one.+ Absent = 0x80,+}++// The values above are written out because the header generator can't follow a path to a constant.+const _: () = {+ assert!(XmlRowKind::Start as u8 == kind::START);+ assert!(XmlRowKind::Attribute as u8 == kind::ATTR);+ assert!(XmlRowKind::Value as u8 == kind::VALUE);+ assert!(XmlRowKind::End as u8 == kind::END);+ assert!(XmlRowKind::Text as u8 == kind::TEXT);+ assert!(XmlRowKind::Cdata as u8 == kind::CDATA);+ assert!(XmlRowKind::Comment as u8 == kind::COMMENT);+ assert!(XmlRowKind::ProcessingInstruction as u8 == kind::PI);+ assert!(XmlRowKind::Doctype as u8 == kind::DOCTYPE);+ assert!(XmlRowKindBits::Mask as u8 == kind::MASK);+ assert!(XmlAttributeFlag::Defaulted as u8 == kind::DEFAULTED);+ assert!(XmlAttributeFlag::NamespaceDeclaration as u8 == kind::NAMESPACE_DECLARATION);+ assert!(XmlValueFlag::Absent as u8 == kind::ABSENT);+};++/// Resolves the name of an HTML character entity. Writes what it stands for, as UTF-8, to `out`, which has room for+/// `capacity` bytes, and returns how many bytes that was, or a negative number if there is no such entity.+/// Null for no resolver.+pub type XmlHtmlEntityResolver = Option<+ unsafe extern "C" fn(+ context: *mut c_void,+ name: *const u8,+ name_length: usize,+ out: *mut u8,+ capacity: usize,+ ) -> isize,+>;++#[repr(C)]+pub struct XmlParseOptions {+ pub preserve_comments: bool,+ pub preserve_cdata: bool,+ /// Used for references to undeclared entities in a document whose doctype has one of the XHTML public ids.+ pub resolve_html_entity: XmlHtmlEntityResolver,+ pub resolver_context: *mut c_void,+}++/// Where a name is, in the address space string operands point into: the source, then the arena.+#[repr(C)]+pub struct XmlName {+ pub offset: u32,+ pub length: u32,+}++#[repr(C)]+pub struct XmlError {+ pub message: *const u8,+ pub message_length: usize,+ pub offset: u32,+ pub line: u32,+ pub column: u32,+ /// The row the error comes before.+ pub row: u32,+ pub fatal: bool,+}++/// Pointers into a document. They are good until the document is freed.+#[repr(C)]+pub struct XmlDocumentView {+ pub kinds: *const u8,+ pub a: *const u32,+ pub b: *const u32,+ pub row_count: usize,+ pub arena: *const u8,+ pub arena_length: usize,+ pub names: *const XmlName,+ pub name_count: usize,+ pub errors: *const XmlError,+ pub error_count: usize,+ pub version_1_0: bool,+ /// Whether the parser got past the XML declaration. If it didn't, the document never started.+ pub started: bool,+}++pub struct XmlDocument {+ document: Document,+ names: Vec<XmlName>,+ errors: Vec<XmlError>,+}++/// Parses the `length` bytes of UTF-8 at `source` as a whole document. Never returns null: a document that isn't+/// well-formed is a document with errors in it. The result has to be freed with `rust_xml_document_free`.+///+/// # Safety+/// `source` must point to `length` readable bytes, or `length` must be zero. `options` must be null or point to a+/// valid `XmlParseOptions`. The resolver, if there is one, must be safe to call with `resolver_context` for as long+/// as this call lasts.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_xml_parse(+ source: *const u8,+ length: usize,+ options: *const XmlParseOptions,+) -> *mut XmlDocument {+ abort_on_panic(|| {+ // SAFETY: The caller promises `length` readable bytes at `source`.+ let source: &[u8] = unsafe { ak::slice_from_raw_parts(source, length) };+ // SAFETY: The caller promises `options` is null or valid.+ let options = unsafe { options.as_ref() };++ let resolver = options.and_then(|options| {+ let resolve = options.resolve_html_entity?;+ let context = options.resolver_context;+ Some(move |name: &[u8], out: &mut Vec<u8>| -> bool {+ let mut buffer = [0u8; 64];+ // SAFETY: The caller promises the resolver can be called with its context. It is given a buffer and+ // the buffer's true size.+ let written = unsafe { resolve(context, name.as_ptr(), name.len(), buffer.as_mut_ptr(), buffer.len()) };+ match usize::try_from(written) {+ Ok(written) if written <= buffer.len() => {+ out.extend_from_slice(&buffer[..written]);+ true+ }+ _ => false,+ }+ })+ });+ let document = crate::parse(+ source,+ Options {+ preserve_comments: options.is_some_and(|options| options.preserve_comments),+ preserve_cdata: options.is_none_or(|options| options.preserve_cdata),+ resolve_html_entity: resolver.as_ref().map(|resolver| resolver as crate::HtmlEntityResolver),+ },+ );++ let names = document+ .names+ .entries()+ .iter()+ .map(|name| XmlName {+ offset: name.offset,+ length: name.length,+ })+ .collect();+ let errors = document+ .errors+ .iter()+ .map(|error| XmlError {+ // The message is owned by `document`, which lives exactly as long as this pointer to it.+ message: error.message.as_ptr(),+ message_length: error.message.len(),+ offset: error.offset,+ line: error.line,+ column: error.column,+ row: error.row,+ fatal: error.fatal,+ })+ .collect();+ Box::into_raw(Box::new(XmlDocument {+ document,+ names,+ errors,+ }))+ })+}++/// # Safety+/// `document` must be a document from `rust_xml_parse` that hasn't been freed.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_xml_document_view(document: *const XmlDocument) -> XmlDocumentView {+ // SAFETY: The caller promises a live document.+ let document = unsafe { &*document };+ let tape = &document.document.tape;+ XmlDocumentView {+ kinds: tape.kinds().as_ptr(),+ a: tape.a().as_ptr(),+ b: tape.b().as_ptr(),+ row_count: tape.len(),+ arena: document.document.arena.as_ptr(),+ arena_length: document.document.arena.len(),+ names: document.names.as_ptr(),+ name_count: document.names.len(),+ errors: document.errors.as_ptr(),+ error_count: document.errors.len(),+ version_1_0: document.document.version_1_0,+ started: document.document.started,+ }+}++/// # Safety+/// `document` must be null or a document from `rust_xml_parse` that hasn't been freed.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_xml_document_free(document: *mut XmlDocument) {+ if !document.is_null() {+ // SAFETY: The caller promises the pointer came from `rust_xml_parse`, where it was a Box, and that this is+ // the only time it is freed.+ drop(unsafe { Box::from_raw(document) });+ }+}diff --git a/Libraries/LibXML/Rust/src/lib.rs b/Libraries/LibXML/Rust/src/lib.rsnew file mode 100644index 00000000000..01e5b00ab84--- /dev/null+++ b/Libraries/LibXML/Rust/src/lib.rs@@ -0,0 +1,43 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! An XML parser.+//!+//! `parse` takes a whole document as UTF-8 and returns a `Document`: a flat tape of events in document order (see+//! `tape`), the table of the names in it, and the errors.++#![deny(unsafe_op_in_unsafe_fn)]++#[cfg(feature = "allocator")]+extern crate ladybird_allocator;++#[path = "../../../RustDemangle.rs"]+mod rust_demangle;++#[path = "../../../RustPanic.rs"]+mod rust_panic;++mod chars;+mod dtd;+pub mod dump;+pub mod ffi;+pub mod names;+mod parser;+mod scan;+pub mod tape;+pub mod verify;++pub use parser::Document;+pub use parser::Error;+pub use parser::HtmlEntityResolver;+pub use parser::Options;++/// Parses `source`, which has to be the whole document, as UTF-8.+pub fn parse(source: &[u8], options: Options) -> Document {+ let mut parser = parser::Parser::new(source, options);+ parser.parse();+ parser.finish()+}diff --git a/Libraries/LibXML/Rust/src/names.rs b/Libraries/LibXML/Rust/src/names.rsnew file mode 100644index 00000000000..da4e97b89c2--- /dev/null+++ b/Libraries/LibXML/Rust/src/names.rs@@ -0,0 +1,430 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The table of every distinct name in a document: element and attribute names, prefixes, namespace names.+//!+//! A name is interned the first time it is seen and is a 32-bit id from then on, so that comparing two names, finding+//! a prefix's namespace or checking a tag for a repeated attribute never looks at the name's bytes again. An entry+//! doesn't own its bytes: it points at the first place the name was written, in the source or in the arena.++use std::hash::BuildHasher;+use std::hash::RandomState;+use std::sync::OnceLock;++use crate::chars;+use crate::tape::NONE;++pub mod flag {+ /// The name is "xmlns".+ pub const IS_XMLNS: u8 = 1 << 0;+ /// The name is a QName with the prefix "xmlns".+ pub const PREFIX_XMLNS: u8 = 1 << 1;+ /// The name is a QName with the prefix "xml".+ pub const PREFIX_XML: u8 = 1 << 2;+ /// The name is a QName with a prefix.+ pub const HAS_PREFIX: u8 = 1 << 3;+ /// The name has a colon but isn't a QName: more than one colon, or nothing or no NCName on one side of it.+ pub const NOT_A_QNAME: u8 = 1 << 4;+ /// As an element name: the DTD declares an attribute with a default value for it.+ pub const HAS_DEFAULTS: u8 = 1 << 5;+ /// The flags above have been worked out.+ pub const ANALYZED: u8 = 1 << 6;+ /// As an element name: the DTD declares an attribute of a type other than CDATA for it.+ pub const HAS_TOKENIZED: u8 = 1 << 7;++ /// The flags that are about a name as an element name, and say nothing when it is an attribute's.+ pub const ELEMENT_ONLY: u8 = HAS_DEFAULTS | HAS_TOKENIZED;+ /// The flags that send a start tag through namespace processing.+ pub const NEEDS_NAMESPACE_PROCESSING: u8 = IS_XMLNS | PREFIX_XMLNS | HAS_PREFIX | NOT_A_QNAME | HAS_DEFAULTS;+}++/// The first sixteen bytes of a name as two little-endian words, with zeros past its end.+///+/// OPTIMIZATION: Nearly every name is at most sixteen bytes long, and then its key is all of it. Hashing a name and+/// comparing it to an entry are a few operations on two registers, with no loop over bytes, no call to memcmp, and+/// no trip to wherever in the document the entry's bytes are.+#[derive(Clone, Copy, PartialEq, Eq)]+pub struct Key(u64, u64);++impl Key {+ /// The key of `bytes[start..start + length]`.+ #[inline(always)]+ pub fn at(bytes: &[u8], start: usize, length: usize) -> Key {+ if start + 16 <= bytes.len() {+ let w0 = u64::from_le_bytes(bytes[start..start + 8].try_into().unwrap_or([0; 8]));+ let w1 = u64::from_le_bytes(bytes[start + 8..start + 16].try_into().unwrap_or([0; 8]));+ if length >= 16 {+ Key(w0, w1)+ } else if length >= 8 {+ Key(w0, w1 & !(u64::MAX << ((length - 8) * 8)))+ } else {+ Key(w0 & !(u64::MAX << (length * 8)), 0)+ }+ } else {+ Key::near_end(&bytes[start..start + length])+ }+ }++ #[inline(always)]+ pub fn of(bytes: &[u8]) -> Key {+ Key::at(bytes, 0, bytes.len())+ }++ /// For a name with fewer than sixteen bytes of input from its start on.+ #[cold]+ #[inline(never)]+ fn near_end(name: &[u8]) -> Key {+ let mut buffer = [0u8; 16];+ let length = name.len().min(16);+ buffer[..length].copy_from_slice(&name[..length]);+ let w0 = u64::from_le_bytes(buffer[..8].try_into().unwrap_or([0; 8]));+ let w1 = u64::from_le_bytes(buffer[8..].try_into().unwrap_or([0; 8]));+ Key(w0, w1)+ }+}++/// Hashes a name id for a map keyed by one.+///+/// OPTIMIZATION: Ids are small integers the parser hands out itself, in order, so there is nothing for a keyed hash+/// to defend against, and one multiplication spreads them well enough.+#[derive(Default)]+pub struct IdHasher(u64);++impl std::hash::Hasher for IdHasher {+ fn finish(&self) -> u64 {+ self.0+ }++ fn write(&mut self, bytes: &[u8]) {+ for &byte in bytes {+ self.0 = (self.0 ^ byte as u64).wrapping_mul(K0);+ }+ }++ fn write_u32(&mut self, id: u32) {+ self.0 = (id as u64 + 1).wrapping_mul(K0).rotate_left(32);+ }+}++pub type IdMap<V> = std::collections::HashMap<u32, V, std::hash::BuildHasherDefault<IdHasher>>;++#[derive(Clone, Copy)]+pub struct Name {+ key: Key,+ hash: u32,+ pub length: u32,+ pub offset: u32,+ /// The id of the prefix, or NONE.+ pub prefix: u32,+ /// The id of the local part. For a name without a prefix, the name itself.+ pub local: u32,+ /// As a prefix: the index of its innermost binding in scope, or NONE.+ pub binding: u32,+ /// The start tag the name was last seen as an attribute of.+ pub stamp: u32,+ pub flags: u8,+}++pub struct Names {+ entries: Vec<Name>,+ /// Open addressing with linear probing. A slot holds an id plus one, or zero when empty.+ table: Vec<u32>,+ seed: u64,+}++/// The two byte ranges a name's offset can point into.+#[derive(Clone, Copy)]+pub struct Storage<'a> {+ pub source: &'a [u8],+ pub arena: &'a [u8],+}++impl<'a> Storage<'a> {+ #[inline(always)]+ pub fn new(source: &'a [u8], arena: &'a [u8]) -> Self {+ Storage { source, arena }+ }++ #[inline(always)]+ pub fn get(self, offset: u32, length: u32) -> &'a [u8] {+ let offset = offset as usize;+ let length = length as usize;+ if offset < self.source.len() {+ &self.source[offset..offset + length]+ } else {+ let offset = offset - self.source.len();+ &self.arena[offset..offset + length]+ }+ }+}++fn process_seed() -> u64 {+ // The seed only has to be unpredictable to whoever wrote the document, so that a document can't be built to make+ // every name collide.+ static SEED: OnceLock<u64> = OnceLock::new();+ *SEED.get_or_init(|| RandomState::new().hash_one(0x584D4Cu32) | 1)+}++const K0: u64 = 0x9E37_79B9_7F4A_7C15;+const K1: u64 = 0xD6E8_FEB8_6659_FD93;++#[inline(always)]+fn hash_name(seed: u64, key: Key, name: &[u8]) -> u32 {+ let mut hash = (key.0 ^ seed).wrapping_mul(K0);+ hash = (hash.rotate_left(29) ^ key.1 ^ name.len() as u64).wrapping_mul(K1);+ if name.len() > 16 {+ hash = hash_tail(hash, &name[16..]);+ }+ (hash >> 32) as u32 ^ hash as u32+}++#[inline(never)]+fn hash_tail(mut hash: u64, tail: &[u8]) -> u64 {+ for chunk in tail.chunks(8) {+ let mut word = 0u64;+ for (index, &byte) in chunk.iter().enumerate() {+ word |= (byte as u64) << (index * 8);+ }+ hash = (hash.rotate_left(29) ^ word).wrapping_mul(K1);+ }+ hash+}++impl Default for Names {+ fn default() -> Self {+ Self::new()+ }+}++impl Names {+ pub fn new() -> Self {+ Names {+ entries: Vec::with_capacity(64),+ table: vec![0; 128],+ seed: process_seed(),+ }+ }++ pub fn len(&self) -> usize {+ self.entries.len()+ }++ pub fn is_empty(&self) -> bool {+ self.entries.is_empty()+ }++ pub fn entries(&self) -> &[Name] {+ &self.entries+ }++ #[inline(always)]+ pub fn get(&self, id: u32) -> &Name {+ &self.entries[id as usize]+ }++ #[inline(always)]+ pub fn get_mut(&mut self, id: u32) -> &mut Name {+ &mut self.entries[id as usize]+ }++ #[inline(always)]+ pub fn bytes<'a>(&self, id: u32, storage: Storage<'a>) -> &'a [u8] {+ let name = &self.entries[id as usize];+ storage.get(name.offset, name.length)+ }++ /// Whether the name `id` is what is written at `bytes[start..]`. The caller checks what comes after it.+ #[inline(always)]+ pub fn is_at(&self, id: u32, bytes: &[u8], start: usize, storage: Storage) -> bool {+ let name = &self.entries[id as usize];+ let length = name.length as usize;+ if start + length > bytes.len() || Key::at(bytes, start, length) != name.key {+ return false;+ }+ length <= 16 || storage.get(name.offset, name.length)[16..] == bytes[start + 16..start + length]+ }++ /// Looks `name` up. Returns its id, or the slot it belongs in.+ #[inline(always)]+ fn lookup(&self, key: Key, hash: u32, name: &[u8], storage: Storage) -> Result<u32, usize> {+ let mask = self.table.len() - 1;+ let mut slot = hash as usize & mask;+ loop {+ let entry = self.table[slot];+ if entry == 0 {+ return Err(slot);+ }+ let candidate = &self.entries[entry as usize - 1];+ if candidate.hash == hash+ && candidate.key == key+ && candidate.length as usize == name.len()+ && (name.len() <= 16 || storage.get(candidate.offset, candidate.length)[16..] == name[16..])+ {+ return Ok(entry - 1);+ }+ slot = (slot + 1) & mask;+ }+ }++ /// Returns the id of `name` if it is in the table.+ pub fn find(&self, name: &[u8], storage: Storage) -> Option<u32> {+ let key = Key::of(name);+ self.lookup(key, hash_name(self.seed, key, name), name, storage).ok()+ }++ /// Returns the id of `name`, adding it to the table if it is new. `offset` is where `name` is in `storage`: an+ /// entry doesn't copy its bytes.+ pub fn intern(&mut self, name: &[u8], offset: u32, storage: Storage) -> u32 {+ let key = Key::of(name);+ let hash = hash_name(self.seed, key, name);+ match self.lookup(key, hash, name, storage) {+ Ok(id) => id,+ Err(slot) => self.insert(slot, key, hash, name.len() as u32, offset),+ }+ }++ /// `intern` for the name at `source[start..end]`, where `source` is the document itself.+ #[inline(always)]+ pub fn intern_in_source(&mut self, source: &[u8], start: usize, end: usize, arena: &[u8]) -> u32 {+ let name = &source[start..end];+ let key = Key::at(source, start, end - start);+ let hash = hash_name(self.seed, key, name);+ match self.lookup(key, hash, name, Storage { source, arena }) {+ Ok(id) => id,+ Err(slot) => self.insert(slot, key, hash, name.len() as u32, start as u32),+ }+ }++ #[inline(never)]+ fn insert(&mut self, slot: usize, key: Key, hash: u32, length: u32, offset: u32) -> u32 {+ let id = self.entries.len() as u32;+ self.entries.push(Name {+ key,+ hash,+ length,+ offset,+ prefix: NONE,+ local: id,+ binding: NONE,+ stamp: 0,+ flags: 0,+ });+ self.table[slot] = id + 1;+ if self.entries.len() * 2 > self.table.len() {+ self.grow();+ }+ id+ }++ fn grow(&mut self) {+ let size = self.table.len() * 2;+ let mask = size - 1;+ let mut table = vec![0u32; size];+ for (index, name) in self.entries.iter().enumerate() {+ let mut slot = name.hash as usize & mask;+ while table[slot] != 0 {+ slot = (slot + 1) & mask;+ }+ table[slot] = index as u32 + 1;+ }+ self.table = table;+ }++ /// Works out how the name `id` splits into a prefix and a local part, interning both, if that hasn't been done.+ /// Returns the name's flags.+ #[inline(always)]+ pub fn analyze(&mut self, id: u32, storage: Storage) -> u8 {+ let flags = self.entries[id as usize].flags;+ if flags & flag::ANALYZED != 0 {+ return flags;+ }+ self.analyze_slow(id, storage)+ }++ #[inline(never)]+ fn analyze_slow(&mut self, id: u32, storage: Storage) -> u8 {+ let entry = self.entries[id as usize];+ let bytes = storage.get(entry.offset, entry.length);+ let mut flags = entry.flags | flag::ANALYZED;+ if let Some(colon) = bytes.iter().position(|&byte| byte == b':') {+ let (prefix, local) = (&bytes[..colon], &bytes[colon + 1..]);+ if chars::is_name(prefix, false) && chars::is_name(local, false) {+ let prefix_id = self.intern(prefix, entry.offset, storage);+ let local_id = self.intern(local, entry.offset + colon as u32 + 1, storage);+ flags |= flag::HAS_PREFIX;+ if prefix == b"xmlns" {+ flags |= flag::PREFIX_XMLNS;+ } else if prefix == b"xml" {+ flags |= flag::PREFIX_XML;+ }+ let entry = &mut self.entries[id as usize];+ entry.prefix = prefix_id;+ entry.local = local_id;+ } else {+ flags |= flag::NOT_A_QNAME;+ }+ } else if bytes == b"xmlns" {+ flags |= flag::IS_XMLNS;+ }+ self.entries[id as usize].flags = flags;+ flags+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn keys() {+ let text = b"abcdefghijklmnopqrstuvwxyz0123456789";+ for start in 0..text.len() {+ for length in 0..=(text.len() - start).min(20) {+ let name = &text[start..start + length];+ // A key is the same wherever the name is read from, and however much input follows it.+ assert!(Key::at(text, start, length) == Key::of(name), "{start} {length}");+ assert!(Key::at(text, start, length) == Key::near_end(name), "{start} {length}");+ }+ }+ assert!(Key::of(b"abc") != Key::of(b"abd"));+ assert!(Key::of(b"abcdefghi") != Key::of(b"abcdefghj"));+ }++ #[test]+ fn interning() {+ let source = b"short a-name-longer-than-sixteen-bytes a-name-longer-than-sixteen-bytez short";+ let storage = Storage { source, arena: &[] };+ let mut names = Names::new();+ let short = names.intern(&source[0..5], 0, storage);+ let long = names.intern(&source[6..38], 6, storage);+ let other = names.intern(&source[39..71], 39, storage);+ assert_ne!(long, other);+ assert_eq!(names.intern_in_source(source, 72, 77, &[]), short);+ assert_eq!(names.find(b"a-name-longer-than-sixteen-bytes", storage), Some(long));+ assert_eq!(names.find(b"a-name-longer-than-sixteen-bytex", storage), None);+ assert!(names.is_at(long, source, 6, storage));+ assert!(!names.is_at(long, source, 39, storage));+ assert!(names.is_at(short, source, 72, storage));+ // Enough names to make the table grow several times.+ let mut arena = Vec::new();+ let mut ranges = Vec::new();+ for index in 0..1000u32 {+ let name = format!("name-number-{index}");+ ranges.push((arena.len(), name.len()));+ arena.extend_from_slice(name.as_bytes());+ }+ let storage = Storage { source, arena: &arena };+ let base = source.len();+ let ids: Vec<u32> = ranges+ .iter()+ .map(|&(start, length)| names.intern(&arena[start..start + length], (base + start) as u32, storage))+ .collect();+ for (&(start, length), &id) in ranges.iter().zip(&ids) {+ assert_eq!(names.find(&arena[start..start + length], storage), Some(id));+ }+ assert_eq!(names.find(b"short", storage), Some(short));+ }+}diff --git a/Libraries/LibXML/Rust/src/parser.rs b/Libraries/LibXML/Rust/src/parser.rsnew file mode 100644index 00000000000..15071d261f1--- /dev/null+++ b/Libraries/LibXML/Rust/src/parser.rs@@ -0,0 +1,1844 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A non-validating parser for XML 1.0 (fifth edition) with Namespaces in XML 1.0.+//!+//! It takes a whole document as UTF-8 and writes a `Tape`. External entities are never read. Where the specifications+//! leave a choice, it does what libxml2 does when driven the way a browser drives it.++use std::collections::HashSet;+use std::rc::Rc;++use crate::chars;+use crate::chars::CLASS;+use crate::dtd::Dtd;+use crate::dtd::EntityKind;+use crate::names::Names;+use crate::names::Storage;+use crate::names::flag;+use crate::scan;+use crate::scan::Controls;+use crate::tape::NONE;+use crate::tape::Tape;+use crate::tape::kind;++pub const XML_NAMESPACE: &[u8] = b"http://www.w3.org/XML/1998/namespace";+pub const XMLNS_NAMESPACE: &[u8] = b"http://www.w3.org/2000/xmlns/";++/// How deep elements can nest.+const MAX_ELEMENT_DEPTH: usize = 5000;+/// How deep entity references can nest.+pub(crate) const MAX_ENTITY_DEPTH: u32 = 20;+/// Entity expansion is free up to this many bytes. Past it, the expansions of a document together can't be more than+/// `MAX_AMPLIFICATION` times its size.+const ALLOWED_EXPANSION: u64 = 1_000_000;+const MAX_AMPLIFICATION: u64 = 5;+/// What every expansion costs on top of its length, so that a flood of references to an empty entity has a cost too.+const ENTITY_FIXED_COST: u64 = 20;++/// The arena starts with these, so that the text of a predefined entity or a normalized line end is a row like any+/// other, without a copy.+const ARENA_CONSTANTS: &[u8] = b"\n<>&'\"";+const CONSTANT_NEWLINE: u32 = 0;+const CONSTANT_LT: u32 = 1;+const CONSTANT_GT: u32 = 2;+const CONSTANT_AMP: u32 = 3;+const CONSTANT_APOS: u32 = 4;+const CONSTANT_QUOT: u32 = 5;++/// Resolves the name of an HTML character entity, appending its text as UTF-8 and returning true if there is one.+pub type HtmlEntityResolver<'a> = &'a dyn Fn(&[u8], &mut Vec<u8>) -> bool;++#[derive(Clone, Copy)]+pub struct Options<'a> {+ /// Whether comments get rows. They are checked either way.+ pub preserve_comments: bool,+ /// Whether a CDATA section gets a CDATA row, as opposed to a TEXT row.+ pub preserve_cdata: bool,+ /// Used for references to undeclared entities in a document whose doctype has one of the XHTML public ids.+ pub resolve_html_entity: Option<HtmlEntityResolver<'a>>,+}++impl Default for Options<'_> {+ fn default() -> Self {+ Options {+ preserve_comments: false,+ preserve_cdata: true,+ resolve_html_entity: None,+ }+ }+}++pub struct Error {+ /// Where in the source the error is. For an error inside an entity's text, where the reference to the entity is.+ pub offset: u32,+ pub line: u32,+ pub column: u32,+ /// The row the error comes before: everything ahead of it was parsed before the error was found.+ pub row: u32,+ /// A fatal error is the last thing in a document: the tape ends there. After any other error (the namespace+ /// constraints) the parser carries on.+ pub fatal: bool,+ pub message: String,+}++pub struct Document {+ pub tape: Tape,+ /// The second half of the address space string operands point into. See `Tape`.+ pub arena: Vec<u8>,+ pub names: Names,+ pub errors: Vec<Error>,+ /// Whether the document is XML 1.0, as opposed to a later 1.x.+ pub version_1_0: bool,+ /// Whether the parser got as far as the document itself: there is something in it, and its XML declaration, if+ /// it has one, is in order.+ pub started: bool,+}++impl Document {+ pub fn storage<'a>(&'a self, source: &'a [u8]) -> Storage<'a> {+ Storage {+ source,+ arena: &self.arena,+ }+ }+}++/// The bytes being parsed: the document, or the replacement text of an entity.+#[derive(Clone, Copy)]+pub(crate) struct In<'i> {+ pub bytes: &'i [u8],+ /// Whether `bytes` is the document. If it isn't, nothing on the tape can point into it.+ pub main: bool,+}++/// A fatal error was reported.+pub(crate) struct Stop;+pub(crate) type R<T> = Result<T, Stop>;++#[derive(Clone, Copy)]+struct Open {+ name: u32,+ /// How many namespace bindings the element's start tag added.+ bindings: u32,+ /// Where the start tag is, for the error message of a mismatched end tag.+ offset: u32,+}++#[derive(Clone, Copy)]+struct Binding {+ prefix: u32,+ namespace: u32,+ /// The binding this one shadows, or NONE.+ previous: u32,+ /// The depth of the element that declares it.+ depth: u32,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Delimited {+ Comment,+ ProcessingInstruction,+ CData,+}++pub(crate) struct Parser<'s, 'o> {+ pub(crate) src: &'s [u8],+ pub(crate) options: Options<'o>,+ pub(crate) tape: Tape,+ pub(crate) arena: Vec<u8>,+ pub(crate) names: Names,+ pub(crate) errors: Vec<Error>,+ stack: Vec<Open>,+ bindings: Vec<Binding>,+ default_namespace: u32,+ /// Counts start tags. See `Name::stamp`.+ stamp: u32,+ /// While a start tag is being parsed, its row.+ tag_row: u32,+ pub(crate) scratch: Vec<u8>,+ rows_scratch: Vec<(u8, u32, u32)>,+ prefixed_scratch: Vec<(u32, u32)>,+ pub(crate) dtd: Option<Box<Dtd>>,+ pub(crate) has_external_subset: bool,+ pub(crate) has_parameter_entity_references: bool,+ pub(crate) standalone: bool,+ pub(crate) is_xhtml: bool,+ version_1_0: bool,+ started: bool,+ pub(crate) entity_depth: u32,+ expanded: u64,+ /// While an entity's text is being parsed, where in the document the outermost reference is.+ pub(crate) entity_reference_offset: usize,+ arena_overflow: bool,+ xmlns_name: u32,+ xml_namespace: u32,+ xmlns_namespace: u32,+}++#[inline(always)]+pub(crate) fn at(bytes: &[u8], pos: usize) -> u8 {+ if pos < bytes.len() { bytes[pos] } else { 0 }+}++#[inline(always)]+pub(crate) fn skip_spaces(bytes: &[u8], mut pos: usize) -> usize {+ while pos < bytes.len() && chars::is_space(bytes[pos]) {+ pos += 1;+ }+ pos+}++/// Returns where the Name that starts at `start` ends, which is `start` if there is no Name there.+#[inline(always)]+pub(crate) fn scan_name(bytes: &[u8], start: usize) -> usize {+ if start >= bytes.len() {+ return start;+ }+ let mut pos = start;+ let first = bytes[pos];+ if first < 0x80 {+ if CLASS[first as usize] & chars::NAME_START == 0 {+ return start;+ }+ pos += 1;+ } else {+ match chars::decode_utf8(bytes, pos) {+ Some((c, length)) if chars::is_name_start_char(c) => pos += length,+ _ => return start,+ }+ }+ // What follows the first character of a Name is an Nmtoken.+ scan_nmtoken(bytes, pos)+}++/// Returns where the Nmtoken that starts at `start` ends.+#[inline(always)]+pub(crate) fn scan_nmtoken(bytes: &[u8], start: usize) -> usize {+ let mut pos = start;+ loop {+ pos = scan::ascii_name_end(bytes, pos);+ if pos < bytes.len()+ && bytes[pos] >= 0x80+ && let Some((c, length)) = chars::decode_utf8(bytes, pos)+ && chars::is_name_char(c)+ {+ pos += length;+ continue;+ }+ return pos;+ }+}++pub(crate) fn lossy(bytes: &[u8]) -> std::borrow::Cow<'_, str> {+ String::from_utf8_lossy(bytes)+}++fn predefined_entity(name: &[u8]) -> Option<u32> {+ match name {+ b"lt" => Some(CONSTANT_LT),+ b"gt" => Some(CONSTANT_GT),+ b"amp" => Some(CONSTANT_AMP),+ b"apos" => Some(CONSTANT_APOS),+ b"quot" => Some(CONSTANT_QUOT),+ _ => None,+ }+}++impl<'s, 'o> Parser<'s, 'o> {+ pub(crate) fn new(src: &'s [u8], options: Options<'o>) -> Self {+ let mut arena = Vec::with_capacity(256);+ arena.extend_from_slice(ARENA_CONSTANTS);+ let mut parser = Parser {+ src,+ options,+ // OPTIMIZATION: Markup-heavy documents come to about one row per ten bytes. Starting near that saves the+ // columns from being copied over and over as they grow.+ tape: Tape::with_capacity(src.len() / 8),+ arena,+ names: Names::new(),+ errors: Vec::new(),+ stack: Vec::with_capacity(32),+ bindings: Vec::with_capacity(8),+ default_namespace: NONE,+ stamp: 0,+ tag_row: NONE,+ scratch: Vec::new(),+ rows_scratch: Vec::new(),+ prefixed_scratch: Vec::new(),+ dtd: None,+ has_external_subset: false,+ has_parameter_entity_references: false,+ standalone: false,+ is_xhtml: false,+ version_1_0: true,+ started: false,+ entity_depth: 0,+ expanded: 0,+ entity_reference_offset: 0,+ arena_overflow: false,+ xmlns_name: 0,+ xml_namespace: 0,+ xmlns_namespace: 0,+ };+ parser.xmlns_name = parser.intern_copied(b"xmlns");+ parser.xml_namespace = parser.intern_copied(XML_NAMESPACE);+ parser.xmlns_namespace = parser.intern_copied(XMLNS_NAMESPACE);+ parser+ }++ pub(crate) fn finish(mut self) -> Document {+ // Line and column are only worked out here, so that the parser never has to count lines. A document can have+ // an error in every tag (the namespace constraints), so the lines are counted on from one error to the next+ // and not from the start for each. The errors are nearly in the order of their offsets, but not quite (one+ // found at the end of a start tag is reported at its start), so they are visited in that order.+ let mut by_offset: Vec<u32> = (0..self.errors.len() as u32).collect();+ by_offset.sort_by_key(|&index| self.errors[index as usize].offset);+ let mut counted_to = 0;+ let mut line = 1;+ let mut line_start = 0;+ for index in by_offset {+ let error = &mut self.errors[index as usize];+ let offset = (error.offset as usize).min(self.src.len());+ let between = &self.src[counted_to..offset];+ line += between.iter().filter(|&&byte| byte == b'\n').count() as u32;+ if let Some(index) = between.iter().rposition(|&byte| byte == b'\n') {+ line_start = counted_to + index + 1;+ }+ counted_to = offset;+ error.line = line;+ error.column = (offset - line_start) as u32 + 1;+ error.row = error.row.min(self.tape.len() as u32);+ }+ Document {+ tape: self.tape,+ arena: self.arena,+ names: self.names,+ errors: self.errors,+ version_1_0: self.version_1_0,+ started: self.started,+ }+ }++ // ------------------------------------------------------------------------------------------------------------+ // Errors+ // ------------------------------------------------------------------------------------------------------------++ fn report(&mut self, inp: In, pos: usize, fatal: bool, message: String) {+ let offset = if inp.main { pos } else { self.entity_reference_offset };+ let row = if self.tag_row != NONE {+ self.tag_row+ } else {+ self.tape.len() as u32+ };+ self.errors.push(Error {+ offset: offset as u32,+ line: 0,+ column: 0,+ row,+ fatal,+ message,+ });+ }++ #[cold]+ #[inline(never)]+ pub(crate) fn fail<T>(&mut self, inp: In, pos: usize, message: impl Into<String>) -> R<T> {+ self.report(inp, pos, true, message.into());+ Err(Stop)+ }++ /// Reports a broken namespace constraint. The document isn't namespace-well-formed, but parsing goes on.+ #[cold]+ #[inline(never)]+ pub(crate) fn namespace_error(&mut self, inp: In, pos: usize, message: String) {+ self.report(inp, pos, false, message);+ }++ // ------------------------------------------------------------------------------------------------------------+ // Strings+ // ------------------------------------------------------------------------------------------------------------++ #[inline(always)]+ pub(crate) fn storage(&self) -> Storage<'_> {+ Storage::new(self.src, &self.arena)+ }++ /// Appends `bytes` to the arena and returns the string operands for them.+ pub(crate) fn arena_push(&mut self, bytes: &[u8]) -> (u32, u32) {+ let offset = self.src.len() + self.arena.len();+ if offset + bytes.len() >= u32::MAX as usize {+ self.arena_overflow = true;+ return (self.src.len() as u32, 0);+ }+ self.arena.extend_from_slice(bytes);+ (offset as u32, bytes.len() as u32)+ }++ #[inline(always)]+ fn constant(&self, index: u32) -> u32 {+ self.src.len() as u32 + index+ }++ /// The string operands for `inp.bytes[start..end]`.+ #[inline(always)]+ pub(crate) fn string(&mut self, inp: In, start: usize, end: usize) -> (u32, u32) {+ if inp.main {+ (start as u32, (end - start) as u32)+ } else {+ self.arena_push(&inp.bytes[start..end])+ }+ }++ #[inline(always)]+ pub(crate) fn intern_name(&mut self, inp: In, start: usize, end: usize) -> u32 {+ if inp.main {+ self.names.intern_in_source(self.src, start, end, &self.arena)+ } else {+ self.intern_copied(&inp.bytes[start..end])+ }+ }++ /// Interns a name that isn't written anywhere in the document.+ pub(crate) fn intern_copied(&mut self, bytes: &[u8]) -> u32 {+ if let Some(id) = self.names.find(bytes, Storage::new(self.src, &self.arena)) {+ return id;+ }+ let (offset, _) = self.arena_push(bytes);+ self.names.intern(bytes, offset, Storage::new(self.src, &self.arena))+ }++ /// A name as an error message quotes it. A message can quote a name that isn't spelled out where the error is+ /// (that of the element an attribute is on), so a very long one is cut short, or the messages of a document+ /// could take far more memory than the document.+ pub(crate) fn name_string(&self, id: u32) -> String {+ const LONGEST_QUOTED_NAME: usize = 256;+ let bytes = self.names.bytes(id, self.storage());+ if bytes.len() <= LONGEST_QUOTED_NAME {+ return lossy(bytes).into_owned();+ }+ let mut end = LONGEST_QUOTED_NAME;+ while bytes[end] & 0xC0 == 0x80 {+ end -= 1;+ }+ format!("{}...", lossy(&bytes[..end]))+ }++ /// Checks the character that starts at `bytes[pos]`, a byte at or above 0x80, and returns its length.+ #[inline(always)]+ pub(crate) fn check_non_ascii(&mut self, inp: In, pos: usize) -> R<usize> {+ // OPTIMIZATION: Most text that isn't ASCII is in the two-byte range (Latin with diacritics, Greek, Cyrillic,+ // Hebrew, Arabic) or in the three-byte range below the surrogates (most of everything else). There a+ // sequence only has to have its continuation bytes to be a character XML allows.+ let bytes = inp.bytes;+ let lead = bytes[pos];+ if pos + 2 < bytes.len() {+ let second = bytes[pos + 1] & 0xC0 == 0x80;+ if (0xC2..0xE0).contains(&lead) && second {+ return Ok(2);+ }+ if (0xE1..0xED).contains(&lead) && second && bytes[pos + 2] & 0xC0 == 0x80 {+ return Ok(3);+ }+ }+ self.check_non_ascii_slow(inp, pos)+ }++ #[inline(never)]+ fn check_non_ascii_slow(&mut self, inp: In, pos: usize) -> R<usize> {+ match chars::decode_utf8(inp.bytes, pos) {+ Some((c, length)) if c < 0xFFFE => Ok(length),+ Some((c, length)) if chars::is_char(c) => Ok(length),+ Some((c, _)) => self.fail(inp, pos, format!("PCDATA invalid Char value {c}")),+ None => self.fail(inp, pos, "Input is not proper UTF-8, indicate encoding !"),+ }+ }++ // ------------------------------------------------------------------------------------------------------------+ // The document+ // ------------------------------------------------------------------------------------------------------------++ pub(crate) fn parse(&mut self) {+ if self.src.len() >= i32::MAX as usize {+ let _ = self.fail::<()>(+ In {+ bytes: self.src,+ main: true,+ },+ 0,+ "Document too large",+ );+ return;+ }+ let _ = self.document();+ if self.arena_overflow && !self.errors.iter().any(|error| error.fatal) {+ let _ = self.fail::<()>(+ In {+ bytes: self.src,+ main: true,+ },+ self.src.len(),+ "Document too large",+ );+ }+ }++ fn document(&mut self) -> R<()> {+ let inp = In {+ bytes: self.src,+ main: true,+ };+ let bytes = self.src;+ let mut pos = 0;+ if bytes.starts_with(b"\xEF\xBB\xBF") {+ pos = 3;+ }+ if pos >= bytes.len() {+ return self.fail(inp, pos, "Document is empty");+ }+ if bytes[pos..].starts_with(b"<?xml") && chars::is_space(at(bytes, pos + 5)) {+ pos = self.xml_declaration(inp, pos)?;+ }+ self.started = true;++ let mut seen_doctype = false;+ loop {+ pos = skip_spaces(bytes, pos);+ if at(bytes, pos) != b'<' {+ return self.fail(inp, pos, "Start tag expected, '<' not found");+ }+ match at(bytes, pos + 1) {+ b'?' => pos = self.processing_instruction(inp, pos, true)?,+ b'!' => {+ if bytes[pos..].starts_with(b"<!--") {+ pos = self.comment(inp, pos, true)?;+ } else if !seen_doctype && bytes[pos..].starts_with(b"<!DOCTYPE") {+ seen_doctype = true;+ pos = self.doctype(inp, pos)?;+ } else {+ return self.fail(inp, pos, "StartTag: invalid element name");+ }+ }+ _ => break,+ }+ }++ pos = self.start_tag(inp, pos)?;+ if !self.stack.is_empty() {+ pos = self.content(inp, pos, 0)?;+ }++ loop {+ pos = skip_spaces(bytes, pos);+ if pos >= bytes.len() {+ return Ok(());+ }+ if bytes[pos..].starts_with(b"<?") {+ pos = self.processing_instruction(inp, pos, true)?;+ } else if bytes[pos..].starts_with(b"<!--") {+ pos = self.comment(inp, pos, true)?;+ } else {+ return self.fail(inp, pos, "Extra content at the end of the document");+ }+ }+ }++ /// XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'+ fn xml_declaration(&mut self, inp: In, start: usize) -> R<usize> {+ let bytes = inp.bytes;+ let mut pos = skip_spaces(bytes, start + 5);++ if !bytes[pos..].starts_with(b"version") {+ return self.fail(inp, pos, "Malformed declaration expecting version");+ }+ let (value_start, value_end, next) = self.pseudo_attribute_value(inp, pos + 7)?;+ let version = &bytes[value_start..value_end];+ let is_version_number = version.len() >= 3+ && version[0].is_ascii_digit()+ && version[1] == b'.'+ && version[2..].iter().all(|byte| byte.is_ascii_digit());+ if !is_version_number || version[0] != b'1' {+ return self.fail(inp, value_start, format!("Unsupported version '{}'", lossy(version)));+ }+ self.version_1_0 = version == b"1.0";+ pos = next;++ let mut after_spaces = skip_spaces(bytes, pos);+ if bytes[after_spaces..].starts_with(b"encoding") {+ if after_spaces == pos {+ return self.fail(inp, pos, "Blank needed here");+ }+ let (value_start, value_end, next) = self.pseudo_attribute_value(inp, after_spaces + 8)?;+ // EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*+ // The name isn't used: the caller has decoded the document already.+ let name = &bytes[value_start..value_end];+ let is_encoding_name = name.first().is_some_and(|byte| byte.is_ascii_alphabetic())+ && name+ .iter()+ .all(|&byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));+ if !is_encoding_name {+ return self.fail(inp, value_start, "Invalid encoding name");+ }+ pos = next;+ after_spaces = skip_spaces(bytes, pos);+ }++ if bytes[after_spaces..].starts_with(b"standalone") {+ if after_spaces == pos {+ return self.fail(inp, pos, "Blank needed here");+ }+ let (value_start, value_end, next) = self.pseudo_attribute_value(inp, after_spaces + 10)?;+ match &bytes[value_start..value_end] {+ b"yes" => self.standalone = true,+ b"no" => self.standalone = false,+ _ => return self.fail(inp, value_start, "standalone accepts only 'yes' or 'no'"),+ }+ pos = next;+ after_spaces = skip_spaces(bytes, pos);+ }++ if !bytes[after_spaces..].starts_with(b"?>") {+ return self.fail(inp, after_spaces, "parsing XML declaration: '?>' expected");+ }+ Ok(after_spaces + 2)+ }++ /// Parses `S? '=' S? ('"' value '"' | "'" value "'")` and returns where the value starts and ends and where the+ /// closing quote ends.+ fn pseudo_attribute_value(&mut self, inp: In, pos: usize) -> R<(usize, usize, usize)> {+ let bytes = inp.bytes;+ let mut pos = skip_spaces(bytes, pos);+ if at(bytes, pos) != b'=' {+ return self.fail(inp, pos, "expected '='");+ }+ pos = skip_spaces(bytes, pos + 1);+ let quote = at(bytes, pos);+ if quote != b'"' && quote != b'\'' {+ return self.fail(inp, pos, "String not started expecting ' or \"");+ }+ let start = pos + 1;+ match bytes[start..].iter().position(|&byte| byte == quote) {+ Some(length) => Ok((start, start + length, start + length + 1)),+ None => self.fail(inp, pos, "String not closed expecting \" or '"),+ }+ }++ // ------------------------------------------------------------------------------------------------------------+ // Content+ // ------------------------------------------------------------------------------------------------------------++ /// content ::= CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*+ ///+ /// Parses content until the element stack is back down to `floor`. For the document that is the end tag of the+ /// root element. For an entity's text it has to be the end of the text: an entity can't close an element it+ /// didn't open, or leave one open.+ pub(crate) fn content(&mut self, inp: In, mut pos: usize, floor: usize) -> R<usize> {+ let bytes = inp.bytes;+ loop {+ let start = pos;+ let byte = loop {+ pos = scan::find(bytes, pos, b'<', b'&', b']', Controls::StopAtCr);+ if pos >= bytes.len() {+ break 0;+ }+ let byte = bytes[pos];+ if byte == b']' {+ if at(bytes, pos + 1) == b']' && at(bytes, pos + 2) == b'>' {+ self.text(inp, start, pos);+ return self.fail(inp, pos, "Sequence ']]>' not allowed in content");+ }+ pos += 1;+ continue;+ }+ if byte >= 0x80 {+ // OPTIMIZATION: Text in a script that isn't Latin is one such character after another, so stay+ // here for the whole run of them.+ while pos < bytes.len() && bytes[pos] >= 0x80 {+ match self.check_non_ascii(inp, pos) {+ Ok(length) => pos += length,+ Err(stop) => {+ // The text that leads up to the bad character is still text of the document.+ self.text(inp, start, pos);+ if let Some(error) = self.errors.last_mut() {+ error.row = self.tape.len() as u32;+ }+ return Err(stop);+ }+ }+ }+ continue;+ }+ break byte;+ };+ self.text(inp, start, pos);++ match byte {+ b'<' => match at(bytes, pos + 1) {+ b'/' => {+ pos = self.end_tag(inp, pos, floor)?;+ if inp.main && self.stack.len() == floor {+ return Ok(pos);+ }+ }+ b'!' => {+ if bytes[pos..].starts_with(b"<!--") {+ pos = self.comment(inp, pos, true)?;+ } else if bytes[pos..].starts_with(b"<![CDATA[") {+ pos = self.cdata_section(inp, pos)?;+ } else {+ return self.fail(inp, pos, "StartTag: invalid element name");+ }+ }+ b'?' => pos = self.processing_instruction(inp, pos, true)?,+ _ => pos = self.start_tag(inp, pos)?,+ },+ b'&' => pos = self.reference(inp, pos)?,+ b'\r' => {+ // A line end is a single LF, however it was written.+ if at(bytes, pos + 1) != b'\n' {+ let newline = self.constant(CONSTANT_NEWLINE);+ self.tape.push(kind::TEXT, newline, 1);+ }+ pos += 1;+ }+ _ => {+ if pos < bytes.len() {+ return self.fail(inp, pos, format!("PCDATA invalid Char value {byte}"));+ }+ if self.stack.len() > floor {+ let open = self.stack[self.stack.len() - 1];+ let message = format!(+ "Premature end of data in tag {} line {}",+ self.name_string(open.name),+ self.line_of(open.offset as usize)+ );+ return self.fail(inp, pos, message);+ }+ return Ok(pos);+ }+ }+ }+ }++ #[inline(always)]+ fn text(&mut self, inp: In, start: usize, end: usize) {+ if end > start {+ let (offset, length) = self.string(inp, start, end);+ self.tape.push(kind::TEXT, offset, length);+ }+ }++ fn line_of(&self, offset: usize) -> usize {+ self.src[..offset.min(self.src.len())]+ .iter()+ .filter(|&&byte| byte == b'\n')+ .count()+ + 1+ }++ // ------------------------------------------------------------------------------------------------------------+ // Tags+ // ------------------------------------------------------------------------------------------------------------++ /// STag ::= '<' QName (S Attribute)* S? '>'+ /// EmptyElemTag ::= '<' QName (S Attribute)* S? '/>'+ fn start_tag(&mut self, inp: In, pos: usize) -> R<usize> {+ let row = self.tape.len();+ self.tag_row = row as u32;+ let result = self.start_tag_inner(inp, pos, row);+ self.tag_row = NONE;+ if result.is_err() {+ self.tape.truncate(row);+ }+ result+ }++ #[inline(always)]+ fn start_tag_inner(&mut self, inp: In, start: usize, row: usize) -> R<usize> {+ let bytes = inp.bytes;+ let name_start = start + 1;+ let name_end = scan_name(bytes, name_start);+ if name_end == name_start {+ return self.fail(inp, start, "StartTag: invalid element name");+ }+ let name = self.intern_name(inp, name_start, name_end);+ let element_flags = self.names.analyze(name, Storage::new(self.src, &self.arena));+ self.tape.push(kind::START, name, NONE);+ self.stamp += 1;+ let stamp = self.stamp;+ let has_tokenized = element_flags & flag::HAS_TOKENIZED != 0;++ let mut flags = element_flags;+ let mut pos = name_end;+ let mut first = true;+ let empty;+ loop {+ let after_spaces = skip_spaces(bytes, pos);+ let byte = at(bytes, after_spaces);+ if byte == b'>' {+ pos = after_spaces + 1;+ empty = false;+ break;+ }+ if byte == b'/' && at(bytes, after_spaces + 1) == b'>' {+ pos = after_spaces + 2;+ empty = true;+ break;+ }+ if after_spaces >= bytes.len() {+ let message = format!("Couldn't find end of Start Tag {}", self.name_string(name));+ return self.fail(inp, after_spaces, message);+ }+ if after_spaces == pos && !first {+ return self.fail(inp, pos, "attributes construct error");+ }++ let attribute_end = scan_name(bytes, after_spaces);+ if attribute_end == after_spaces {+ return self.fail(inp, after_spaces, "error parsing attribute name");+ }+ let attribute = self.intern_name(inp, after_spaces, attribute_end);+ let attribute_flags = self.names.analyze(attribute, Storage::new(self.src, &self.arena));+ let entry = self.names.get_mut(attribute);+ if entry.stamp == stamp {+ let message = format!("Attribute {} redefined", self.name_string(attribute));+ return self.fail(inp, after_spaces, message);+ }+ entry.stamp = stamp;+ flags |= attribute_flags & !flag::ELEMENT_ONLY;++ let mut value_start = skip_spaces(bytes, attribute_end);+ if at(bytes, value_start) != b'=' {+ let message = format!(+ "Specification mandates value for attribute {}",+ self.name_string(attribute)+ );+ return self.fail(inp, value_start, message);+ }+ value_start = skip_spaces(bytes, value_start + 1);+ let quote = at(bytes, value_start);+ if quote != b'"' && quote != b'\'' {+ return self.fail(inp, value_start, "AttValue: \" or ' expected");+ }+ let collapse = has_tokenized && self.attribute_is_tokenized(name, attribute);+ let (offset, length, next) = self.attribute_value(inp, value_start, collapse)?;+ self.tape.push(kind::ATTR, attribute, NONE);+ self.tape.push(kind::VALUE, offset, length);+ pos = next;+ first = false;+ }++ // OPTIMIZATION: Most tags declare no namespace and have no prefix anywhere, and then all there is to do is+ // give the element the default namespace.+ let bindings = if flags & flag::NEEDS_NAMESPACE_PROCESSING != 0 {+ self.process_namespaces(inp, start, row, name, element_flags, flags)?+ } else {+ self.tape.set_b(row, self.default_namespace);+ 0+ };++ if self.stack.len() >= MAX_ELEMENT_DEPTH {+ return self.fail(inp, start, "Excessive node nesting.");+ }+ if empty {+ self.tape.push(kind::END, name, NONE);+ self.pop_bindings(bindings);+ } else {+ self.stack.push(Open {+ name,+ bindings,+ offset: start.min(u32::MAX as usize) as u32,+ });+ }+ Ok(pos)+ }++ /// ETag ::= '</' QName S? '>'+ #[inline(always)]+ fn end_tag(&mut self, inp: In, start: usize, floor: usize) -> R<usize> {+ let bytes = inp.bytes;+ if self.stack.len() <= floor {+ return self.fail(inp, start, "chunk is not well balanced");+ }+ let open = self.stack[self.stack.len() - 1];+ // OPTIMIZATION: The name in an end tag has to be the name of the open element, so it isn't scanned, hashed+ // and looked up. It is compared to the bytes it has to be.+ let name_start = start + 2;+ if !self+ .names+ .is_at(open.name, bytes, name_start, Storage::new(self.src, &self.arena))+ {+ return self.end_tag_mismatch(inp, start, open);+ }+ let mut pos = name_start + self.names.get(open.name).length as usize;+ let byte = at(bytes, pos);+ if byte != b'>' {+ if !chars::is_space(byte) {+ return self.end_tag_mismatch(inp, start, open);+ }+ pos = skip_spaces(bytes, pos);+ if at(bytes, pos) != b'>' {+ return self.fail(inp, pos, "expected '>'");+ }+ }+ self.tape.push(kind::END, open.name, NONE);+ self.stack.pop();+ if open.bindings != 0 {+ self.pop_bindings(open.bindings);+ }+ Ok(pos + 1)+ }++ #[cold]+ #[inline(never)]+ fn end_tag_mismatch(&mut self, inp: In, start: usize, open: Open) -> R<usize> {+ let found_end = scan_nmtoken(inp.bytes, start + 2);+ let message = format!(+ "Opening and ending tag mismatch: {} line {} and {}",+ self.name_string(open.name),+ self.line_of(open.offset as usize),+ lossy(&inp.bytes[start + 2..found_end])+ );+ self.fail(inp, start, message)+ }++ // ------------------------------------------------------------------------------------------------------------+ // Attribute values+ // ------------------------------------------------------------------------------------------------------------++ /// AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"+ ///+ /// `pos` is at the opening quote. Returns the string operands of the normalized value and where the closing+ /// quote ends. `collapse` is set for an attribute the DTD declares with a type other than CDATA: such a value+ /// also has its leading and trailing spaces removed and its runs of spaces made single spaces.+ #[inline(always)]+ pub(crate) fn attribute_value(&mut self, inp: In, pos: usize, collapse: bool) -> R<(u32, u32, usize)> {+ let bytes = inp.bytes;+ let quote = bytes[pos];+ let start = pos + 1;+ let end = scan::find(bytes, start, quote, b'&', b'<', Controls::StopAtAll);+ // OPTIMIZATION: A value with no reference, no white space other than spaces and nothing but ASCII is its own+ // normalized form, and that is nearly every value. It stays where it is in the source.+ if end < bytes.len() && bytes[end] == quote && !collapse {+ let (offset, length) = self.string(inp, start, end);+ return Ok((offset, length, end + 1));+ }+ self.attribute_value_slow(inp, start, end, quote, collapse)+ }++ #[inline(never)]+ fn attribute_value_slow(+ &mut self,+ inp: In,+ start: usize,+ mut pos: usize,+ quote: u8,+ collapse: bool,+ ) -> R<(u32, u32, usize)> {+ let bytes = inp.bytes;+ let mut buffer = std::mem::take(&mut self.scratch);+ buffer.clear();+ let mut run = start;+ loop {+ buffer.extend_from_slice(&bytes[run..pos]);+ if pos >= bytes.len() {+ return self.fail(inp, pos, "AttValue: ' expected");+ }+ let byte = bytes[pos];+ if byte == quote {+ break;+ }+ match byte {+ b'&' => pos = self.attribute_reference(inp, pos, &mut buffer)?,+ b'<' => return self.fail(inp, pos, "Unescaped '<' not allowed in attributes values"),+ b'\t' | b'\n' => {+ buffer.push(b' ');+ pos += 1;+ }+ b'\r' => {+ buffer.push(b' ');+ pos += 1;+ if at(bytes, pos) == b'\n' {+ pos += 1;+ }+ }+ _ if byte >= 0x80 => {+ let length = self.check_non_ascii(inp, pos)?;+ buffer.extend_from_slice(&bytes[pos..pos + length]);+ pos += length;+ }+ _ => return self.fail(inp, pos, format!("invalid character in attribute value: {byte}")),+ }+ run = pos;+ pos = scan::find(bytes, pos, quote, b'&', b'<', Controls::StopAtAll);+ }+ if collapse {+ collapse_spaces(&mut buffer);+ }+ let (offset, length) = self.arena_push(&buffer);+ self.scratch = buffer;+ Ok((offset, length, pos + 1))+ }++ /// Handles the reference at `bytes[pos]` in an attribute value, appending what it stands for to `buffer`.+ fn attribute_reference(&mut self, inp: In, pos: usize, buffer: &mut Vec<u8>) -> R<usize> {+ let bytes = inp.bytes;+ if at(bytes, pos + 1) == b'#' {+ let (c, next) = self.character_reference(inp, pos)?;+ chars::encode_utf8(c, buffer);+ return Ok(next);+ }+ let (name_start, name_end) = self.entity_reference_name(inp, pos)?;+ let name = &bytes[name_start..name_end];+ let next = name_end + 1;+ if let Some(constant) = predefined_entity(name) {+ buffer.push(ARENA_CONSTANTS[constant as usize]);+ return Ok(next);+ }+ self.expand_entity_in_attribute(inp, pos, name, buffer)?;+ Ok(next)+ }++ fn expand_entity_in_attribute(&mut self, inp: In, pos: usize, name: &[u8], buffer: &mut Vec<u8>) -> R<()> {+ let Some((id, kind, text)) = self.find_general_entity(name) else {+ return self.undeclared_entity(inp, pos, name, Some(buffer));+ };+ match kind {+ EntityKind::Internal => {}+ EntityKind::External => {+ let message = format!("Attribute references external entity '{}'", lossy(name));+ return self.fail(inp, pos, message);+ }+ EntityKind::Unparsed => {+ let message = format!("Entity reference to unparsed entity {}", lossy(name));+ return self.fail(inp, pos, message);+ }+ }+ self.enter_entity(inp, pos, id, text.len())?;+ let saved_offset = self.entity_reference_offset;+ if inp.main {+ self.entity_reference_offset = pos;+ }+ let result = self.entity_text_in_attribute(&text, name, buffer);+ self.entity_reference_offset = saved_offset;+ self.leave_entity(id);+ result+ }++ /// Appends the replacement text of an entity to an attribute value: white space becomes spaces, references are+ /// followed, and a '<' that isn't from a character reference is an error.+ fn entity_text_in_attribute(&mut self, text: &[u8], entity_name: &[u8], buffer: &mut Vec<u8>) -> R<()> {+ let inp = In {+ bytes: text,+ main: false,+ };+ let mut pos = 0;+ while pos < text.len() {+ let byte = text[pos];+ match byte {+ b'&' => pos = self.attribute_reference(inp, pos, buffer)?,+ b'<' => {+ let message = format!(+ "'<' in entity '{}' is not allowed in attributes values",+ lossy(entity_name)+ );+ return self.fail(inp, pos, message);+ }+ b'\t' | b'\n' | b'\r' | b' ' => {+ buffer.push(b' ');+ pos += 1;+ }+ _ => {+ buffer.push(byte);+ pos += 1;+ }+ }+ }+ Ok(())+ }++ // ------------------------------------------------------------------------------------------------------------+ // References+ // ------------------------------------------------------------------------------------------------------------++ /// CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'+ pub(crate) fn character_reference(&mut self, inp: In, start: usize) -> R<(u32, usize)> {+ let bytes = inp.bytes;+ let mut pos = start + 2;+ let mut value: u32 = 0;+ let digits_start;+ if at(bytes, pos) == b'x' {+ pos += 1;+ digits_start = pos;+ while pos < bytes.len() && CLASS[bytes[pos] as usize] & chars::HEX != 0 {+ let digit = (bytes[pos] as char).to_digit(16).unwrap_or(0);+ value = (value * 16 + digit).min(0x110000);+ pos += 1;+ }+ if pos == digits_start || at(bytes, pos) != b';' {+ return self.fail(inp, start, "xmlParseCharRef: invalid hexadecimal value");+ }+ } else {+ digits_start = pos;+ while pos < bytes.len() && bytes[pos].is_ascii_digit() {+ value = (value * 10 + (bytes[pos] - b'0') as u32).min(0x110000);+ pos += 1;+ }+ if pos == digits_start || at(bytes, pos) != b';' {+ return self.fail(inp, start, "xmlParseCharRef: invalid decimal value");+ }+ }+ if !chars::is_char(value) {+ return self.fail(inp, start, format!("xmlParseCharRef: invalid xmlChar value {value}"));+ }+ Ok((value, pos + 1))+ }++ /// EntityRef ::= '&' Name ';'+ ///+ /// Returns where the name starts and ends.+ pub(crate) fn entity_reference_name(&mut self, inp: In, start: usize) -> R<(usize, usize)> {+ let name_start = start + 1;+ let name_end = scan_name(inp.bytes, name_start);+ if name_end == name_start {+ return self.fail(inp, start, "xmlParseEntityRef: no name");+ }+ if at(inp.bytes, name_end) != b';' {+ return self.fail(inp, name_end, "EntityRef: expecting ';'");+ }+ Ok((name_start, name_end))+ }++ fn find_general_entity(&self, name: &[u8]) -> Option<(u32, EntityKind, Rc<[u8]>)> {+ let dtd = self.dtd.as_ref()?;+ let id = self.names.find(name, self.storage())?;+ let entity = dtd.general.get(&id)?;+ Some((id, entity.kind, entity.text.clone()))+ }++ /// Checks that expanding the entity `id` here is allowed, and marks it as being expanded.+ fn enter_entity(&mut self, inp: In, pos: usize, id: u32, length: usize) -> R<()> {+ let expanding = self+ .dtd+ .as_ref()+ .and_then(|dtd| dtd.general.get(&id))+ .is_some_and(|entity| entity.expanding);+ if expanding {+ return self.fail(inp, pos, "Detected an entity reference loop");+ }+ if self.entity_depth >= MAX_ENTITY_DEPTH {+ return self.fail(inp, pos, "Maximum entity nesting depth exceeded");+ }+ self.account_for_expansion(inp, pos, length)?;+ if let Some(entity) = self.dtd.as_mut().and_then(|dtd| dtd.general.get_mut(&id)) {+ entity.expanding = true;+ }+ self.entity_depth += 1;+ Ok(())+ }++ fn leave_entity(&mut self, id: u32) {+ self.entity_depth -= 1;+ if let Some(entity) = self.dtd.as_mut().and_then(|dtd| dtd.general.get_mut(&id)) {+ entity.expanding = false;+ }+ }++ pub(crate) fn account_for_expansion(&mut self, inp: In, pos: usize, length: usize) -> R<()> {+ self.expanded = self+ .expanded+ .saturating_add(length as u64)+ .saturating_add(ENTITY_FIXED_COST);+ if self.expanded > ALLOWED_EXPANSION && self.expanded / MAX_AMPLIFICATION > self.src.len() as u64 {+ return self.fail(inp, pos, "Maximum entity amplification factor exceeded");+ }+ Ok(())+ }++ /// Handles a reference to an entity that has no declaration. With `buffer` the reference is in an attribute+ /// value, without it in content.+ fn undeclared_entity(&mut self, inp: In, pos: usize, name: &[u8], buffer: Option<&mut Vec<u8>>) -> R<()> {+ if self.is_xhtml+ && let Some(resolve) = self.options.resolve_html_entity+ {+ let mut text = Vec::new();+ if resolve(name, &mut text) {+ match buffer {+ Some(buffer) => buffer.extend_from_slice(&text),+ None => {+ let (offset, length) = self.arena_push(&text);+ self.tape.push(kind::TEXT, offset, length);+ }+ }+ return Ok(());+ }+ }+ let message = format!("Entity '{}' not defined", lossy(name));+ if self.standalone || !(self.has_external_subset || self.has_parameter_entity_references) {+ return self.fail(inp, pos, message);+ }+ // A document that points at declarations this parser doesn't read may well declare the entity there, so the+ // document is still well-formed and parsing goes on, with the reference standing for nothing. But nothing is+ // known of what it should stand for, so the document can't be shown as its author meant it, and whoever+ // asked for it is told.+ self.report(inp, pos, false, message);+ Ok(())+ }++ /// Reference ::= EntityRef | CharRef+ #[inline(never)]+ fn reference(&mut self, inp: In, pos: usize) -> R<usize> {+ let bytes = inp.bytes;+ if at(bytes, pos + 1) == b'#' {+ let (c, next) = self.character_reference(inp, pos)?;+ let mut encoded = [0u8; 4];+ let encoded = char::from_u32(c).unwrap_or('\u{FFFD}').encode_utf8(&mut encoded);+ let (offset, length) = self.arena_push(encoded.as_bytes());+ self.tape.push(kind::TEXT, offset, length);+ return Ok(next);+ }+ let (name_start, name_end) = self.entity_reference_name(inp, pos)?;+ let name = &bytes[name_start..name_end];+ let next = name_end + 1;+ if let Some(constant) = predefined_entity(name) {+ let offset = self.constant(constant);+ self.tape.push(kind::TEXT, offset, 1);+ return Ok(next);+ }++ let Some((id, kind, text)) = self.find_general_entity(name) else {+ self.undeclared_entity(inp, pos, name, None)?;+ return Ok(next);+ };+ match kind {+ EntityKind::Internal => {}+ // External entities aren't read. The reference stands for nothing.+ EntityKind::External => return Ok(next),+ EntityKind::Unparsed => {+ let message = format!("Entity reference to unparsed entity {}", lossy(name));+ return self.fail(inp, pos, message);+ }+ }++ self.enter_entity(inp, pos, id, text.len())?;+ let saved_offset = self.entity_reference_offset;+ if inp.main {+ self.entity_reference_offset = pos;+ }+ let floor = self.stack.len();+ let result = self.content(+ In {+ bytes: &text,+ main: false,+ },+ 0,+ floor,+ );+ self.entity_reference_offset = saved_offset;+ self.leave_entity(id);+ result?;+ if self.arena_overflow {+ return self.fail(inp, pos, "Document too large");+ }+ Ok(next)+ }++ // ------------------------------------------------------------------------------------------------------------+ // Comments, processing instructions, CDATA sections+ // ------------------------------------------------------------------------------------------------------------++ /// Scans from `start` to the terminator of a comment, a processing instruction or a CDATA section, checking the+ /// characters on the way. Returns the string operands of what is before the terminator and where the terminator+ /// starts.+ fn delimited(&mut self, inp: In, start: usize, what: Delimited) -> R<(u32, u32, usize)> {+ let bytes = inp.bytes;+ let delimiter = match what {+ Delimited::Comment => b'-',+ Delimited::ProcessingInstruction => b'?',+ Delimited::CData => b']',+ };+ let mut pos = start;+ let mut run = start;+ // A CR has to be normalized, which the source can't be edited to do. The text is only copied once there is+ // one.+ let mut buffer = std::mem::take(&mut self.scratch);+ buffer.clear();+ let mut copied = false;+ loop {+ pos = scan::find(bytes, pos, delimiter, delimiter, delimiter, Controls::StopAtCr);+ if pos >= bytes.len() {+ let message = match what {+ Delimited::Comment => "Comment not terminated",+ Delimited::ProcessingInstruction => "PI not finished",+ Delimited::CData => "CData section not finished",+ };+ return self.fail(inp, start, message);+ }+ let byte = bytes[pos];+ if byte == delimiter {+ match what {+ Delimited::Comment => {+ if at(bytes, pos + 1) == b'-' {+ if at(bytes, pos + 2) == b'>' {+ break;+ }+ return self.fail(inp, pos, "Double hyphen within comment");+ }+ }+ Delimited::ProcessingInstruction => {+ if at(bytes, pos + 1) == b'>' {+ break;+ }+ }+ Delimited::CData => {+ if at(bytes, pos + 1) == b']' && at(bytes, pos + 2) == b'>' {+ break;+ }+ }+ }+ pos += 1;+ } else if byte == b'\r' {+ buffer.extend_from_slice(&bytes[run..pos]);+ buffer.push(b'\n');+ copied = true;+ pos += 1;+ if at(bytes, pos) == b'\n' {+ pos += 1;+ }+ run = pos;+ } else if byte >= 0x80 {+ while pos < bytes.len() && bytes[pos] >= 0x80 {+ pos += self.check_non_ascii(inp, pos)?;+ }+ } else {+ return self.fail(inp, pos, format!("PCDATA invalid Char value {byte}"));+ }+ }+ let (offset, length) = if copied {+ buffer.extend_from_slice(&bytes[run..pos]);+ self.arena_push(&buffer)+ } else {+ self.string(inp, start, pos)+ };+ self.scratch = buffer;+ Ok((offset, length, pos))+ }++ /// Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'+ pub(crate) fn comment(&mut self, inp: In, start: usize, in_content: bool) -> R<usize> {+ let (offset, length, end) = self.delimited(inp, start + 4, Delimited::Comment)?;+ if in_content && self.options.preserve_comments {+ self.tape.push(kind::COMMENT, offset, length);+ }+ Ok(end + 3)+ }++ /// CDSect ::= '<![CDATA[' (Char* - (Char* ']]>' Char*)) ']]>'+ fn cdata_section(&mut self, inp: In, start: usize) -> R<usize> {+ let (offset, length, end) = self.delimited(inp, start + 9, Delimited::CData)?;+ let row_kind = if self.options.preserve_cdata {+ kind::CDATA+ } else {+ kind::TEXT+ };+ self.tape.push(row_kind, offset, length);+ Ok(end + 3)+ }++ /// PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'+ ///+ /// A processing instruction in the DTD is checked but gets no row: it isn't part of the document's content.+ pub(crate) fn processing_instruction(&mut self, inp: In, start: usize, in_content: bool) -> R<usize> {+ let bytes = inp.bytes;+ let target_start = start + 2;+ let target_end = scan_name(bytes, target_start);+ if target_end == target_start {+ return self.fail(inp, start, "xmlParsePI : no target name");+ }+ let target = &bytes[target_start..target_end];+ if target == b"xml" {+ return self.fail(inp, start, "XML declaration allowed only at the start of the document");+ }+ if target.eq_ignore_ascii_case(b"xml") {+ return self.fail(inp, start, "XML reserved name");+ }+ if target.contains(&b':') {+ let message = format!("colons are forbidden from PI names '{}'", lossy(target));+ self.namespace_error(inp, start, message);+ }++ let (offset, length, end);+ if at(bytes, target_end) == b'?' && at(bytes, target_end + 1) == b'>' {+ (offset, length) = (self.src.len() as u32, 0);+ end = target_end;+ } else {+ if !chars::is_space(at(bytes, target_end)) {+ let message = format!("ParsePI: PI {} space expected", lossy(target));+ return self.fail(inp, target_end, message);+ }+ let data_start = skip_spaces(bytes, target_end);+ (offset, length, end) = self.delimited(inp, data_start, Delimited::ProcessingInstruction)?;+ }+ if in_content {+ let name = self.intern_name(inp, target_start, target_end);+ self.tape.push(kind::PI, name, NONE);+ self.tape.push(kind::VALUE, offset, length);+ }+ Ok(end + 2)+ }++ // ------------------------------------------------------------------------------------------------------------+ // Namespaces+ // ------------------------------------------------------------------------------------------------------------++ fn push_binding(&mut self, prefix: u32, namespace: u32, depth: u32) -> bool {+ let previous = self.names.get(prefix).binding;+ if previous != NONE && self.bindings[previous as usize].depth == depth {+ return false;+ }+ self.names.get_mut(prefix).binding = self.bindings.len() as u32;+ self.bindings.push(Binding {+ prefix,+ namespace,+ previous,+ depth,+ });+ if prefix == self.xmlns_name {+ self.default_namespace = namespace;+ }+ true+ }++ fn pop_bindings(&mut self, count: u32) {+ for _ in 0..count {+ let Some(binding) = self.bindings.pop() else {+ return;+ };+ self.names.get_mut(binding.prefix).binding = binding.previous;+ if binding.prefix == self.xmlns_name {+ self.default_namespace = if binding.previous == NONE {+ NONE+ } else {+ self.bindings[binding.previous as usize].namespace+ };+ }+ }+ }++ /// The namespace `prefix` is bound to, or None.+ fn namespace_of_prefix(&self, prefix: u32) -> Option<u32> {+ let binding = self.names.get(prefix).binding;+ if binding == NONE {+ None+ } else {+ Some(self.bindings[binding as usize].namespace)+ }+ }++ fn attribute_is_tokenized(&self, element: u32, attribute: u32) -> bool {+ self.dtd+ .as_ref()+ .is_some_and(|dtd| dtd.defined_attributes.get(&(element, attribute)) == Some(&true))+ }++ /// Does everything about a start tag that has to do with namespaces, and with the attributes the DTD gives the+ /// element by default: adds the tag's namespace declarations to the bindings in scope, appends the defaulted+ /// attributes, resolves the prefixes of the element and its attributes, and moves the declarations ahead of the+ /// other attributes. Returns how many bindings were added.+ #[inline(never)]+ fn process_namespaces(+ &mut self,+ inp: In,+ pos: usize,+ row: usize,+ element: u32,+ element_flags: u8,+ tag_flags: u8,+ ) -> R<u32> {+ let depth = self.stack.len() as u32 + 1;+ let stamp = self.stamp;+ let mut bindings = 0;+ let mut reorder = false;+ // Without a declaration in the tag, the attributes in it are all plain ones.+ let mut seen_plain_attribute =+ tag_flags & (flag::IS_XMLNS | flag::PREFIX_XMLNS) == 0 && self.tape.len() > row + 1;++ // The declarations in the tag.+ // OPTIMIZATION: A tag is far more often here for a prefix it uses than for one it declares.+ let mut index = row + 1;+ let explicit_end = if tag_flags & (flag::IS_XMLNS | flag::PREFIX_XMLNS) != 0 {+ self.tape.len()+ } else {+ 0+ };+ while index < explicit_end {+ let (_, attribute, _) = self.tape.row(index);+ let attribute_flags = self.names.get(attribute).flags;+ if attribute_flags & (flag::IS_XMLNS | flag::PREFIX_XMLNS) != 0 {+ let (_, offset, length) = self.tape.row(index + 1);+ let prefix = if attribute_flags & flag::IS_XMLNS != 0 {+ None+ } else {+ Some(self.names.get(attribute).local)+ };+ let value = Storage::new(self.src, &self.arena).get(offset, length);+ let redeclares_xml = value == XML_NAMESPACE+ && prefix+ .is_some_and(|prefix| self.names.bytes(prefix, Storage::new(self.src, &self.arena)) == b"xml");+ if redeclares_xml {+ // The xml prefix is bound from the start, so declaring it as what it already is binds nothing, but+ // the declaration is an attribute of the element like any other.+ self.tape.set_row(+ index,+ kind::ATTR | kind::NAMESPACE_DECLARATION,+ attribute,+ self.xmlns_namespace,+ );+ reorder |= seen_plain_attribute;+ } else if self.declare_namespace(inp, pos, prefix, offset, length, depth) {+ self.tape.set_row(+ index,+ kind::ATTR | kind::NAMESPACE_DECLARATION,+ attribute,+ self.xmlns_namespace,+ );+ bindings += 1;+ reorder |= seen_plain_attribute;+ } else {+ // A declaration that breaks a rule declares nothing and isn't an attribute either.+ self.tape.set_kind(index, 0);+ reorder = true;+ }+ } else {+ seen_plain_attribute = true;+ }+ index += 2;+ }++ // The attributes the DTD defaults.+ if element_flags & flag::HAS_DEFAULTS != 0 {+ let definitions = self.dtd.as_ref().and_then(|dtd| dtd.attlists.get(&element)).cloned();+ for definition in definitions.iter().flat_map(|definitions| definitions.iter()) {+ let (offset, length) = definition.default;+ let entry = self.names.get_mut(definition.name);+ if entry.stamp == stamp {+ continue;+ }+ entry.stamp = stamp;+ // A default is a name and a value the document didn't spell out here, as an entity's replacement+ // text is. A few lines of declarations can give every element thousands of attributes, so both draw+ // on the same budget.+ let name_length = self+ .names+ .bytes(definition.name, Storage::new(self.src, &self.arena))+ .len();+ self.account_for_expansion(inp, pos, name_length + length as usize)?;+ let attribute_flags = self.names.analyze(definition.name, Storage::new(self.src, &self.arena));+ let name = self.names.bytes(definition.name, Storage::new(self.src, &self.arena));++ // The name in an attribute-list declaration is a Name, not a QName, so it is split at its first+ // colon whatever comes after, and "xmlns:" followed by anything declares a prefix.+ let declared_prefix: Option<Option<&[u8]>> = if name == b"xmlns" {+ Some(None)+ } else if name.len() > 6 && name.starts_with(b"xmlns:") {+ Some(Some(&name[6..]))+ } else {+ None+ };+ if let Some(prefix) = declared_prefix {+ let value = Storage::new(self.src, &self.arena).get(offset, length);+ if prefix == Some(b"xml") {+ // As in a start tag: declaring the xml prefix as what it already is binds nothing and is an+ // attribute all the same.+ if value == XML_NAMESPACE {+ reorder |= seen_plain_attribute;+ self.tape.push(+ kind::ATTR | kind::NAMESPACE_DECLARATION | kind::DEFAULTED,+ definition.name,+ self.xmlns_namespace,+ );+ self.tape.push(kind::VALUE, offset, length);+ } else {+ self.namespace_error(inp, pos, "xml namespace prefix mapped to wrong URI".into());+ }+ continue;+ }+ if let Some(prefix) = prefix+ && !chars::is_name(prefix, false)+ {+ let message = format!("Namespace prefix '{}' is not an NCName", lossy(prefix));+ return self.fail(inp, pos, message);+ }+ if let Some(message) = reserved_binding_error(prefix, value) {+ return self.fail(inp, pos, message);+ }+ let prefix_id = match prefix {+ Some(_) => self.names.get(definition.name).local,+ None => self.xmlns_name,+ };+ let namespace = if length == 0 {+ NONE+ } else {+ self.names.intern(value, offset, Storage::new(self.src, &self.arena))+ };+ if !self.push_binding(prefix_id, namespace, depth) {+ continue;+ }+ bindings += 1;+ reorder |= seen_plain_attribute;+ self.tape.push(+ kind::ATTR | kind::NAMESPACE_DECLARATION | kind::DEFAULTED,+ definition.name,+ self.xmlns_namespace,+ );+ self.tape.push(kind::VALUE, offset, length);+ continue;+ }++ if attribute_flags & flag::NOT_A_QNAME != 0 {+ let message = format!("Attribute name '{}' is not a qualified name", lossy(name));+ return self.fail(inp, pos, message);+ }+ seen_plain_attribute = true;+ self.tape.push(kind::ATTR | kind::DEFAULTED, definition.name, NONE);+ self.tape.push(kind::VALUE, offset, length);+ }+ }++ // The element's own namespace.+ let namespace = if element_flags & flag::NOT_A_QNAME != 0 {+ let message = format!("Failed to parse QName '{}'", self.name_string(element));+ self.namespace_error(inp, pos, message);+ self.default_namespace+ } else if element_flags & flag::HAS_PREFIX != 0 {+ let prefix = self.names.get(element).prefix;+ if element_flags & flag::PREFIX_XML != 0 {+ self.xml_namespace+ } else if element_flags & flag::PREFIX_XMLNS == 0+ && let Some(namespace) = self.namespace_of_prefix(prefix)+ {+ // The name "xmlns" holds the binding of the default namespace, which is no binding of the xmlns+ // prefix: that prefix can't be declared, so an element can't use it.+ namespace+ } else {+ let message = format!(+ "Namespace prefix {} on {} is not defined",+ self.name_string(prefix),+ self.name_string(self.names.get(element).local)+ );+ self.namespace_error(inp, pos, message);+ NONE+ }+ } else {+ self.default_namespace+ };+ self.tape.set_b(row, namespace);++ // The namespaces of the attributes. Two attributes with different prefixes are the same attribute if the+ // prefixes are bound to the same namespace.+ let mut prefixed = std::mem::take(&mut self.prefixed_scratch);+ prefixed.clear();+ let mut index = row + 1;+ while index < self.tape.len() {+ let (row_kind, attribute, _) = self.tape.row(index);+ if row_kind & kind::MASK == kind::ATTR && row_kind & kind::NAMESPACE_DECLARATION == 0 {+ let entry = *self.names.get(attribute);+ if entry.flags & flag::NOT_A_QNAME != 0 {+ let message = format!("Failed to parse QName '{}'", self.name_string(attribute));+ self.namespace_error(inp, pos, message);+ } else if entry.flags & flag::HAS_PREFIX != 0 {+ let namespace = if entry.flags & flag::PREFIX_XML != 0 {+ Some(self.xml_namespace)+ } else {+ self.namespace_of_prefix(entry.prefix)+ };+ match namespace {+ Some(namespace) if namespace != NONE => {+ self.tape.set_b(index, namespace);+ prefixed.push((entry.local, namespace));+ }+ _ => {+ let message = format!(+ "Namespace prefix {} for {} on {} is not defined",+ self.name_string(entry.prefix),+ self.name_string(entry.local),+ self.name_string(element)+ );+ self.namespace_error(inp, pos, message);+ }+ }+ }+ }+ index += 2;+ }+ if prefixed.len() > 1 {+ self.check_for_repeated_namespaced_attributes(inp, pos, &prefixed);+ }+ self.prefixed_scratch = prefixed;++ if reorder {+ let mut rows = std::mem::take(&mut self.rows_scratch);+ rows.clear();+ for index in row + 1..self.tape.len() {+ rows.push(self.tape.row(index));+ }+ self.tape.truncate(row + 1);+ for declarations in [true, false] {+ for pair in rows.as_chunks::<2>().0 {+ let (row_kind, a, b) = pair[0];+ if row_kind == 0 || (row_kind & kind::NAMESPACE_DECLARATION != 0) != declarations {+ continue;+ }+ self.tape.push(row_kind, a, b);+ self.tape.push(pair[1].0, pair[1].1, pair[1].2);+ }+ }+ self.rows_scratch = rows;+ }++ Ok(bindings)+ }++ #[inline(never)]+ fn check_for_repeated_namespaced_attributes(&mut self, inp: In, pos: usize, prefixed: &[(u32, u32)]) {+ const FEW: usize = 8;+ let mut seen = HashSet::new();+ for (index, &attribute) in prefixed.iter().enumerate() {+ // OPTIMIZATION: A tag with more than a few prefixed attributes is rare enough that building a set for+ // every tag would cost more than it saves.+ let repeated = if prefixed.len() <= FEW {+ prefixed[..index].contains(&attribute)+ } else {+ !seen.insert(attribute)+ };+ if repeated {+ let message = format!(+ "Namespaced Attribute {} in '{}' redefined",+ self.name_string(attribute.0),+ self.name_string(attribute.1)+ );+ self.namespace_error(inp, pos, message);+ }+ }+ }++ /// Handles a namespace declaration written in a start tag: `prefix` is None for `xmlns`, and the value is the+ /// string at `offset`. Returns whether it declared anything.+ fn declare_namespace(+ &mut self,+ inp: In,+ pos: usize,+ prefix: Option<u32>,+ offset: u32,+ length: u32,+ depth: u32,+ ) -> bool {+ let value = Storage::new(self.src, &self.arena).get(offset, length);+ let is_xml_namespace = value == XML_NAMESPACE;+ let is_xmlns_namespace = value == XMLNS_NAMESPACE;+ // NB: A namespace name is meant to be a URI reference, but one that isn't is a name all the same: nothing+ // ever resolves it, and it is only ever compared with other names.+ let namespace = if length == 0 {+ NONE+ } else {+ self.names.intern(value, offset, Storage::new(self.src, &self.arena))+ };++ let Some(prefix) = prefix else {+ if is_xml_namespace {+ self.namespace_error(inp, pos, "xml namespace URI cannot be the default namespace".into());+ return false;+ }+ if is_xmlns_namespace {+ self.namespace_error(inp, pos, "reuse of the xmlns namespace name is forbidden".into());+ return false;+ }+ return self.push_binding(self.xmlns_name, namespace, depth);+ };++ let prefix_bytes = self.names.bytes(prefix, Storage::new(self.src, &self.arena));+ if prefix_bytes == b"xml" {+ // The xml prefix is bound to its namespace from the start, and there is nothing else it can be bound to.+ if !is_xml_namespace {+ self.namespace_error(inp, pos, "xml namespace prefix mapped to wrong URI".into());+ }+ return false;+ }+ if is_xml_namespace {+ self.namespace_error(inp, pos, "xml namespace URI mapped to wrong prefix".into());+ return false;+ }+ if prefix_bytes == b"xmlns" {+ self.namespace_error(inp, pos, "redefinition of the xmlns prefix is forbidden".into());+ return false;+ }+ if is_xmlns_namespace {+ self.namespace_error(inp, pos, "reuse of the xmlns namespace name is forbidden".into());+ return false;+ }+ if length == 0 {+ let message = format!("xmlns:{}: Empty XML namespace is not allowed", self.name_string(prefix));+ self.namespace_error(inp, pos, message);+ return false;+ }+ self.push_binding(prefix, namespace, depth)+ }+}++/// The rules of Namespaces in XML 1.0 §3 for the reserved prefixes and namespace names, and of §6.2 that a prefix+/// can't be bound to an empty namespace name, as they apply to a declaration the DTD defaults.+fn reserved_binding_error(prefix: Option<&[u8]>, value: &[u8]) -> Option<String> {+ let Some(prefix) = prefix else {+ if value == XML_NAMESPACE {+ return Some("The XML namespace must not be declared as the default namespace".into());+ }+ if value == XMLNS_NAMESPACE {+ return Some("The xmlns namespace must not be declared as the default namespace".into());+ }+ return None;+ };+ let prefix = lossy(prefix);+ if prefix == "xmlns" {+ return Some("The xmlns prefix must not be declared".into());+ }+ if value.is_empty() {+ return Some(format!(+ "Namespace prefix '{prefix}' must not be bound to an empty namespace name"+ ));+ }+ if value == XML_NAMESPACE {+ return Some(format!(+ "Namespace prefix '{prefix}' must not be bound to the XML namespace"+ ));+ }+ if value == XMLNS_NAMESPACE {+ return Some(format!(+ "Namespace prefix '{prefix}' must not be bound to the xmlns namespace"+ ));+ }+ None+}++/// Removes leading and trailing spaces and makes every run of spaces one space.+pub(crate) fn collapse_spaces(buffer: &mut Vec<u8>) {+ let mut write = 0;+ let mut pending_space = false;+ for read in 0..buffer.len() {+ let byte = buffer[read];+ if byte == b' ' {+ pending_space = write > 0;+ } else {+ if pending_space {+ buffer[write] = b' ';+ write += 1;+ pending_space = false;+ }+ buffer[write] = byte;+ write += 1;+ }+ }+ buffer.truncate(write);+}diff --git a/Libraries/LibXML/Rust/src/scan.rs b/Libraries/LibXML/Rust/src/scan.rsnew file mode 100644index 00000000000..eb4acca984d--- /dev/null+++ b/Libraries/LibXML/Rust/src/scan.rs@@ -0,0 +1,334 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The loops that skip over runs of plain characters: the text between two tags, the inside of an attribute value, a+//! comment. Each returns the position of the first byte the caller has to look at, or the length of the input.+//!+//! OPTIMIZATION: Most of a document's bytes are in such runs, so these loops look at a block of bytes at a time. A+//! byte needs the caller's attention when it is one of up to three delimiters, a C0 control, or the start of a+//! non-ASCII sequence. The last two share one signed comparison: as an i8, a byte at or above 0x80 is negative, so+//! "less than 0x20" covers both.++/// Which C0 controls end a run, besides the ones that are never allowed.+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum Controls {+ /// Tab and LF are plain. CR ends the run: it has to be normalized.+ StopAtCr,+ /// Tab, LF and CR all end the run: in an attribute value each becomes a space.+ StopAtAll,+}++#[inline(always)]+fn needs_attention(byte: u8, d0: u8, d1: u8, d2: u8, controls: Controls) -> bool {+ if byte == d0 || byte == d1 || byte == d2 {+ return true;+ }+ if (byte as i8) < 0x20 {+ return controls == Controls::StopAtAll || (byte != b'\t' && byte != b'\n');+ }+ false+}++#[inline(always)]+fn scalar(bytes: &[u8], mut pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ while pos < bytes.len() && !needs_attention(bytes[pos], d0, d1, d2, controls) {+ pos += 1;+ }+ pos+}++/// The first position at or after `pos` whose byte is `d0`, `d1`, `d2`, a control selected by `controls`, or at or+/// above 0x80. Pass the same delimiter more than once to look for fewer than three.+#[inline(always)]+pub fn find(bytes: &[u8], pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ let pos = block::find(bytes, pos, d0, d1, d2, controls);+ scalar(bytes, pos, d0, d1, d2, controls)+}++/// The reference implementation, for testing the block versions against.+#[cfg(test)]+pub fn find_scalar(bytes: &[u8], pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ scalar(bytes, pos, d0, d1, d2, controls)+}++#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]+mod block {+ use super::Controls;+ use core::arch::x86_64::*;++ const BLOCK: usize = 32;++ /// Returns the position of the first byte that needs attention if a whole block containing it could be read, or+ /// else the position of the first byte no whole block covers.+ #[inline(always)]+ pub fn find(bytes: &[u8], mut pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ while pos + BLOCK <= bytes.len() {+ // SAFETY: The block [pos, pos + BLOCK) is inside `bytes`, and AVX2 is statically enabled.+ let mask = unsafe {+ let x = _mm256_loadu_si256(bytes.as_ptr().add(pos) as *const __m256i);+ let delimiters = _mm256_or_si256(+ _mm256_or_si256(+ _mm256_cmpeq_epi8(x, _mm256_set1_epi8(d0 as i8)),+ _mm256_cmpeq_epi8(x, _mm256_set1_epi8(d1 as i8)),+ ),+ _mm256_cmpeq_epi8(x, _mm256_set1_epi8(d2 as i8)),+ );+ let mut low = _mm256_cmpgt_epi8(_mm256_set1_epi8(0x20), x);+ if controls == Controls::StopAtCr {+ let plain = _mm256_or_si256(+ _mm256_cmpeq_epi8(x, _mm256_set1_epi8(b'\t' as i8)),+ _mm256_cmpeq_epi8(x, _mm256_set1_epi8(b'\n' as i8)),+ );+ low = _mm256_andnot_si256(plain, low);+ }+ _mm256_movemask_epi8(_mm256_or_si256(delimiters, low)) as u32+ };+ if mask != 0 {+ return pos + mask.trailing_zeros() as usize;+ }+ pos += BLOCK;+ }+ pos+ }+}++#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))]+mod block {+ use super::Controls;+ use core::arch::x86_64::*;++ const BLOCK: usize = 16;++ /// Returns the position of the first byte that needs attention if a whole block containing it could be read, or+ /// else the position of the first byte no whole block covers.+ #[inline(always)]+ pub fn find(bytes: &[u8], mut pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ while pos + BLOCK <= bytes.len() {+ // SAFETY: The block [pos, pos + BLOCK) is inside `bytes`, and SSE2 is part of the x86_64 baseline.+ let mask = unsafe {+ let x = _mm_loadu_si128(bytes.as_ptr().add(pos) as *const __m128i);+ let delimiters = _mm_or_si128(+ _mm_or_si128(+ _mm_cmpeq_epi8(x, _mm_set1_epi8(d0 as i8)),+ _mm_cmpeq_epi8(x, _mm_set1_epi8(d1 as i8)),+ ),+ _mm_cmpeq_epi8(x, _mm_set1_epi8(d2 as i8)),+ );+ let mut low = _mm_cmplt_epi8(x, _mm_set1_epi8(0x20));+ if controls == Controls::StopAtCr {+ let plain = _mm_or_si128(+ _mm_cmpeq_epi8(x, _mm_set1_epi8(b'\t' as i8)),+ _mm_cmpeq_epi8(x, _mm_set1_epi8(b'\n' as i8)),+ );+ low = _mm_andnot_si128(plain, low);+ }+ _mm_movemask_epi8(_mm_or_si128(delimiters, low)) as u32+ };+ if mask != 0 {+ return pos + mask.trailing_zeros() as usize;+ }+ pos += BLOCK;+ }+ pos+ }+}++#[cfg(target_arch = "aarch64")]+mod block {+ use super::Controls;+ use core::arch::aarch64::*;++ const BLOCK: usize = 16;++ /// Returns the position of the first byte that needs attention if a whole block containing it could be read, or+ /// else the position of the first byte no whole block covers.+ #[inline(always)]+ pub fn find(bytes: &[u8], mut pos: usize, d0: u8, d1: u8, d2: u8, controls: Controls) -> usize {+ while pos + BLOCK <= bytes.len() {+ // SAFETY: The block [pos, pos + BLOCK) is inside `bytes`, and NEON is part of the aarch64 baseline.+ let mask = unsafe {+ let x = vld1q_u8(bytes.as_ptr().add(pos));+ let delimiters = vorrq_u8(+ vorrq_u8(vceqq_u8(x, vdupq_n_u8(d0)), vceqq_u8(x, vdupq_n_u8(d1))),+ vceqq_u8(x, vdupq_n_u8(d2)),+ );+ let mut low = vcltq_s8(vreinterpretq_s8_u8(x), vdupq_n_s8(0x20));+ if controls == Controls::StopAtCr {+ let plain = vorrq_u8(vceqq_u8(x, vdupq_n_u8(b'\t')), vceqq_u8(x, vdupq_n_u8(b'\n')));+ low = vbicq_u8(low, plain);+ }+ // Narrowing each 16-bit lane by four bits leaves four mask bits per byte, in order.+ let any = vreinterpretq_u16_u8(vorrq_u8(delimiters, low));+ vget_lane_u64::<0>(vreinterpret_u64_u8(vshrn_n_u16::<4>(any)))+ };+ if mask != 0 {+ return pos + (mask.trailing_zeros() / 4) as usize;+ }+ pos += BLOCK;+ }+ pos+ }+}++#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]+mod block {+ use super::Controls;++ #[inline(always)]+ pub fn find(_bytes: &[u8], pos: usize, _d0: u8, _d1: u8, _d2: u8, _controls: Controls) -> usize {+ pos+ }+}++/// Returns where the run of ASCII name characters that starts at `pos` ends. A caller parsing a name has to look at+/// the byte there: if it is at or above 0x80 the name may go on.+#[inline(always)]+pub fn ascii_name_end(bytes: &[u8], mut pos: usize) -> usize {+ pos = name_block::ascii_name_end(bytes, pos);+ while pos < bytes.len() && crate::chars::CLASS[bytes[pos] as usize] & crate::chars::NAME != 0 {+ pos += 1;+ }+ pos+}++// OPTIMIZATION: A name is a handful of bytes, and where it ends is anyone's guess, so a loop over its bytes ends in a+// mispredicted branch nearly every time. Classifying sixteen bytes at once and counting the leading name characters+// has no such branch. The classification is two table lookups on the halves of each byte: a byte is a name+// character if the entries for its high and low nibbles share a bit.+//+// | high nibble | name characters | bit |+// |-------------|-----------------|-----|+// | 2 | - . | 0 |+// | 3 | 0-9 : | 1 |+// | 4, 6 | A-O, a-o | 2 |+// | 5 | P-Z _ | 3 |+// | 7 | p-z | 4 |+#[cfg(any(all(target_arch = "x86_64", target_feature = "ssse3"), target_arch = "aarch64"))]+const NAME_LOW_NIBBLES: [u8; 16] = [26, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 4, 4, 5, 5, 12];+#[cfg(any(all(target_arch = "x86_64", target_feature = "ssse3"), target_arch = "aarch64"))]+const NAME_HIGH_NIBBLES: [u8; 16] = [0, 0, 1, 2, 4, 8, 4, 16, 0, 0, 0, 0, 0, 0, 0, 0];++#[cfg(all(target_arch = "x86_64", target_feature = "ssse3"))]+mod name_block {+ use super::NAME_HIGH_NIBBLES;+ use super::NAME_LOW_NIBBLES;+ use core::arch::x86_64::*;++ #[inline(always)]+ pub fn ascii_name_end(bytes: &[u8], mut pos: usize) -> usize {+ while pos + 16 <= bytes.len() {+ // SAFETY: The block [pos, pos + 16) is inside `bytes`, the tables are sixteen bytes, and SSSE3 is+ // statically enabled.+ let others = unsafe {+ let x = _mm_loadu_si128(bytes.as_ptr().add(pos) as *const __m128i);+ let low_table = _mm_loadu_si128(NAME_LOW_NIBBLES.as_ptr() as *const __m128i);+ let high_table = _mm_loadu_si128(NAME_HIGH_NIBBLES.as_ptr() as *const __m128i);+ // A byte at or above 0x80 selects zero from the first table, and so is never a name character.+ let low = _mm_shuffle_epi8(low_table, x);+ let high = _mm_shuffle_epi8(high_table, _mm_and_si128(_mm_srli_epi16::<4>(x), _mm_set1_epi8(0x0F)));+ _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_and_si128(low, high), _mm_setzero_si128())) as u32+ };+ if others != 0 {+ return pos + others.trailing_zeros() as usize;+ }+ pos += 16;+ }+ pos+ }+}++#[cfg(target_arch = "aarch64")]+mod name_block {+ use super::NAME_HIGH_NIBBLES;+ use super::NAME_LOW_NIBBLES;+ use core::arch::aarch64::*;++ #[inline(always)]+ pub fn ascii_name_end(bytes: &[u8], mut pos: usize) -> usize {+ while pos + 16 <= bytes.len() {+ // SAFETY: The block [pos, pos + 16) is inside `bytes`, the tables are sixteen bytes, and NEON is part of+ // the aarch64 baseline.+ let others = unsafe {+ let x = vld1q_u8(bytes.as_ptr().add(pos));+ let low_table = vld1q_u8(NAME_LOW_NIBBLES.as_ptr());+ let high_table = vld1q_u8(NAME_HIGH_NIBBLES.as_ptr());+ // The high nibble of a byte at or above 0x80 selects zero from the second table, and so such a byte+ // is never a name character.+ let low = vqtbl1q_u8(low_table, vandq_u8(x, vdupq_n_u8(0x0F)));+ let high = vqtbl1q_u8(high_table, vshrq_n_u8::<4>(x));+ let other = vceqzq_u8(vandq_u8(low, high));+ vget_lane_u64::<0>(vreinterpret_u64_u8(vshrn_n_u16::<4>(vreinterpretq_u16_u8(other))))+ };+ if others != 0 {+ return pos + (others.trailing_zeros() / 4) as usize;+ }+ pos += 16;+ }+ pos+ }+}++#[cfg(not(any(all(target_arch = "x86_64", target_feature = "ssse3"), target_arch = "aarch64")))]+mod name_block {+ #[inline(always)]+ pub fn ascii_name_end(_bytes: &[u8], pos: usize) -> usize {+ pos+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn block_and_scalar_agree() {+ // A deterministic xorshift, so a failure reproduces.+ let mut state = 0x9E37_79B9_7F4A_7C15u64;+ let mut next = move || {+ state ^= state << 13;+ state ^= state >> 7;+ state ^= state << 17;+ state+ };+ for _ in 0..20_000 {+ let length = (next() % 100) as usize;+ let mut bytes = vec![b'a'; length];+ for _ in 0..(next() % 4) {+ if length > 0 {+ let index = (next() % length as u64) as usize;+ bytes[index] = (next() % 256) as u8;+ }+ }+ let start = if length == 0 {+ 0+ } else {+ (next() % length as u64) as usize+ };+ for controls in [Controls::StopAtCr, Controls::StopAtAll] {+ assert_eq!(+ find(&bytes, start, b'<', b'&', b']', controls),+ find_scalar(&bytes, start, b'<', b'&', b']', controls),+ "{bytes:?} from {start}"+ );+ }+ }+ }++ #[test]+ fn name_end_agrees_with_the_class_table() {+ let mut bytes: Vec<u8> = (0..=255u8).collect();+ bytes.extend(std::iter::repeat_n(b'a', 40));+ bytes.extend_from_slice(b"-._:09AZaz /=>\x80abc");+ bytes.extend(std::iter::repeat_n(b'z', 40));+ for start in 0..bytes.len() {+ let mut expected = start;+ while expected < bytes.len() && crate::chars::CLASS[bytes[expected] as usize] & crate::chars::NAME != 0 {+ expected += 1;+ }+ assert_eq!(ascii_name_end(&bytes, start), expected, "from {start}");+ }+ }+}diff --git a/Libraries/LibXML/Rust/src/tape.rs b/Libraries/LibXML/Rust/src/tape.rsnew file mode 100644index 00000000000..11722e46a6e--- /dev/null+++ b/Libraries/LibXML/Rust/src/tape.rs@@ -0,0 +1,140 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the parser produces: a flat list of events in document order, stored as three parallel columns.+//!+//! A row is a kind and two 32-bit operands. Strings are never copied out of the document if they can be used as they+//! are: a string operand pair is an offset and a length into one address space that holds the source first and the+//! parser's arena (decoded text, normalized attribute values) right after it. Names are ids into the name table.+//!+//! | kind | a | b | followed by |+//! |---------|--------------|--------------|----------------------------------------------|+//! | START | name | namespace | its ATTR rows |+//! | ATTR | name | namespace | one VALUE row |+//! | VALUE | offset | length | |+//! | END | name | NONE | |+//! | TEXT | offset | length | |+//! | CDATA | offset | length | |+//! | COMMENT | offset | length | |+//! | PI | target name | NONE | one VALUE row, the data |+//! | DOCTYPE | name | NONE | two VALUE rows, the public and system ids |++pub const NONE: u32 = u32::MAX;++pub mod kind {+ pub const START: u8 = 1;+ pub const ATTR: u8 = 2;+ pub const VALUE: u8 = 3;+ pub const END: u8 = 4;+ pub const TEXT: u8 = 5;+ pub const CDATA: u8 = 6;+ pub const COMMENT: u8 = 7;+ pub const PI: u8 = 8;+ pub const DOCTYPE: u8 = 9;++ /// The low bits of a kind byte hold the kind, the high bits its flags.+ pub const MASK: u8 = 0x0F;++ /// On ATTR: the attribute is a namespace declaration.+ pub const NAMESPACE_DECLARATION: u8 = 0x80;+ /// On ATTR: the attribute wasn't in the tag, its value is the default the DTD declares.+ pub const DEFAULTED: u8 = 0x40;+ /// On a VALUE row of a DOCTYPE: the id is absent, as opposed to empty.+ pub const ABSENT: u8 = 0x80;+}++#[derive(Default)]+pub struct Tape {+ // The columns are always fully initialized up to their capacity and `len` says how much is in use, so that+ // appending a row is one capacity check and three plain stores.+ kind: Vec<u8>,+ a: Vec<u32>,+ b: Vec<u32>,+ len: usize,+}++impl Tape {+ pub fn with_capacity(rows: usize) -> Self {+ let rows = rows.max(16);+ Tape {+ kind: vec![0; rows],+ a: vec![0; rows],+ b: vec![0; rows],+ len: 0,+ }+ }++ #[inline(always)]+ pub fn push(&mut self, kind: u8, a: u32, b: u32) {+ if self.len == self.kind.len() {+ self.grow();+ }+ let index = self.len;+ self.kind[index] = kind;+ self.a[index] = a;+ self.b[index] = b;+ self.len = index + 1;+ }++ #[cold]+ #[inline(never)]+ fn grow(&mut self) {+ let rows = (self.kind.len() * 2).max(16);+ self.kind.resize(rows, 0);+ self.a.resize(rows, 0);+ self.b.resize(rows, 0);+ }++ #[inline(always)]+ pub fn len(&self) -> usize {+ self.len+ }++ pub fn is_empty(&self) -> bool {+ self.len == 0+ }++ pub fn truncate(&mut self, len: usize) {+ self.len = self.len.min(len);+ }++ pub fn kinds(&self) -> &[u8] {+ &self.kind[..self.len]+ }++ pub fn a(&self) -> &[u32] {+ &self.a[..self.len]+ }++ pub fn b(&self) -> &[u32] {+ &self.b[..self.len]+ }++ #[inline(always)]+ pub fn row(&self, index: usize) -> (u8, u32, u32) {+ (self.kind[index], self.a[index], self.b[index])+ }++ #[inline(always)]+ pub fn set_row(&mut self, index: usize, kind: u8, a: u32, b: u32) {+ debug_assert!(index < self.len);+ self.kind[index] = kind;+ self.a[index] = a;+ self.b[index] = b;+ }++ #[inline(always)]+ pub fn set_b(&mut self, index: usize, b: u32) {+ debug_assert!(index < self.len);+ self.b[index] = b;+ }++ #[inline(always)]+ pub fn set_kind(&mut self, index: usize, kind: u8) {+ debug_assert!(index < self.len);+ self.kind[index] = kind;+ }+}diff --git a/Libraries/LibXML/Rust/src/verify.rs b/Libraries/LibXML/Rust/src/verify.rsnew file mode 100644index 00000000000..f5853f32ad1--- /dev/null+++ b/Libraries/LibXML/Rust/src/verify.rs@@ -0,0 +1,129 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Checks a `Document` against everything a reader of one relies on. For tests and fuzzing: whatever the input, the+//! parser has to produce a document this accepts.++use crate::Document;+use crate::tape::NONE;+use crate::tape::kind;++/// Returns what is wrong with `document`, the result of parsing `source`, if anything is.+pub fn verify(document: &Document, source: &[u8]) -> Result<(), String> {+ let tape = &document.tape;+ let (kinds, a, b) = (tape.kinds(), tape.a(), tape.b());+ let names = document.names.entries();+ let end_of_strings = source.len() + document.arena.len();++ // A string is wholly in the source or wholly in the arena, and is UTF-8: readers turn it into text unchecked.+ let string = |offset: u32, length: u32, what: &str| -> Result<(), String> {+ let (offset, length) = (offset as usize, length as usize);+ let bytes = if offset < source.len() {+ source.get(offset..offset + length)+ } else if offset + length <= end_of_strings {+ document+ .arena+ .get(offset - source.len()..offset - source.len() + length)+ } else {+ None+ };+ let Some(bytes) = bytes else {+ return Err(format!("{what}: string {offset}+{length} is out of range"));+ };+ if std::str::from_utf8(bytes).is_err() {+ return Err(format!("{what}: string {offset}+{length} is not UTF-8"));+ }+ Ok(())+ };+ let name = |id: u32, what: &str| -> Result<(), String> {+ let Some(entry) = names.get(id as usize) else {+ return Err(format!("{what}: name {id} is out of range"));+ };+ if entry.length == 0 {+ return Err(format!("{what}: name {id} is empty"));+ }+ string(entry.offset, entry.length, what)+ };+ let value = |row: usize, what: &str| -> Result<(), String> {+ if row >= kinds.len() || kinds[row] & kind::MASK != kind::VALUE {+ return Err(format!("{what} at row {row}: no value row"));+ }+ string(a[row], b[row], what)+ };++ let fatal = document.errors.iter().any(|error| error.fatal);+ let mut open: Vec<u32> = Vec::new();+ let mut roots = 0;+ let mut row = 0;+ while row < kinds.len() {+ match kinds[row] & kind::MASK {+ kind::START => {+ name(a[row], "start tag")?;+ if b[row] != NONE {+ name(b[row], "element namespace")?;+ }+ if open.is_empty() {+ roots += 1;+ }+ open.push(a[row]);+ while row + 1 < kinds.len() && kinds[row + 1] & kind::MASK == kind::ATTR {+ name(a[row + 1], "attribute")?;+ if b[row + 1] != NONE {+ name(b[row + 1], "attribute namespace")?;+ }+ value(row + 2, "attribute")?;+ row += 2;+ }+ }+ kind::END => {+ name(a[row], "end tag")?;+ if open.pop() != Some(a[row]) {+ return Err(format!("row {row}: end tag doesn't match the open element"));+ }+ }+ kind::TEXT | kind::CDATA | kind::COMMENT => string(a[row], b[row], "character data")?,+ kind::PI => {+ name(a[row], "processing instruction")?;+ value(row + 1, "processing instruction")?;+ row += 1;+ }+ kind::DOCTYPE => {+ name(a[row], "doctype")?;+ value(row + 1, "doctype")?;+ value(row + 2, "doctype")?;+ row += 2;+ }+ other => return Err(format!("row {row}: unexpected kind {other}")),+ }+ row += 1;+ }++ if !fatal {+ if !open.is_empty() {+ return Err("an element is left open in a document without a fatal error".into());+ }+ if roots != 1 {+ return Err(format!("{roots} root elements in a document without a fatal error"));+ }+ } else if roots > 1 {+ return Err(format!("{roots} root elements"));+ }++ let mut previous_row = 0;+ for (index, error) in document.errors.iter().enumerate() {+ if error.row < previous_row || error.row as usize > kinds.len() {+ return Err(format!("error {index} is out of order, at row {}", error.row));+ }+ previous_row = error.row;+ if error.fatal && index + 1 != document.errors.len() {+ return Err(format!("error {index} is fatal but isn't the last"));+ }+ if error.offset as usize > source.len() {+ return Err(format!("error {index} is past the end of the source"));+ }+ }+ Ok(())+}diff --git a/Libraries/LibXML/Rust/tests/xmlconf.rs b/Libraries/LibXML/Rust/tests/xmlconf.rsnew file mode 100644index 00000000000..ba351dd9d52--- /dev/null+++ b/Libraries/LibXML/Rust/tests/xmlconf.rs@@ -0,0 +1,413 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runs the W3C XML Conformance Test Suite, if `XMLCONF_DIR` points at an unpacked copy of it (the directory with+//! `xmlconf.xml` in it). Set `XMLCONF_VERBOSE` to list the tests that don't do what the suite says, or to `all` to+//! include the ones that can't without reading external entities.++use std::collections::BTreeMap;+use std::path::Path;+use std::path::PathBuf;++use libxml_rust::Document;+use libxml_rust::Options;+use libxml_rust::parse;+use libxml_rust::tape::kind;++struct Test {+ id: String,+ kind: String,+ path: PathBuf,+ output: Option<PathBuf>,+ entities: String,+ namespaces: bool,+}++fn attribute<'a>(document: &'a Document, source: &'a [u8], row: usize, wanted: &str) -> Option<&'a [u8]> {+ let storage = document.storage(source);+ let tape = &document.tape;+ let mut index = row + 1;+ while index < tape.len() && tape.row(index).0 & kind::MASK == kind::ATTR {+ let (_, name, _) = tape.row(index);+ if document.names.bytes(name, storage) == wanted.as_bytes() {+ let (_, offset, length) = tape.row(index + 1);+ return Some(storage.get(offset, length));+ }+ index += 2;+ }+ None+}++/// Reads one catalog file. The suite's catalogs are XML, so they are read with the parser under test.+fn read_catalog(path: &Path, tests: &mut Vec<Test>) {+ let mut source = std::fs::read(path).unwrap();+ // Some of the catalogs are a list of TEST elements with no element around them.+ if !source.windows(10).any(|window| window == b"<TESTCASES") {+ let mut wrapped = b"<TESTCASES>".to_vec();+ let body = match source.windows(2).position(|window| window == b"?>") {+ Some(end) if source.starts_with(b"<?xml") => &source[end + 2..],+ _ => &source[..],+ };+ wrapped.extend_from_slice(body);+ wrapped.extend_from_slice(b"</TESTCASES>");+ source = wrapped;+ }+ let document = parse(&source, Options::default());+ assert!(+ document.errors.is_empty(),+ "{}: {}",+ path.display(),+ document.errors[0].message+ );+ let storage = document.storage(&source);+ let directory = path.parent().unwrap();+ for row in 0..document.tape.len() {+ let (row_kind, name, _) = document.tape.row(row);+ if row_kind & kind::MASK != kind::START || document.names.bytes(name, storage) != b"TEST" {+ continue;+ }+ let text =+ |wanted: &str| attribute(&document, &source, row, wanted).map(|v| String::from_utf8_lossy(v).into_owned());+ // This parser implements the fifth edition of XML 1.0, and XML 1.1 documents are read by its rules.+ if text("VERSION").is_some_and(|version| version != "1.0") {+ continue;+ }+ if text("RECOMMENDATION").is_some_and(|recommendation| recommendation.ends_with("1.1")) {+ continue;+ }+ if text("EDITION").is_some_and(|edition| !edition.split_whitespace().any(|e| e == "5")) {+ continue;+ }+ tests.push(Test {+ id: text("ID").unwrap(),+ kind: text("TYPE").unwrap(),+ path: directory.join(text("URI").unwrap()),+ output: text("OUTPUT").map(|output| directory.join(output)),+ entities: text("ENTITIES").unwrap_or_else(|| "none".into()),+ namespaces: text("NAMESPACE").is_none_or(|namespace| namespace != "no"),+ });+ }+}++fn escape(bytes: &[u8], out: &mut Vec<u8>) {+ for &byte in bytes {+ match byte {+ b'&' => out.extend_from_slice(b"&"),+ b'<' => out.extend_from_slice(b"<"),+ b'>' => out.extend_from_slice(b">"),+ b'"' => out.extend_from_slice(b"""),+ b'\t' => out.extend_from_slice(b"	"),+ b'\n' => out.extend_from_slice(b" "),+ b'\r' => out.extend_from_slice(b" "),+ _ => out.push(byte),+ }+ }+}++/// The document in the canonical form the suite's expected outputs are in.+fn canonical(document: &Document, source: &[u8]) -> Vec<u8> {+ let storage = document.storage(source);+ let tape = &document.tape;+ let mut out = Vec::new();+ let mut index = 0;+ while index < tape.len() {+ let (row_kind, a, b) = tape.row(index);+ match row_kind & kind::MASK {+ kind::START => {+ out.push(b'<');+ out.extend_from_slice(document.names.bytes(a, storage));+ let mut attributes = BTreeMap::new();+ index += 1;+ while index < tape.len() && tape.row(index).0 & kind::MASK == kind::ATTR {+ let (_, name, _) = tape.row(index);+ let (_, offset, length) = tape.row(index + 1);+ attributes.insert(document.names.bytes(name, storage), storage.get(offset, length));+ index += 2;+ }+ for (name, value) in attributes {+ out.push(b' ');+ out.extend_from_slice(name);+ out.extend_from_slice(b"=\"");+ escape(value, &mut out);+ out.push(b'"');+ }+ out.push(b'>');+ continue;+ }+ kind::END => {+ out.extend_from_slice(b"</");+ out.extend_from_slice(document.names.bytes(a, storage));+ out.push(b'>');+ }+ kind::TEXT => escape(storage.get(a, b), &mut out),+ kind::PI => {+ let (_, offset, length) = tape.row(index + 1);+ out.extend_from_slice(b"<?");+ out.extend_from_slice(document.names.bytes(a, storage));+ out.push(b' ');+ out.extend_from_slice(storage.get(offset, length));+ out.extend_from_slice(b"?>");+ index += 1;+ }+ kind::DOCTYPE => index += 2,+ _ => {}+ }+ index += 1;+ }+ out+}++#[test]+fn xmlconf() {+ let Ok(root) = std::env::var("XMLCONF_DIR") else {+ eprintln!("XMLCONF_DIR is not set, skipping");+ return;+ };+ let root = PathBuf::from(root);+ let verbose = std::env::var("XMLCONF_VERBOSE").is_ok();++ // The top catalog pulls the others in as external entities, which this parser doesn't read. Their paths are in+ // its entity declarations.+ let top = std::fs::read_to_string(root.join("xmlconf.xml")).unwrap();+ let mut tests = Vec::new();+ for declaration in top.split("<!ENTITY").skip(1) {+ let Some(start) = declaration.find("SYSTEM \"") else {+ continue;+ };+ let rest = &declaration[start + 8..];+ let path = &rest[..rest.find('"').unwrap()];+ read_catalog(&root.join(path), &mut tests);+ }+ assert!(tests.len() > 1500, "only found {} tests", tests.len());++ let options = Options {+ preserve_comments: false,+ preserve_cdata: false,+ resolve_html_entity: None,+ };+ let mut tally: BTreeMap<String, (usize, usize)> = BTreeMap::new();+ let mut failures = Vec::new();+ for test in &tests {+ // These three are documents whose encoding declaration disagrees with how they are encoded. That is for+ // whoever decodes the document to notice: the parser is handed UTF-8 and doesn't act on the declaration.+ if matches!(test.id.as_str(), "rmt-e2e-61" | "hst-lhs-007" | "hst-lhs-008") {+ continue;+ }+ // The expected output of this one has a processing instruction that is in the DTD. Those aren't part of the+ // document's content, and get no row.+ if test.id == "ibm-valid-P29-ibm29v01.xml" {+ continue;+ }+ let source = std::fs::read(&test.path)+ .unwrap_or_else(|error| panic!("{}: cannot read {}: {error}", test.id, test.path.display()));+ // The suite has documents in UTF-16 and other encodings. Decoding is the caller's job, so they are decoded+ // here, and the ones this test can't decode are left out.+ let source = if source.starts_with(&[0xFF, 0xFE]) || source.starts_with(&[0xFE, 0xFF]) {+ let big_endian = source[0] == 0xFE;+ let units: Vec<u16> = source[2..]+ .as_chunks::<2>()+ .0+ .iter()+ .map(|pair| {+ if big_endian {+ u16::from_be_bytes([pair[0], pair[1]])+ } else {+ u16::from_le_bytes([pair[0], pair[1]])+ }+ })+ .collect();+ match String::from_utf16(&units) {+ Ok(text) => text.into_bytes(),+ Err(_) => continue,+ }+ } else {+ let head = String::from_utf8_lossy(&source[..source.len().min(100)]).to_lowercase();+ if head.contains("encoding")+ && !head.contains("utf-8")+ && !head.contains("us-ascii")+ && std::str::from_utf8(&source).is_err()+ {+ continue;+ }+ source+ };++ let document = parse(&source, options);+ if let Err(problem) = libxml_rust::verify::verify(&document, &source) {+ panic!("{}: {problem}", test.id);+ }+ let fatal = document.errors.iter().any(|error| error.fatal);+ // A reference to an entity that may be declared where this parser doesn't read is reported without failing+ // the parse. The document is well-formed all the same, and namespace-well-formed too.+ let any_error = document+ .errors+ .iter()+ .any(|error| error.fatal || !error.message.starts_with("Entity '"));+ let self_contained = test.entities == "none";+ let bucket = format!(+ "{}{}",+ test.kind,+ if self_contained { "" } else { " (external entities)" }+ );+ let passed = match test.kind.as_str() {+ "not-wf" => {+ if test.namespaces {+ any_error+ } else {+ fatal+ }+ }+ "valid" | "invalid" => {+ let well_formed = if test.namespaces { !any_error } else { !fatal };+ let output_matches = match &test.output {+ Some(output) if well_formed => std::fs::read(output).is_ok_and(|expected| {+ // Some expected outputs start with the document's notation declarations, which a parser+ // that doesn't validate has no use for and this one doesn't report.+ let expected = match expected.windows(3).position(|window| window == b"]>\n") {+ Some(end) if expected.starts_with(b"<!DOCTYPE") => &expected[end + 3..],+ _ => &expected[..],+ };+ expected == canonical(&document, &source)+ }),+ _ => true,+ };+ well_formed && output_matches+ }+ _ => true,+ };+ // These two say that a CR written as a character reference in an entity's value is still a CR where the+ // entity is used in content. That is what XML says, but not what libxml2 and with it most of the web does:+ // the line end is normalized where the entity is used, and the CR arrives as a LF.+ let passed = passed || matches!(test.id.as_str(), "valid-sa-068" | "valid-sa-108");+ let entry = tally.entry(bucket.clone()).or_default();+ entry.1 += 1;+ if passed {+ entry.0 += 1;+ } else {+ let reason = match document.errors.first() {+ Some(error) => format!("{}:{}: {}", error.line, error.column, error.message),+ None => "no error".into(),+ };+ if self_contained || std::env::var("XMLCONF_VERBOSE").is_ok_and(|value| value == "all") {+ let path = test.path.strip_prefix(&root).unwrap_or(&test.path);+ failures.push(format!("{} [{}] {} -- {}", test.id, bucket, path.display(), reason));+ }+ }+ }++ for (bucket, (passed, total)) in &tally {+ eprintln!("{bucket:40} {passed:5} / {total}");+ }+ if verbose {+ for failure in &failures {+ eprintln!(" {failure}");+ }+ }++ // Everything that doesn't depend on an external entity has to do what the suite says.+ for bucket in ["not-wf", "valid", "invalid"] {+ let (passed, total) = tally[bucket];+ assert_eq!(passed, total, "{bucket}: run with XMLCONF_VERBOSE=1 for the list");+ }+}++#[test]+fn error_positions() {+ // An error in an entity's text is at the reference to the entity.+ let source = b"<!DOCTYPE a [\n<!ENTITY e '<q:c/>'>\n]>\n<a>\n <p:b/>\n\n <p:b x='&e;'/><p:c>&e;</p:c>\n<";+ let document = parse(source, Options::default());+ let positions: Vec<(u32, u32, bool)> = document+ .errors+ .iter()+ .map(|error| (error.line, error.column, error.fatal))+ .collect();+ assert_eq!(+ positions,+ [(5, 3, false), (7, 10, true)],+ "{:?}",+ document.errors.iter().map(|error| &error.message).collect::<Vec<_>>()+ );++ let source = b"<a>\n<p:b/>\n\n <p:c/><p:d>\n";+ let document = parse(source, Options::default());+ let positions: Vec<(u32, u32, bool)> = document+ .errors+ .iter()+ .map(|error| (error.line, error.column, error.fatal))+ .collect();+ assert_eq!(positions, [(2, 1, false), (4, 3, false), (4, 9, false), (5, 1, true)]);+}++#[test]+fn defaulted_attributes_count_as_expansion() {+ let document_with = |attributes: usize, elements: usize| {+ let mut source = String::from("<!DOCTYPE a [\n<!ATTLIST e");+ for index in 0..attributes {+ source.push_str(&format!(" a{index} CDATA '0'"));+ }+ source.push_str(">\n]>\n<a>");+ source.push_str(&"<e/>".repeat(elements));+ source.push_str("</a>");+ source+ };++ // A document that makes modest use of defaults is fine.+ let source = document_with(20, 100);+ assert!(parse(source.as_bytes(), Options::default()).errors.is_empty());++ // One whose elements each get hundreds of attributes they don't spell out grows with the square of its size.+ let source = document_with(500, 2000);+ let document = parse(source.as_bytes(), Options::default());+ let error = document.errors.first().expect("the document is refused");+ assert!(error.fatal);+ assert_eq!(error.message, "Maximum entity amplification factor exceeded");+ assert!(document.tape.len() < 200_000, "{} rows", document.tape.len());++ // So does one whose elements each get a single attribute with a very long name and no value to speak of.+ let source = format!(+ "<!DOCTYPE a [<!ATTLIST e {} CDATA ''>]><a>{}</a>",+ "n".repeat(100_000),+ "<e/>".repeat(10_000)+ );+ let document = parse(source.as_bytes(), Options::default());+ let error = document.errors.first().expect("the document is refused");+ assert_eq!(error.message, "Maximum entity amplification factor exceeded");++ // A message that quotes a name the error isn't at doesn't quote all of a very long one.+ let source = format!("<{} p:a='' p:b=''/>", "e".repeat(100_000));+ let document = parse(source.as_bytes(), Options::default());+ assert_eq!(document.errors.len(), 2);+ assert!(document.errors.iter().all(|error| error.message.len() < 1000));++ // Errors that aren't in the order of their offsets still get their own lines.+ let document = parse(+ b"<!DOCTYPE a SYSTEM 'a.dtd'>\n<a>\n<e a='&b;' p:x=''/>\n<e\n a='&b;' p:x=''/></a>",+ Options::default(),+ );+ let positions: Vec<_> = document.errors.iter().map(|error| (error.line, error.column)).collect();+ assert_eq!(positions, [(3, 7), (3, 1), (5, 5), (4, 1)]);++ // The xml prefix can't be given another namespace by a default either.+ let document = parse(+ b"<!DOCTYPE r [<!ATTLIST r xmlns:xml CDATA 'urn:wrong'>]><r/>",+ Options::default(),+ );+ let errors: Vec<_> = document+ .errors+ .iter()+ .map(|error| (error.message.as_str(), error.fatal))+ .collect();+ assert_eq!(errors, [("xml namespace prefix mapped to wrong URI", false)]);++ // An undeclared entity that may be declared where the parser doesn't read is reported, and parsing goes on.+ let document = parse(b"<!DOCTYPE a SYSTEM 'a.dtd'><a>&b;</a>", Options::default());+ let errors: Vec<_> = document+ .errors+ .iter()+ .map(|error| (error.message.as_str(), error.fatal))+ .collect();+ assert_eq!(errors, [("Entity 'b' not defined", false)]);+}