1use std::fmt;
4
5#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
8pub struct TextPos {
9 pub row: u32,
11 pub col: u32,
13}
14
15impl TextPos {
16 #[must_use]
18 pub const fn new(row: u32, col: u32) -> Self {
19 Self { row, col }
20 }
21
22 #[must_use]
25 pub fn at(text: &str, offset: usize) -> Self {
26 let before = text.as_bytes().get(..offset).unwrap_or(text.as_bytes());
27 let line_start = memchr::memrchr(b'\n', before).map_or(0, |i| i + 1);
28 let rows = memchr::memchr_iter(b'\n', before).count();
29 let cols = before[line_start..]
30 .iter()
31 .filter(|&&b| b & 0xC0 != 0x80)
32 .count();
33 Self {
34 row: saturating_u32(rows.saturating_add(1)),
35 col: saturating_u32(cols.saturating_add(1)),
36 }
37 }
38}
39
40fn saturating_u32(n: usize) -> u32 {
41 u32::try_from(n).unwrap_or(u32::MAX)
42}
43
44impl fmt::Display for TextPos {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 write!(f, "{}:{}", self.row, self.col)
47 }
48}
49
50#[derive(Clone, PartialEq, Eq, Hash, Debug)]
60#[non_exhaustive]
61pub enum Error {
62 InvalidXmlPrefixUri(TextPos),
65 UnexpectedXmlUri(TextPos),
68 UnexpectedXmlnsUri(TextPos),
70 InvalidElementNamePrefix(TextPos),
72 DuplicatedNamespace(String, TextPos),
74 UnknownNamespace(String, TextPos),
76 UnexpectedCloseTag {
78 expected: String,
80 actual: String,
82 pos: TextPos,
84 },
85 UnknownEntityReference(String, TextPos),
87 MalformedEntityReference(TextPos),
89 DuplicatedAttribute(String, TextPos),
91 NoRootNode,
93 UnclosedRootNode,
95 UnexpectedDeclaration(TextPos),
97 DtdDetected,
100 NodesLimitReached,
102 AttributesLimitReached,
104 NamespacesLimitReached,
106 InvalidName(TextPos),
108 NonXmlChar(char, TextPos),
110 InvalidChar {
112 expected: u8,
114 actual: u8,
116 pos: TextPos,
118 },
119 ExpectedChar {
121 expected: &'static str,
123 actual: u8,
125 pos: TextPos,
127 },
128 InvalidString(&'static str, TextPos),
130 InvalidComment(TextPos),
132 InvalidCharacterData(TextPos),
134 UnknownToken(TextPos),
136 UnexpectedEndOfStream,
138 InvalidCharacterReference(TextPos),
141 InvalidPiTarget(TextPos),
143 PiWithoutWhitespace(TextPos),
145 InvalidXmlDeclaration(&'static str, TextPos),
148 InvalidQName(TextPos),
150 EmptyPrefixedNamespace(String, TextPos),
152 XmlnsPrefixDeclared(TextPos),
154 DuplicatedNamespaceDeclaration(String, TextPos),
157 PrefixedXmlnsAttribute(String, TextPos),
159 DepthLimitReached,
161 UnsupportedEncoding(String),
165 EncodingMismatch {
168 found: &'static str,
170 declared: String,
172 },
173 InvalidEncodedBytes {
175 encoding: &'static str,
177 pos: TextPos,
179 },
180}
181
182impl Error {
183 #[must_use]
185 pub fn pos(&self) -> TextPos {
186 match self {
187 Self::InvalidXmlPrefixUri(pos)
188 | Self::UnexpectedXmlUri(pos)
189 | Self::UnexpectedXmlnsUri(pos)
190 | Self::InvalidElementNamePrefix(pos)
191 | Self::DuplicatedNamespace(_, pos)
192 | Self::UnknownNamespace(_, pos)
193 | Self::UnexpectedCloseTag { pos, .. }
194 | Self::UnknownEntityReference(_, pos)
195 | Self::MalformedEntityReference(pos)
196 | Self::DuplicatedAttribute(_, pos)
197 | Self::UnexpectedDeclaration(pos)
198 | Self::InvalidName(pos)
199 | Self::NonXmlChar(_, pos)
200 | Self::InvalidChar { pos, .. }
201 | Self::ExpectedChar { pos, .. }
202 | Self::InvalidString(_, pos)
203 | Self::InvalidComment(pos)
204 | Self::InvalidCharacterData(pos)
205 | Self::UnknownToken(pos)
206 | Self::InvalidCharacterReference(pos)
207 | Self::InvalidPiTarget(pos)
208 | Self::PiWithoutWhitespace(pos)
209 | Self::InvalidXmlDeclaration(_, pos)
210 | Self::InvalidQName(pos)
211 | Self::EmptyPrefixedNamespace(_, pos)
212 | Self::XmlnsPrefixDeclared(pos)
213 | Self::DuplicatedNamespaceDeclaration(_, pos)
214 | Self::PrefixedXmlnsAttribute(_, pos)
215 | Self::InvalidEncodedBytes { pos, .. } => *pos,
216 Self::NoRootNode
217 | Self::UnclosedRootNode
218 | Self::DtdDetected
219 | Self::NodesLimitReached
220 | Self::AttributesLimitReached
221 | Self::NamespacesLimitReached
222 | Self::UnexpectedEndOfStream
223 | Self::DepthLimitReached
224 | Self::UnsupportedEncoding(_)
225 | Self::EncodingMismatch { .. } => TextPos::new(1, 1),
226 }
227 }
228}
229
230impl fmt::Display for Error {
231 #[expect(clippy::too_many_lines, reason = "one message per error, in one place")]
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233 match self {
234 Self::InvalidXmlPrefixUri(pos) => {
235 write!(f, "'xml' namespace prefix mapped to wrong URI at {pos}")
236 }
237 Self::UnexpectedXmlUri(pos) => write!(
238 f,
239 "the 'xml' namespace URI is used for not 'xml' prefix at {pos}"
240 ),
241 Self::UnexpectedXmlnsUri(pos) => write!(
242 f,
243 "the 'xmlns' URI is used at {pos}, but it must not be declared"
244 ),
245 Self::InvalidElementNamePrefix(pos) => {
246 write!(f, "the 'xmlns' prefix is used at {pos}, but it must not be")
247 }
248 Self::DuplicatedNamespace(name, pos) => {
249 write!(f, "namespace '{name}' at {pos} is already defined")
250 }
251 Self::UnknownNamespace(name, pos) => {
252 write!(f, "an unknown namespace prefix '{name}' at {pos}")
253 }
254 Self::UnexpectedCloseTag {
255 expected,
256 actual,
257 pos,
258 } => write!(f, "expected '{expected}' tag, not '{actual}' at {pos}"),
259 Self::UnknownEntityReference(name, pos) => {
260 write!(f, "unknown entity reference '{name}' at {pos}")
261 }
262 Self::MalformedEntityReference(pos) => {
263 write!(f, "malformed entity reference at {pos}")
264 }
265 Self::DuplicatedAttribute(name, pos) => {
266 write!(f, "attribute '{name}' at {pos} is already defined")
267 }
268 Self::NoRootNode => f.write_str("the document does not have a root node"),
269 Self::UnclosedRootNode => f.write_str("the root node was opened but never closed"),
270 Self::UnexpectedDeclaration(pos) => write!(f, "unexpected XML declaration at {pos}"),
271 Self::DtdDetected => f.write_str("XML with DTD detected"),
272 Self::NodesLimitReached => f.write_str("nodes limit reached"),
273 Self::AttributesLimitReached => f.write_str("more than 2^32 attributes were parsed"),
274 Self::NamespacesLimitReached => {
275 f.write_str("more than 2^16 unique namespaces were parsed")
276 }
277 Self::InvalidName(pos) => write!(f, "invalid name token at {pos}"),
278 Self::NonXmlChar(c, pos) => write!(f, "a non-XML character {c:?} found at {pos}"),
279 Self::InvalidChar {
280 expected,
281 actual,
282 pos,
283 } => write!(
284 f,
285 "expected '{}' not '{}' at {pos}",
286 char::from(*expected),
287 char::from(*actual)
288 ),
289 Self::ExpectedChar {
290 expected,
291 actual,
292 pos,
293 } => write!(
294 f,
295 "expected {expected} not '{}' at {pos}",
296 char::from(*actual)
297 ),
298 Self::InvalidString(expected, pos) => write!(f, "expected '{expected}' at {pos}"),
299 Self::InvalidComment(pos) => write!(f, "comment at {pos} contains '--'"),
300 Self::InvalidCharacterData(pos) => {
301 write!(f, "']]>' at {pos} is not allowed inside a character data")
302 }
303 Self::UnknownToken(pos) => write!(f, "unknown token at {pos}"),
304 Self::UnexpectedEndOfStream => f.write_str("unexpected end of stream"),
305 Self::InvalidCharacterReference(pos) => write!(
306 f,
307 "the character reference at {pos} is not a Unicode scalar value"
308 ),
309 Self::InvalidPiTarget(pos) => write!(
310 f,
311 "the processing instruction target at {pos} is reserved or contains ':'"
312 ),
313 Self::PiWithoutWhitespace(pos) => write!(
314 f,
315 "expected a whitespace between the processing instruction target and its data at {pos}"
316 ),
317 Self::InvalidXmlDeclaration(reason, pos) => {
318 write!(f, "invalid XML declaration at {pos}: {reason}")
319 }
320 Self::InvalidQName(pos) => write!(f, "a name with an empty prefix at {pos}"),
321 Self::EmptyPrefixedNamespace(prefix, pos) => write!(
322 f,
323 "the prefix '{prefix}' at {pos} is bound to an empty namespace name"
324 ),
325 Self::XmlnsPrefixDeclared(pos) => {
326 write!(
327 f,
328 "the 'xmlns' prefix is declared at {pos}, but it must not be"
329 )
330 }
331 Self::DuplicatedNamespaceDeclaration(name, pos) => {
332 write!(
333 f,
334 "namespace declaration '{name}' at {pos} is already defined"
335 )
336 }
337 Self::PrefixedXmlnsAttribute(name, pos) => write!(
338 f,
339 "attribute '{name}' at {pos}: a prefixed attribute named 'xmlns' is not supported"
340 ),
341 Self::DepthLimitReached => f.write_str("elements nested deeper than the limit"),
342 Self::UnsupportedEncoding(name) => write!(f, "unsupported encoding '{name}'"),
343 Self::EncodingMismatch { found, declared } => write!(
344 f,
345 "{found}, but the XML declaration names the encoding '{declared}'"
346 ),
347 Self::InvalidEncodedBytes { encoding, pos } => {
348 write!(f, "bytes that are not {encoding} at {pos}")
349 }
350 }
351 }
352}
353
354impl std::error::Error for Error {}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn positions_count_lines_and_characters() {
362 let text = "ab\n\u{e9}cd\r\nx";
363 assert_eq!(TextPos::at(text, 0), TextPos::new(1, 1));
364 assert_eq!(TextPos::at(text, 2), TextPos::new(1, 3));
365 assert_eq!(TextPos::at(text, 3), TextPos::new(2, 1));
366 assert_eq!(TextPos::at(text, 5), TextPos::new(2, 2));
367 assert_eq!(TextPos::at(text, 8), TextPos::new(2, 5));
369 assert_eq!(TextPos::at(text, 9), TextPos::new(3, 1));
370 assert_eq!(TextPos::at(text, 1000), TextPos::new(3, 2));
371 assert_eq!(TextPos::new(3, 7).to_string(), "3:7");
372 }
373}