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}
162
163impl Error {
164 #[must_use]
166 pub fn pos(&self) -> TextPos {
167 match self {
168 Self::InvalidXmlPrefixUri(pos)
169 | Self::UnexpectedXmlUri(pos)
170 | Self::UnexpectedXmlnsUri(pos)
171 | Self::InvalidElementNamePrefix(pos)
172 | Self::DuplicatedNamespace(_, pos)
173 | Self::UnknownNamespace(_, pos)
174 | Self::UnexpectedCloseTag { pos, .. }
175 | Self::UnknownEntityReference(_, pos)
176 | Self::MalformedEntityReference(pos)
177 | Self::DuplicatedAttribute(_, pos)
178 | Self::UnexpectedDeclaration(pos)
179 | Self::InvalidName(pos)
180 | Self::NonXmlChar(_, pos)
181 | Self::InvalidChar { pos, .. }
182 | Self::ExpectedChar { pos, .. }
183 | Self::InvalidString(_, pos)
184 | Self::InvalidComment(pos)
185 | Self::InvalidCharacterData(pos)
186 | Self::UnknownToken(pos)
187 | Self::InvalidCharacterReference(pos)
188 | Self::InvalidPiTarget(pos)
189 | Self::PiWithoutWhitespace(pos)
190 | Self::InvalidXmlDeclaration(_, pos)
191 | Self::InvalidQName(pos)
192 | Self::EmptyPrefixedNamespace(_, pos)
193 | Self::XmlnsPrefixDeclared(pos)
194 | Self::DuplicatedNamespaceDeclaration(_, pos)
195 | Self::PrefixedXmlnsAttribute(_, pos) => *pos,
196 Self::NoRootNode
197 | Self::UnclosedRootNode
198 | Self::DtdDetected
199 | Self::NodesLimitReached
200 | Self::AttributesLimitReached
201 | Self::NamespacesLimitReached
202 | Self::UnexpectedEndOfStream
203 | Self::DepthLimitReached => TextPos::new(1, 1),
204 }
205 }
206}
207
208impl fmt::Display for Error {
209 #[expect(clippy::too_many_lines, reason = "one message per error, in one place")]
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 match self {
212 Self::InvalidXmlPrefixUri(pos) => {
213 write!(f, "'xml' namespace prefix mapped to wrong URI at {pos}")
214 }
215 Self::UnexpectedXmlUri(pos) => write!(
216 f,
217 "the 'xml' namespace URI is used for not 'xml' prefix at {pos}"
218 ),
219 Self::UnexpectedXmlnsUri(pos) => write!(
220 f,
221 "the 'xmlns' URI is used at {pos}, but it must not be declared"
222 ),
223 Self::InvalidElementNamePrefix(pos) => {
224 write!(f, "the 'xmlns' prefix is used at {pos}, but it must not be")
225 }
226 Self::DuplicatedNamespace(name, pos) => {
227 write!(f, "namespace '{name}' at {pos} is already defined")
228 }
229 Self::UnknownNamespace(name, pos) => {
230 write!(f, "an unknown namespace prefix '{name}' at {pos}")
231 }
232 Self::UnexpectedCloseTag {
233 expected,
234 actual,
235 pos,
236 } => write!(f, "expected '{expected}' tag, not '{actual}' at {pos}"),
237 Self::UnknownEntityReference(name, pos) => {
238 write!(f, "unknown entity reference '{name}' at {pos}")
239 }
240 Self::MalformedEntityReference(pos) => {
241 write!(f, "malformed entity reference at {pos}")
242 }
243 Self::DuplicatedAttribute(name, pos) => {
244 write!(f, "attribute '{name}' at {pos} is already defined")
245 }
246 Self::NoRootNode => f.write_str("the document does not have a root node"),
247 Self::UnclosedRootNode => f.write_str("the root node was opened but never closed"),
248 Self::UnexpectedDeclaration(pos) => write!(f, "unexpected XML declaration at {pos}"),
249 Self::DtdDetected => f.write_str("XML with DTD detected"),
250 Self::NodesLimitReached => f.write_str("nodes limit reached"),
251 Self::AttributesLimitReached => f.write_str("more than 2^32 attributes were parsed"),
252 Self::NamespacesLimitReached => {
253 f.write_str("more than 2^16 unique namespaces were parsed")
254 }
255 Self::InvalidName(pos) => write!(f, "invalid name token at {pos}"),
256 Self::NonXmlChar(c, pos) => write!(f, "a non-XML character {c:?} found at {pos}"),
257 Self::InvalidChar {
258 expected,
259 actual,
260 pos,
261 } => write!(
262 f,
263 "expected '{}' not '{}' at {pos}",
264 char::from(*expected),
265 char::from(*actual)
266 ),
267 Self::ExpectedChar {
268 expected,
269 actual,
270 pos,
271 } => write!(
272 f,
273 "expected {expected} not '{}' at {pos}",
274 char::from(*actual)
275 ),
276 Self::InvalidString(expected, pos) => write!(f, "expected '{expected}' at {pos}"),
277 Self::InvalidComment(pos) => write!(f, "comment at {pos} contains '--'"),
278 Self::InvalidCharacterData(pos) => {
279 write!(f, "']]>' at {pos} is not allowed inside a character data")
280 }
281 Self::UnknownToken(pos) => write!(f, "unknown token at {pos}"),
282 Self::UnexpectedEndOfStream => f.write_str("unexpected end of stream"),
283 Self::InvalidCharacterReference(pos) => write!(
284 f,
285 "the character reference at {pos} is not a Unicode scalar value"
286 ),
287 Self::InvalidPiTarget(pos) => write!(
288 f,
289 "the processing instruction target at {pos} is reserved or contains ':'"
290 ),
291 Self::PiWithoutWhitespace(pos) => write!(
292 f,
293 "expected a whitespace between the processing instruction target and its data at {pos}"
294 ),
295 Self::InvalidXmlDeclaration(reason, pos) => {
296 write!(f, "invalid XML declaration at {pos}: {reason}")
297 }
298 Self::InvalidQName(pos) => write!(f, "a name with an empty prefix at {pos}"),
299 Self::EmptyPrefixedNamespace(prefix, pos) => write!(
300 f,
301 "the prefix '{prefix}' at {pos} is bound to an empty namespace name"
302 ),
303 Self::XmlnsPrefixDeclared(pos) => {
304 write!(
305 f,
306 "the 'xmlns' prefix is declared at {pos}, but it must not be"
307 )
308 }
309 Self::DuplicatedNamespaceDeclaration(name, pos) => {
310 write!(
311 f,
312 "namespace declaration '{name}' at {pos} is already defined"
313 )
314 }
315 Self::PrefixedXmlnsAttribute(name, pos) => write!(
316 f,
317 "attribute '{name}' at {pos}: a prefixed attribute named 'xmlns' is not supported"
318 ),
319 Self::DepthLimitReached => f.write_str("elements nested deeper than the limit"),
320 }
321 }
322}
323
324impl std::error::Error for Error {}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 #[test]
331 fn positions_count_lines_and_characters() {
332 let text = "ab\n\u{e9}cd\r\nx";
333 assert_eq!(TextPos::at(text, 0), TextPos::new(1, 1));
334 assert_eq!(TextPos::at(text, 2), TextPos::new(1, 3));
335 assert_eq!(TextPos::at(text, 3), TextPos::new(2, 1));
336 assert_eq!(TextPos::at(text, 5), TextPos::new(2, 2));
337 assert_eq!(TextPos::at(text, 8), TextPos::new(2, 5));
339 assert_eq!(TextPos::at(text, 9), TextPos::new(3, 1));
340 assert_eq!(TextPos::at(text, 1000), TextPos::new(3, 2));
341 assert_eq!(TextPos::new(3, 7).to_string(), "3:7");
342 }
343}