use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TextPos {
pub row: u32,
pub col: u32,
}
impl TextPos {
#[must_use]
pub const fn new(row: u32, col: u32) -> Self {
Self { row, col }
}
#[must_use]
pub fn at(text: &str, offset: usize) -> Self {
let before = text.as_bytes().get(..offset).unwrap_or(text.as_bytes());
let line_start = memchr::memrchr(b'\n', before).map_or(0, |i| i + 1);
let rows = memchr::memchr_iter(b'\n', before).count();
let cols = before[line_start..]
.iter()
.filter(|&&b| b & 0xC0 != 0x80)
.count();
Self {
row: saturating_u32(rows.saturating_add(1)),
col: saturating_u32(cols.saturating_add(1)),
}
}
}
fn saturating_u32(n: usize) -> u32 {
u32::try_from(n).unwrap_or(u32::MAX)
}
impl fmt::Display for TextPos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.row, self.col)
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Error {
InvalidXmlPrefixUri(TextPos),
UnexpectedXmlUri(TextPos),
UnexpectedXmlnsUri(TextPos),
InvalidElementNamePrefix(TextPos),
DuplicatedNamespace(String, TextPos),
UnknownNamespace(String, TextPos),
UnexpectedCloseTag {
expected: String,
actual: String,
pos: TextPos,
},
UnknownEntityReference(String, TextPos),
MalformedEntityReference(TextPos),
DuplicatedAttribute(String, TextPos),
NoRootNode,
UnclosedRootNode,
UnexpectedDeclaration(TextPos),
DtdDetected,
NodesLimitReached,
AttributesLimitReached,
NamespacesLimitReached,
InvalidName(TextPos),
NonXmlChar(char, TextPos),
InvalidChar {
expected: u8,
actual: u8,
pos: TextPos,
},
ExpectedChar {
expected: &'static str,
actual: u8,
pos: TextPos,
},
InvalidString(&'static str, TextPos),
InvalidComment(TextPos),
InvalidCharacterData(TextPos),
UnknownToken(TextPos),
UnexpectedEndOfStream,
InvalidCharacterReference(TextPos),
InvalidPiTarget(TextPos),
PiWithoutWhitespace(TextPos),
InvalidXmlDeclaration(&'static str, TextPos),
InvalidQName(TextPos),
EmptyPrefixedNamespace(String, TextPos),
XmlnsPrefixDeclared(TextPos),
DuplicatedNamespaceDeclaration(String, TextPos),
PrefixedXmlnsAttribute(String, TextPos),
DepthLimitReached,
}
impl Error {
#[must_use]
pub fn pos(&self) -> TextPos {
match self {
Self::InvalidXmlPrefixUri(pos)
| Self::UnexpectedXmlUri(pos)
| Self::UnexpectedXmlnsUri(pos)
| Self::InvalidElementNamePrefix(pos)
| Self::DuplicatedNamespace(_, pos)
| Self::UnknownNamespace(_, pos)
| Self::UnexpectedCloseTag { pos, .. }
| Self::UnknownEntityReference(_, pos)
| Self::MalformedEntityReference(pos)
| Self::DuplicatedAttribute(_, pos)
| Self::UnexpectedDeclaration(pos)
| Self::InvalidName(pos)
| Self::NonXmlChar(_, pos)
| Self::InvalidChar { pos, .. }
| Self::ExpectedChar { pos, .. }
| Self::InvalidString(_, pos)
| Self::InvalidComment(pos)
| Self::InvalidCharacterData(pos)
| Self::UnknownToken(pos)
| Self::InvalidCharacterReference(pos)
| Self::InvalidPiTarget(pos)
| Self::PiWithoutWhitespace(pos)
| Self::InvalidXmlDeclaration(_, pos)
| Self::InvalidQName(pos)
| Self::EmptyPrefixedNamespace(_, pos)
| Self::XmlnsPrefixDeclared(pos)
| Self::DuplicatedNamespaceDeclaration(_, pos)
| Self::PrefixedXmlnsAttribute(_, pos) => *pos,
Self::NoRootNode
| Self::UnclosedRootNode
| Self::DtdDetected
| Self::NodesLimitReached
| Self::AttributesLimitReached
| Self::NamespacesLimitReached
| Self::UnexpectedEndOfStream
| Self::DepthLimitReached => TextPos::new(1, 1),
}
}
}
impl fmt::Display for Error {
#[expect(clippy::too_many_lines, reason = "one message per error, in one place")]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidXmlPrefixUri(pos) => {
write!(f, "'xml' namespace prefix mapped to wrong URI at {pos}")
}
Self::UnexpectedXmlUri(pos) => write!(
f,
"the 'xml' namespace URI is used for not 'xml' prefix at {pos}"
),
Self::UnexpectedXmlnsUri(pos) => write!(
f,
"the 'xmlns' URI is used at {pos}, but it must not be declared"
),
Self::InvalidElementNamePrefix(pos) => {
write!(f, "the 'xmlns' prefix is used at {pos}, but it must not be")
}
Self::DuplicatedNamespace(name, pos) => {
write!(f, "namespace '{name}' at {pos} is already defined")
}
Self::UnknownNamespace(name, pos) => {
write!(f, "an unknown namespace prefix '{name}' at {pos}")
}
Self::UnexpectedCloseTag {
expected,
actual,
pos,
} => write!(f, "expected '{expected}' tag, not '{actual}' at {pos}"),
Self::UnknownEntityReference(name, pos) => {
write!(f, "unknown entity reference '{name}' at {pos}")
}
Self::MalformedEntityReference(pos) => {
write!(f, "malformed entity reference at {pos}")
}
Self::DuplicatedAttribute(name, pos) => {
write!(f, "attribute '{name}' at {pos} is already defined")
}
Self::NoRootNode => f.write_str("the document does not have a root node"),
Self::UnclosedRootNode => f.write_str("the root node was opened but never closed"),
Self::UnexpectedDeclaration(pos) => write!(f, "unexpected XML declaration at {pos}"),
Self::DtdDetected => f.write_str("XML with DTD detected"),
Self::NodesLimitReached => f.write_str("nodes limit reached"),
Self::AttributesLimitReached => f.write_str("more than 2^32 attributes were parsed"),
Self::NamespacesLimitReached => {
f.write_str("more than 2^16 unique namespaces were parsed")
}
Self::InvalidName(pos) => write!(f, "invalid name token at {pos}"),
Self::NonXmlChar(c, pos) => write!(f, "a non-XML character {c:?} found at {pos}"),
Self::InvalidChar {
expected,
actual,
pos,
} => write!(
f,
"expected '{}' not '{}' at {pos}",
char::from(*expected),
char::from(*actual)
),
Self::ExpectedChar {
expected,
actual,
pos,
} => write!(
f,
"expected {expected} not '{}' at {pos}",
char::from(*actual)
),
Self::InvalidString(expected, pos) => write!(f, "expected '{expected}' at {pos}"),
Self::InvalidComment(pos) => write!(f, "comment at {pos} contains '--'"),
Self::InvalidCharacterData(pos) => {
write!(f, "']]>' at {pos} is not allowed inside a character data")
}
Self::UnknownToken(pos) => write!(f, "unknown token at {pos}"),
Self::UnexpectedEndOfStream => f.write_str("unexpected end of stream"),
Self::InvalidCharacterReference(pos) => write!(
f,
"the character reference at {pos} is not a Unicode scalar value"
),
Self::InvalidPiTarget(pos) => write!(
f,
"the processing instruction target at {pos} is reserved or contains ':'"
),
Self::PiWithoutWhitespace(pos) => write!(
f,
"expected a whitespace between the processing instruction target and its data at {pos}"
),
Self::InvalidXmlDeclaration(reason, pos) => {
write!(f, "invalid XML declaration at {pos}: {reason}")
}
Self::InvalidQName(pos) => write!(f, "a name with an empty prefix at {pos}"),
Self::EmptyPrefixedNamespace(prefix, pos) => write!(
f,
"the prefix '{prefix}' at {pos} is bound to an empty namespace name"
),
Self::XmlnsPrefixDeclared(pos) => {
write!(
f,
"the 'xmlns' prefix is declared at {pos}, but it must not be"
)
}
Self::DuplicatedNamespaceDeclaration(name, pos) => {
write!(
f,
"namespace declaration '{name}' at {pos} is already defined"
)
}
Self::PrefixedXmlnsAttribute(name, pos) => write!(
f,
"attribute '{name}' at {pos}: a prefixed attribute named 'xmlns' is not supported"
),
Self::DepthLimitReached => f.write_str("elements nested deeper than the limit"),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positions_count_lines_and_characters() {
let text = "ab\n\u{e9}cd\r\nx";
assert_eq!(TextPos::at(text, 0), TextPos::new(1, 1));
assert_eq!(TextPos::at(text, 2), TextPos::new(1, 3));
assert_eq!(TextPos::at(text, 3), TextPos::new(2, 1));
assert_eq!(TextPos::at(text, 5), TextPos::new(2, 2));
assert_eq!(TextPos::at(text, 8), TextPos::new(2, 5));
assert_eq!(TextPos::at(text, 9), TextPos::new(3, 1));
assert_eq!(TextPos::at(text, 1000), TextPos::new(3, 2));
assert_eq!(TextPos::new(3, 7).to_string(), "3:7");
}
}