Skip to main content

soml/
error.rs

1use crate::scalar::{line_end, line_start};
2use std::fmt::{self, Display, Write};
3
4/**
5An error from reading or writing SOML.
6
7A document that is not valid SOML, a document that does not fit the type it is read into, and a value that SOML cannot represent all give an `Error`. [`kind`](Self::kind) tells them apart. When the error is about a place in a document, it has a line and a column, and [`code_frame`](Self::code_frame) shows that place.
8
9Messages replace terminal controls and bidirectional controls with U+FFFD. Tabs stay, and messages other than syntax errors may contain line feeds.
10
11```rust
12let error = soml::from_str::<soml::Value>("a: 1\na: 2").unwrap_err();
13
14assert_eq!(error.kind(), soml::ErrorKind::Syntax);
15assert_eq!(error.message(), "Duplicate key a");
16assert_eq!(error.position(), Some(soml::LineColumn { line: 2, column: 1 }));
17assert_eq!(error.to_string(), "Duplicate key a at line 2, column 1");
18```
19*/
20pub struct Error {
21	// Boxed, so that a `Result` that holds an `Error` stays small. serde_json measured a larger error type to be substantially slower.
22	inner: Box<Inner>,
23}
24
25struct Inner {
26	kind: ErrorKind,
27	message: String,
28	position: Option<Position>,
29	source: Option<std::io::Error>,
30}
31
32/**
33What kind of problem an [`Error`] is about.
34*/
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum ErrorKind {
38	/**
39	The text is not valid SOML: a document, or a date, an instant, or a duration read from text.
40	*/
41	Syntax,
42	/**
43	Valid SOML that does not fit what it is read into, such as a string for a number field, a value that is out of range for a conversion, or a path that does not fit a document.
44	*/
45	Data,
46	/**
47	A value that cannot be written as SOML, such as NaN or a carriage return, or a [`Document::set`](crate::Document::set) that would make the document invalid.
48	*/
49	Write,
50	/**
51	Reading or writing failed, in [`from_reader`](crate::from_reader) or [`to_writer`](crate::to_writer). The `io::Error` is the error's [`source`](std::error::Error::source).
52	*/
53	Io,
54}
55
56/**
57A place in a document's text, as a person counts it: a 1-based line, and a 1-based column in Unicode scalar values.
58*/
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
60pub struct LineColumn {
61	/**
62	The 1-based line.
63	*/
64	pub line: usize,
65	/**
66	The 1-based column, counted in Unicode scalar values.
67	*/
68	pub column: usize,
69}
70
71#[derive(Clone, Copy)]
72struct Position {
73	line_column: LineColumn,
74	offset: usize,
75}
76
77impl Error {
78	/**
79	Bounds quoted input before serde formats a type or value mismatch.
80	*/
81	#[cold]
82	fn unexpected(
83		kind: &str,
84		unexpected: serde_core::de::Unexpected<'_>,
85		expected: &dyn serde_core::de::Expected,
86	) -> Self {
87		if let serde_core::de::Unexpected::Str(text) = unexpected {
88			let text = crate::abbreviate(text, 40);
89			return Self::data(format!(
90				"invalid {kind}: {}, expected {expected}",
91				serde_core::de::Unexpected::Str(&text)
92			));
93		}
94
95		Self::data(format!("invalid {kind}: {unexpected}, expected {expected}"))
96	}
97
98	#[cold]
99	pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
100		// Messages may quote input or come from a custom serde implementation. Keep intentional line feeds except in syntax errors, whose messages quote raw input.
101		let mut message = message.into();
102		let sanitized = |character| {
103			if character == '\n' && kind != ErrorKind::Syntax {
104				character
105			} else {
106				sanitize(character)
107			}
108		};
109
110		if let Some((start, _)) = message
111			.char_indices()
112			.find(|&(_, character)| sanitized(character) != character)
113		{
114			let mut clean = String::with_capacity(message.len());
115			clean.push_str(&message[..start]);
116			clean.extend(message[start..].chars().map(sanitized));
117			message = clean;
118		}
119
120		Self {
121			inner: Box::new(Inner {
122				kind,
123				message,
124				position: None,
125				source: None,
126			}),
127		}
128	}
129
130	#[cold]
131	pub(crate) fn syntax(message: impl Into<String>) -> Self {
132		Self::new(ErrorKind::Syntax, message)
133	}
134
135	/**
136	A data error. The message can quote the document, such as an unknown key in serde's messages, so its control characters are hidden, as in a syntax error. Line feeds stay, because a message of your own can have more than one line.
137	*/
138	#[cold]
139	pub(crate) fn data(message: impl Into<String>) -> Self {
140		Self::new(ErrorKind::Data, message)
141	}
142
143	#[cold]
144	pub(crate) fn write(message: impl Into<String>) -> Self {
145		Self::new(ErrorKind::Write, message)
146	}
147
148	#[cold]
149	pub(crate) fn io(error: std::io::Error) -> Self {
150		let mut io = Self::new(ErrorKind::Io, error.to_string());
151		io.inner.source = Some(error);
152		io
153	}
154
155	/**
156	A syntax error at a byte offset in `source`. The message can quote the document, so its control characters are hidden, as in a code frame.
157	*/
158	#[cold]
159	pub(crate) fn at(message: impl Into<String>, source: &str, offset: usize) -> Self {
160		let mut error = Self::syntax(message);
161		error.inner.position = Some(Position::locate(source, offset));
162		error
163	}
164
165	/**
166	An error of your own about a place in a document, such as a value that is valid SOML but not valid for your app. Use the byte offset of a [`Spanned`](crate::Spanned) value or of a syntax tree node. An offset past the end of `text` counts as its end. The error's kind is [`ErrorKind::Data`].
167
168	```rust
169	#[derive(serde::Deserialize)]
170	struct Server {
171		port: soml::Spanned<u16>,
172	}
173
174	let text = "# The server.\nport: 0";
175	let server: Server = soml::from_str(text)?;
176
177	if *server.port == 0 {
178		let start = server.port.span().unwrap().start;
179		let error = soml::Error::with_position("Port 0 is reserved", text, start);
180		assert_eq!(error.to_string(), "Port 0 is reserved at line 2, column 7");
181	}
182	# Ok::<(), soml::Error>(())
183	```
184	*/
185	#[must_use]
186	pub fn with_position(message: impl Into<String>, text: &str, offset: usize) -> Self {
187		let mut error = Self::data(message);
188		error.inner.position = Some(Position::locate(text, offset));
189		error
190	}
191
192	/**
193	Gives the error a position, unless it already has one. The innermost position is the most precise one, because it is the value or key the error is about.
194	*/
195	#[cold]
196	pub(crate) fn or_at(mut self, source: Option<&str>, offset: Option<usize>) -> Self {
197		// Note: Not using Option::zip because the condition chain benchmarks cheaper when adding a position.
198		if self.inner.position.is_none()
199			&& let Some(source) = source
200			&& let Some(offset) = offset
201		{
202			self.inner.position = Some(Position::locate(source, offset));
203		}
204
205		self
206	}
207
208	/**
209	What kind of problem the error is about.
210	*/
211	#[must_use]
212	pub const fn kind(&self) -> ErrorKind {
213		self.inner.kind
214	}
215
216	/**
217	What is wrong, without the position.
218	*/
219	#[must_use]
220	pub const fn message(&self) -> &str {
221		self.inner.message.as_str()
222	}
223
224	/**
225	The line and column of the error, if it is about a place in a document.
226	*/
227	#[must_use]
228	pub const fn position(&self) -> Option<LineColumn> {
229		match self.inner.position {
230			Some(position) => Some(position.line_column),
231			None => None,
232		}
233	}
234
235	/**
236	The 0-based byte offset of the error in the document, if it is about a place in a document.
237	*/
238	#[must_use]
239	pub const fn offset(&self) -> Option<usize> {
240		match self.inner.position {
241			Some(position) => Some(position.offset),
242			None => None,
243		}
244	}
245
246	/**
247	Up to three lines of `text` that end at the error, with a caret under its position, for a terminal. Give it the text the error came from. `None` when the error is not about a place in a document.
248
249	A long line is cut to a part around the position, and control characters, bidirectional controls, and other characters a terminal could act on are shown as U+FFFD. Tabs are kept, so the caret lines up whatever the tab width is. The layout is the same as the `codeFrame` of the JS reference implementation, except that a long line is cut by characters rather than by UTF-16 code units.
250
251	```rust
252	let text = "name: 'api'\nport: 80\nhost: localhost";
253	let error = soml::from_str::<soml::Value>(text).unwrap_err();
254
255	assert_eq!(error.code_frame(text).unwrap(), "  1 | name: 'api'\n  2 | port: 80\n> 3 | host: localhost\n    |       ^");
256	```
257
258	For an error from [`from_slice`](crate::from_slice) about bytes that are not UTF-8, use `String::from_utf8_lossy` for the text: it matches the bytes up to the error.
259	*/
260	#[must_use]
261	pub fn code_frame(&self, text: &str) -> Option<String> {
262		const CONTEXT_LINES: usize = 2;
263		let position = self.inner.position?;
264
265		// The text may not be the one the error came from, so the offset is kept inside it.
266		let offset = character_start(text, position.offset);
267
268		let line = text.as_bytes()[..offset]
269			.iter()
270			.filter(|&&byte| byte == b'\n')
271			.count() + 1;
272		// Note: Not using successors or rsplit because their adapters add work to these short scans.
273		let mut starts = [0; CONTEXT_LINES + 1];
274		let mut first = CONTEXT_LINES;
275		starts[first] = line_start(text.as_bytes(), offset);
276		while first > 0 && starts[first] > 0 {
277			// The line before ends at the line feed before this one.
278			starts[first - 1] = line_start(text.as_bytes(), starts[first] - 1);
279			first -= 1;
280		}
281		let line_starts = &starts[first..];
282
283		let first_line = line + 1 - line_starts.len();
284		let gutter_width = line.ilog10() as usize + 1;
285		let mut frame = String::with_capacity(384);
286
287		for (index, &line_start) in line_starts.iter().enumerate() {
288			let number = first_line + index;
289			let is_error_line = number == line;
290			let line_end = line_end(text.as_bytes(), line_start);
291			let pointer = if is_error_line {
292				text[line_start..offset].chars().count()
293			} else {
294				0
295			};
296			let (characters, pointer) = clip(&text[line_start..line_end], pointer);
297			let marker = if is_error_line { '>' } else { ' ' };
298
299			if index > 0 {
300				frame.push('\n');
301			}
302
303			write!(frame, "{marker} {number:>gutter_width$} |")
304				.expect("writing to a String does not fail");
305
306			if !characters.is_empty() {
307				frame.push(' ');
308				frame.extend(characters.iter());
309			}
310
311			if is_error_line {
312				write!(frame, "\n  {:gutter_width$} | ", "")
313					.expect("writing to a String does not fail");
314				frame.extend(
315					characters[..pointer]
316						.iter()
317						.map(|&character| if character == '\t' { '\t' } else { ' ' }),
318				);
319				frame.push('^');
320			}
321		}
322
323		Some(frame)
324	}
325}
326
327/**
328A character that a terminal could act on rather than show, as U+FFFD: a control character other than tab, and a bidirectional control.
329*/
330pub(crate) const fn sanitize(character: char) -> char {
331	let is_bidirectional_control = matches!(character, '\u{61C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}');
332
333	if (character.is_control() && character != '\t') || is_bidirectional_control {
334		'\u{FFFD}'
335	} else {
336		character
337	}
338}
339
340/**
341The characters of a line for a code frame, as [`sanitize`] shows them, cut to a window around the pointer when the line is long, with `…` where it was cut. Returns the characters and the pointer's new position. Only the window is collected, so a long line costs no more memory than a short one.
342*/
343fn clip(line: &str, pointer: usize) -> (Vec<char>, usize) {
344	const MAX_LINE_WIDTH: usize = 100;
345
346	let length = line.chars().count();
347
348	if length <= MAX_LINE_WIDTH {
349		return (line.chars().map(sanitize).collect(), pointer);
350	}
351
352	// The window is centered on the pointer, but it does not go past the end of the line.
353	let start = pointer
354		.saturating_sub(MAX_LINE_WIDTH / 2)
355		.min(length - MAX_LINE_WIDTH);
356	let end = start + MAX_LINE_WIDTH;
357	let mut clipped = Vec::with_capacity(MAX_LINE_WIDTH + 2);
358
359	if start > 0 {
360		clipped.push('…');
361	}
362
363	clipped.extend(line.chars().skip(start).take(MAX_LINE_WIDTH).map(sanitize));
364
365	if end < length {
366		clipped.push('…');
367	}
368
369	// The leading `…` moves the pointer one character to the right.
370	let pointer = pointer - start + usize::from(start > 0);
371	(clipped, pointer)
372}
373
374impl Position {
375	/**
376	The position of a byte offset. Only called when an error is created, so a document that reads without error never pays for it.
377	*/
378	fn locate(source: &str, offset: usize) -> Self {
379		let offset = character_start(source, offset);
380
381		Self {
382			line_column: LineColumn::locate(source, offset),
383			offset,
384		}
385	}
386}
387
388/**
389A byte offset kept inside `text`, at the start of a character: an offset past the end is the end, and an offset inside a character, which an error of your own can have, is the start of that character.
390*/
391fn character_start(text: &str, offset: usize) -> usize {
392	// Note: Not using split_at_checked because it rejects interior offsets instead of clamping them.
393	text.floor_char_boundary(offset)
394}
395
396impl LineColumn {
397	/**
398	The line and column of a byte offset in `source`. An offset past the end counts as the end, and an offset inside a character points at that character.
399	*/
400	pub(crate) fn locate(source: &str, offset: usize) -> Self {
401		let offset = character_start(source, offset);
402
403		let before = &source.as_bytes()[..offset];
404		let line_start = line_start(source.as_bytes(), offset);
405		let line = before.iter().filter(|&&byte| byte == b'\n').count() + 1;
406
407		// A UTF-8 continuation byte does not start a scalar value, so counting the other bytes counts the scalar values.
408		let column = before[line_start..]
409			.iter()
410			.filter(|&&byte| byte & 0xC0 != 0x80)
411			.count() + 1;
412
413		Self { line, column }
414	}
415}
416
417/**
418Writes `line 2, column 7`.
419*/
420impl Display for LineColumn {
421	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
422		write!(formatter, "line {}, column {}", self.line, self.column)
423	}
424}
425
426impl Display for Error {
427	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
428		match self.inner.position {
429			Some(position) => write!(
430				formatter,
431				"{} at {}",
432				self.inner.message, position.line_column
433			),
434			None => formatter.write_str(&self.inner.message),
435		}
436	}
437}
438
439impl fmt::Debug for Error {
440	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
441		let mut debug = formatter.debug_struct("Error");
442		debug.field("kind", &self.inner.kind);
443		debug.field("message", &self.inner.message);
444
445		if let Some(position) = self.inner.position {
446			debug.field("line", &position.line_column.line);
447			debug.field("column", &position.line_column.column);
448		}
449
450		debug.finish()
451	}
452}
453
454impl std::error::Error for Error {
455	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
456		self.inner
457			.source
458			.as_ref()
459			.map(|error| error as &(dyn std::error::Error + 'static))
460	}
461}
462
463impl serde_core::de::Error for Error {
464	#[cold]
465	fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
466		let field = crate::abbreviate(field, 40);
467		let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_field(
468			&field, expected,
469		);
470		Self::data(error.to_string())
471	}
472
473	#[cold]
474	fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
475		let variant = crate::abbreviate(variant, 40);
476		let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_variant(
477			&variant, expected,
478		);
479		Self::data(error.to_string())
480	}
481
482	#[cold]
483	fn custom<T: Display>(message: T) -> Self {
484		Self::data(message.to_string())
485	}
486
487	#[cold]
488	fn invalid_type(
489		unexpected: serde_core::de::Unexpected<'_>,
490		expected: &dyn serde_core::de::Expected,
491	) -> Self {
492		Self::unexpected("type", unexpected, expected)
493	}
494
495	#[cold]
496	fn invalid_value(
497		unexpected: serde_core::de::Unexpected<'_>,
498		expected: &dyn serde_core::de::Expected,
499	) -> Self {
500		Self::unexpected("value", unexpected, expected)
501	}
502}
503
504impl serde_core::ser::Error for Error {
505	#[cold]
506	fn custom<T: Display>(message: T) -> Self {
507		Self::write(message.to_string())
508	}
509}