use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use indexmap::IndexMap;
use regex::Regex;
pub(crate) fn is_name_start(cp: char) -> bool {
let cp = cp as u32;
cp == 0x3a || cp == 0x5f || (0x41..=0x5a).contains(&cp)
|| (0x61..=0x7a).contains(&cp)
|| (0xc0..=0xd6).contains(&cp)
|| (0xd8..=0xf6).contains(&cp)
|| (0xf8..=0x2ff).contains(&cp)
|| (0x370..=0x37d).contains(&cp)
|| (0x37f..=0x1fff).contains(&cp)
|| (0x200c..=0x200d).contains(&cp)
|| (0x2070..=0x218f).contains(&cp)
|| (0x2c00..=0x2fef).contains(&cp)
|| (0x3001..=0xd7ff).contains(&cp)
|| (0xf900..=0xfdcf).contains(&cp)
|| (0xfdf0..=0xfffd).contains(&cp)
|| (0x10000..=0xeffff).contains(&cp)
}
pub(crate) fn is_name_char(cp: char) -> bool {
if is_name_start(cp) {
return true;
}
let cp = cp as u32;
cp == 0x2d
|| cp == 0x2e
|| (0x30..=0x39).contains(&cp)
|| cp == 0xb7
|| (0x300..=0x36f).contains(&cp)
|| (0x203f..=0x2040).contains(&cp)
}
pub(crate) fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
}
pub(crate) fn after_char(s: &str, at: usize) -> usize {
if at >= s.len() {
return s.len();
}
s[at..]
.chars()
.next()
.map_or(s.len(), |ch| at + ch.len_utf8())
}
pub(crate) fn read_name(s: &str, start: usize) -> Option<(&str, usize)> {
let mut chars = s[start..].char_indices();
let (_, first) = chars.next()?;
if !is_name_start(first) {
return None;
}
let mut end = start + first.len_utf8();
for (offset, ch) in chars {
if !is_name_char(ch) {
break;
}
end = start + offset + ch.len_utf8();
}
Some((&s[start..end], end))
}
fn read_declaration_name(s: &str, start: usize) -> Option<(&str, usize)> {
let bmp = |ch: char| (ch as u32) <= 0xffff;
let mut chars = s[start..].char_indices();
let (_, first) = chars.next()?;
if !bmp(first) || !is_name_start(first) {
return None;
}
let mut end = start + first.len_utf8();
for (offset, ch) in chars {
if !bmp(ch) || !is_name_char(ch) {
break;
}
end = start + offset + ch.len_utf8();
}
Some((&s[start..end], end))
}
pub(crate) fn check_chars(s: &str) -> Option<&'static str> {
s.bytes()
.any(|byte| byte < 0x20 && !matches!(byte, 0x09 | 0x0a | 0x0d))
.then_some("invalid_xml_char")
}
pub(crate) fn normalise_line_endings(s: &str) -> Cow<'_, str> {
if !s.contains('\r') {
return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\r' {
out.push('\n');
if chars.peek() == Some(&'\n') {
chars.next();
}
} else {
out.push(ch);
}
}
Cow::Owned(out)
}
pub(crate) fn normalise_attr_whitespace(s: &str) -> Cow<'_, str> {
if !s.bytes().any(|byte| matches!(byte, b'\t' | b'\n' | b'\r')) {
return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\t' | '\n' => out.push(' '),
'\r' => {
out.push(' ');
if chars.peek() == Some(&'\n') {
chars.next();
}
}
other => out.push(other),
}
}
Cow::Owned(out)
}
const PREDEFINED: [(&str, &str); 5] = [
("amp", "&"),
("lt", "<"),
("gt", ">"),
("quot", "\""),
("apos", "'"),
];
fn entity_pattern() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"&(#x[0-9a-fA-F]+|#[0-9]+|[A-Za-z_:][A-Za-z0-9_\-.:]*);")
.expect("the entity pattern is a literal and compiles")
})
}
#[derive(Debug, Clone)]
pub(crate) struct EntityDecoder {
base: HashMap<String, String>,
}
impl EntityDecoder {
pub(crate) fn new(custom: &IndexMap<String, String>) -> Self {
let mut base: HashMap<String, String> = PREDEFINED
.iter()
.map(|(name, text)| ((*name).to_string(), (*text).to_string()))
.collect();
for (name, text) in custom {
base.insert(name.clone(), text.clone());
}
EntityDecoder { base }
}
pub(crate) fn declared(&self) -> &HashMap<String, String> {
&self.base
}
pub(crate) fn decode(&self, src: &str, dtd: &HashMap<String, String>) -> String {
let mut seen = HashSet::new();
self.expand(src, dtd, &mut seen)
}
fn expand(
&self,
src: &str,
dtd: &HashMap<String, String>,
seen: &mut HashSet<String>,
) -> String {
if !src.contains('&') {
return src.to_string();
}
let mut out = String::with_capacity(src.len());
let mut last = 0;
for found in entity_pattern().captures_iter(src) {
let whole = found.get(0).expect("a match has a whole");
out.push_str(&src[last..whole.start()]);
last = whole.end();
let reference = &found[1];
if let Some(digits) = reference.strip_prefix('#') {
let code = match digits.strip_prefix('x') {
Some(hex) => u32::from_str_radix(hex, 16),
None => digits.parse::<u32>(),
};
match code {
Ok(code) if code <= 0x10ffff => {
out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
}
_ => out.push_str(whole.as_str()),
}
continue;
}
if let Some(text) = self.base.get(reference) {
out.push_str(text);
continue;
}
match dtd.get(reference) {
Some(text) if !seen.contains(reference) => {
seen.insert(reference.to_string());
let expanded = self.expand(text, dtd, seen);
seen.remove(reference);
out.push_str(&expanded);
}
_ => out.push_str(whole.as_str()),
}
}
out.push_str(&src[last..]);
out
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct EntityDeclState {
pub(crate) external: HashMap<String, String>,
pub(crate) unparsed: HashMap<String, String>,
pub(crate) unread: bool,
}
pub(crate) fn check_entity_refs(
s: &str,
dtd: &HashMap<String, String>,
declared: &HashMap<String, String>,
strict: bool,
entdecl: &EntityDeclState,
in_attr: bool,
) -> Option<&'static str> {
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'&' {
i += 1;
continue;
}
let Some(semi) = s[i + 1..].find(';').map(|at| at + i + 1) else {
return Some("bad_entity_ref");
};
let reference = &s[i + 1..semi];
if reference.is_empty() {
return Some("bad_entity_ref");
}
if let Some(digits) = reference.strip_prefix('#') {
if digits.is_empty() {
return Some("bad_entity_ref");
}
let (hex, digits) = match digits.strip_prefix('x') {
Some(rest) => (true, rest),
None => (false, digits),
};
if digits.is_empty() {
return Some("bad_entity_ref");
}
let valid = digits.chars().all(|ch| {
if hex {
ch.is_ascii_hexdigit()
} else {
ch.is_ascii_digit()
}
});
if !valid {
return Some("bad_entity_ref");
}
} else {
let mut chars = reference.chars();
if !chars.next().is_some_and(is_name_start) || !chars.all(is_name_char) {
return Some("bad_entity_ref");
}
if entdecl.unparsed.contains_key(reference) {
return Some("unparsed_entity_ref");
}
if entdecl.external.contains_key(reference) {
if in_attr {
return Some("external_entity_in_attr");
}
} else if strict
&& !entdecl.unread
&& !declared.contains_key(reference)
&& !dtd.contains_key(reference)
{
return Some("undeclared_entity");
}
}
i = semi + 1;
}
None
}
#[derive(Debug, Default)]
pub(crate) struct DoctypeEntities {
pub(crate) internal: HashMap<String, String>,
pub(crate) external: HashMap<String, String>,
pub(crate) unparsed: HashMap<String, String>,
}
const JS_SPACE: &str =
r"\t\n\x0B\f\r \u{a0}\u{1680}\u{2000}-\u{200a}\u{2028}\u{2029}\u{202f}\u{205f}\u{3000}\u{feff}";
fn ndata_pattern() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(r#"(^|[{JS_SPACE}"'])NDATA([{JS_SPACE}"']|$)"#))
.expect("the NDATA pattern is a literal")
})
}
pub(crate) fn pe_ref_pattern() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"%[A-Za-z_:][A-Za-z0-9_\-.:]*;").expect("the PE reference pattern is a literal")
})
}
pub(crate) fn external_id_pattern() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(
r#"(^|[{JS_SPACE}>])(SYSTEM|PUBLIC)([{JS_SPACE}"'])"#
))
.expect("the ExternalID pattern is a literal")
})
}
pub(crate) fn standalone_yes_pattern() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(&format!(
r#"(?-u:\b)standalone[{JS_SPACE}]*=[{JS_SPACE}]*("yes"|'yes')"#
))
.expect("the standalone pattern is a literal")
})
}
fn skip_space(body: &str, mut at: usize) -> usize {
let bytes = body.as_bytes();
while at < bytes.len() && is_space(bytes[at]) {
at += 1;
}
at
}
pub(crate) fn parse_doctype_entities(body: &str) -> DoctypeEntities {
let mut out = DoctypeEntities::default();
let bytes = body.as_bytes();
let mut i = 0;
while i < body.len() {
let Some(found) = body[i..].find("<!ENTITY") else {
break;
};
let mut j = skip_space(body, i + found + "<!ENTITY".len());
if j < bytes.len() && bytes[j] == b'%' {
i = body[j..].find('>').map_or(body.len(), |end| j + end + 1);
continue;
}
let Some((name, after)) = read_declaration_name(body, j) else {
i = after_char(body, j);
continue;
};
j = skip_space(body, after);
if j < bytes.len() && (bytes[j] == b'"' || bytes[j] == b'\'') {
let quote = bytes[j];
j += 1;
let value_start = j;
while j < bytes.len() && bytes[j] != quote {
j += 1;
}
if j >= bytes.len() {
break;
}
out.internal
.insert(name.to_string(), body[value_start..j].to_string());
i = body[j..].find('>').map_or(body.len(), |end| j + end + 1);
continue;
}
let end = body[j..].find('>').map(|end| j + end);
let tail = &body[j..end.unwrap_or(body.len())];
if tail.starts_with("SYSTEM") || tail.starts_with("PUBLIC") {
if ndata_pattern().is_match(tail) {
out.unparsed.insert(name.to_string(), String::new());
} else {
out.external.insert(name.to_string(), String::new());
}
}
i = end.map_or(body.len(), |end| end + 1);
}
out
}
pub(crate) fn parse_doctype_attlists(body: &str) -> IndexMap<String, IndexMap<String, String>> {
let mut out: IndexMap<String, IndexMap<String, String>> = IndexMap::new();
let bytes = body.as_bytes();
let mut i = 0;
while i < body.len() {
let Some(found) = body[i..].find("<!ATTLIST") else {
break;
};
let mut j = skip_space(body, i + found + "<!ATTLIST".len());
let Some((elem_name, after)) = read_name(body, j) else {
i = after_char(body, j);
continue;
};
j = after;
while j < body.len() {
j = skip_space(body, j);
if j >= body.len() {
break;
}
if bytes[j] == b'>' {
j += 1;
break;
}
let Some((attr_name, after)) = read_name(body, j) else {
j = after_char(body, j);
continue;
};
j = skip_space(body, after);
if j < bytes.len() && bytes[j] == b'(' {
match body[j..].find(')') {
Some(close) => j += close + 1,
None => {
j = body.len();
break;
}
}
} else if body[j..].starts_with("NOTATION") {
j = skip_space(body, j + "NOTATION".len());
if j < bytes.len() && bytes[j] == b'(' {
match body[j..].find(')') {
Some(close) => j += close + 1,
None => {
j = body.len();
break;
}
}
}
} else {
while j < bytes.len() && bytes[j].is_ascii_uppercase() {
j += 1;
}
}
j = skip_space(body, j);
if body[j..].starts_with("#REQUIRED") {
j += "#REQUIRED".len();
continue;
}
if body[j..].starts_with("#IMPLIED") {
j += "#IMPLIED".len();
continue;
}
if body[j..].starts_with("#FIXED") {
j = skip_space(body, j + "#FIXED".len());
}
if j < bytes.len() && (bytes[j] == b'"' || bytes[j] == b'\'') {
let quote = bytes[j];
j += 1;
let value_start = j;
while j < bytes.len() && bytes[j] != quote {
j += 1;
}
if j >= bytes.len() {
break;
}
out.entry(elem_name.to_string())
.or_default()
.insert(attr_name.to_string(), body[value_start..j].to_string());
j += 1;
}
}
i = j;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_are_read_by_character() {
assert_eq!(read_name("<เจมส์>", 1), Some(("เจมส์", 1 + "เจมส์".len())));
assert_eq!(read_name("<1a>", 1), None);
assert_eq!(read_name("a-b.c>", 0), Some(("a-b.c", 5)));
assert_eq!(read_name("", 0), None);
}
#[test]
fn declaration_names_stop_at_the_basic_multilingual_plane() {
assert_eq!(read_declaration_name("a-b.c>", 0), Some(("a-b.c", 5)));
assert_eq!(read_declaration_name("<เจมส์>", 1), read_name("<เจมส์>", 1));
assert_eq!(read_declaration_name("\u{1F600} ", 0), None);
assert_eq!(read_declaration_name("a\u{1F600}b ", 0), Some(("a", 1)));
assert_eq!(read_declaration_name("", 0), None);
assert_eq!(
read_name("\u{1F600} ", 0),
Some(("\u{1F600}", "\u{1F600}".len()))
);
}
#[test]
fn ported_patterns_use_the_javascript_whitespace_class() {
assert!(ndata_pattern().is_match("SYSTEM \"u\"\u{feff}NDATA n"));
assert!(!ndata_pattern().is_match("SYSTEM \"u\"\u{85}NDATA n"));
assert!(ndata_pattern().is_match("SYSTEM \"u\"\u{a0}NDATA n"));
assert!(external_id_pattern().is_match(" d\u{feff}SYSTEM \"u\""));
assert!(!external_id_pattern().is_match(" d\u{85}SYSTEM \"u\""));
assert!(standalone_yes_pattern().is_match("a\u{e9}standalone=\"yes\""));
assert!(!standalone_yes_pattern().is_match("astandalone=\"yes\""));
assert!(standalone_yes_pattern().is_match("standalone\u{feff}=\u{feff}\"yes\""));
assert!(!standalone_yes_pattern().is_match("standalone\u{85}=\"yes\""));
}
#[test]
fn after_char_steps_over_a_whole_character() {
assert_eq!(after_char("é!", 0), 2);
assert_eq!(after_char("a", 0), 1);
assert_eq!(after_char("a", 5), 1);
}
#[test]
fn line_endings_and_attribute_whitespace_normalise() {
assert_eq!(normalise_line_endings("a\r\nb\rc\n"), "a\nb\nc\n");
assert_eq!(normalise_attr_whitespace("a\tb\r\nc\rd\ne"), "a b c d e");
}
#[test]
fn decoder_expands_dtd_entities_with_cycle_detection() {
let decoder = EntityDecoder::new(&IndexMap::new());
let mut dtd = HashMap::new();
dtd.insert("a".to_string(), "&b;".to_string());
dtd.insert("b".to_string(), "&a;x".to_string());
assert_eq!(decoder.decode("&a;", &dtd), "&a;x");
assert_eq!(decoder.decode("😀A&", &dtd), "\u{1F600}A&");
assert_eq!(decoder.decode("�", &dtd), "\u{FFFD}");
assert_eq!(decoder.decode("�", &dtd), "�");
}
#[test]
fn entity_reference_checks() {
let none = HashMap::new();
let decoder = EntityDecoder::new(&IndexMap::new());
let state = EntityDeclState::default();
let check = |s: &str, attr: bool| {
check_entity_refs(s, &none, decoder.declared(), true, &state, attr)
};
assert_eq!(check("a & b", false), None);
assert_eq!(check("a & b", false), Some("bad_entity_ref"));
assert_eq!(check("&", false), Some("bad_entity_ref"));
assert_eq!(check("&nope;", false), Some("undeclared_entity"));
let mut external = EntityDeclState::default();
external.external.insert("e".to_string(), String::new());
assert_eq!(
check_entity_refs("&e;", &none, decoder.declared(), true, &external, true),
Some("external_entity_in_attr")
);
assert_eq!(
check_entity_refs("&e;", &none, decoder.declared(), true, &external, false),
None
);
}
#[test]
fn doctype_declarations_are_mined() {
let subset = r#"<!ENTITY % p SYSTEM "p.ent"><!ENTITY g "G"><!ENTITY e SYSTEM "e.ent"><!ENTITY u SYSTEM "u.gif" NDATA gif><!ATTLIST doc x CDATA "default" y (a|b) #FIXED "b" r CDATA #REQUIRED>"#;
let ents = parse_doctype_entities(subset);
assert_eq!(ents.internal.get("g").map(String::as_str), Some("G"));
assert!(ents.external.contains_key("e"));
assert!(ents.unparsed.contains_key("u"));
assert!(!ents.internal.contains_key("p"));
let atts = parse_doctype_attlists(subset);
assert_eq!(atts["doc"]["x"], "default");
assert_eq!(atts["doc"]["y"], "b");
assert!(!atts["doc"].contains_key("r"));
}
}