soml-lang 0.0.3

SOML, a config format for humans: a strict reader, serde support, and a lossless syntax tree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use crate::scalar::{line_end, line_start};
use std::fmt::{self, Display, Write};

/**
An error from reading or writing SOML.

A 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.

Messages replace terminal controls and bidirectional controls with U+FFFD. Tabs stay, and messages other than syntax errors may contain line feeds.

```rust
let error = soml::from_str::<soml::Value>("a: 1\na: 2").unwrap_err();

assert_eq!(error.kind(), soml::ErrorKind::Syntax);
assert_eq!(error.message(), "Duplicate key a");
assert_eq!(error.position(), Some(soml::LineColumn { line: 2, column: 1 }));
assert_eq!(error.to_string(), "Duplicate key a at line 2, column 1");
```
*/
pub struct Error {
	// Boxed, so that a `Result` that holds an `Error` stays small. serde_json measured a larger error type to be substantially slower.
	inner: Box<Inner>,
}

struct Inner {
	kind: ErrorKind,
	message: String,
	position: Option<Position>,
	source: Option<std::io::Error>,
}

/**
What kind of problem an [`Error`] is about.
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
	/**
	The text is not valid SOML: a document, or a date, an instant, or a duration read from text.
	*/
	Syntax,
	/**
	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.
	*/
	Data,
	/**
	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.
	*/
	Write,
	/**
	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).
	*/
	Io,
}

/**
A place in a document's text, as a person counts it: a 1-based line, and a 1-based column in Unicode scalar values.
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LineColumn {
	/**
	The 1-based line.
	*/
	pub line: usize,
	/**
	The 1-based column, counted in Unicode scalar values.
	*/
	pub column: usize,
}

#[derive(Clone, Copy)]
struct Position {
	line_column: LineColumn,
	offset: usize,
}

impl Error {
	/**
	Bounds quoted input before serde formats a type or value mismatch.
	*/
	#[cold]
	fn unexpected(
		kind: &str,
		unexpected: serde_core::de::Unexpected<'_>,
		expected: &dyn serde_core::de::Expected,
	) -> Self {
		if let serde_core::de::Unexpected::Str(text) = unexpected {
			let text = crate::abbreviate(text, 40);
			return Self::data(format!(
				"invalid {kind}: {}, expected {expected}",
				serde_core::de::Unexpected::Str(&text)
			));
		}

		Self::data(format!("invalid {kind}: {unexpected}, expected {expected}"))
	}

	#[cold]
	pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
		// Messages may quote input or come from a custom serde implementation. Keep intentional line feeds except in syntax errors, whose messages quote raw input.
		let mut message = message.into();
		let sanitized = |character| {
			if character == '\n' && kind != ErrorKind::Syntax {
				character
			} else {
				sanitize(character)
			}
		};

		if let Some((start, _)) = message
			.char_indices()
			.find(|&(_, character)| sanitized(character) != character)
		{
			let mut clean = String::with_capacity(message.len());
			clean.push_str(&message[..start]);
			clean.extend(message[start..].chars().map(sanitized));
			message = clean;
		}

		Self {
			inner: Box::new(Inner {
				kind,
				message,
				position: None,
				source: None,
			}),
		}
	}

	#[cold]
	pub(crate) fn syntax(message: impl Into<String>) -> Self {
		Self::new(ErrorKind::Syntax, message)
	}

	/**
	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.
	*/
	#[cold]
	pub(crate) fn data(message: impl Into<String>) -> Self {
		Self::new(ErrorKind::Data, message)
	}

	#[cold]
	pub(crate) fn write(message: impl Into<String>) -> Self {
		Self::new(ErrorKind::Write, message)
	}

	#[cold]
	pub(crate) fn io(error: std::io::Error) -> Self {
		let mut io = Self::new(ErrorKind::Io, error.to_string());
		io.inner.source = Some(error);
		io
	}

	/**
	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.
	*/
	#[cold]
	pub(crate) fn at(message: impl Into<String>, source: &str, offset: usize) -> Self {
		let mut error = Self::syntax(message);
		error.inner.position = Some(Position::locate(source, offset));
		error
	}

	/**
	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`].

	```rust
	#[derive(serde::Deserialize)]
	struct Server {
		port: soml::Spanned<u16>,
	}

	let text = "# The server.\nport: 0";
	let server: Server = soml::from_str(text)?;

	if *server.port == 0 {
		let start = server.port.span().unwrap().start;
		let error = soml::Error::with_position("Port 0 is reserved", text, start);
		assert_eq!(error.to_string(), "Port 0 is reserved at line 2, column 7");
	}
	# Ok::<(), soml::Error>(())
	```
	*/
	#[must_use]
	pub fn with_position(message: impl Into<String>, text: &str, offset: usize) -> Self {
		let mut error = Self::data(message);
		error.inner.position = Some(Position::locate(text, offset));
		error
	}

	/**
	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.
	*/
	#[cold]
	pub(crate) fn or_at(mut self, source: Option<&str>, offset: Option<usize>) -> Self {
		// Note: Not using Option::zip because the condition chain benchmarks cheaper when adding a position.
		if self.inner.position.is_none()
			&& let Some(source) = source
			&& let Some(offset) = offset
		{
			self.inner.position = Some(Position::locate(source, offset));
		}

		self
	}

	/**
	What kind of problem the error is about.
	*/
	#[must_use]
	pub const fn kind(&self) -> ErrorKind {
		self.inner.kind
	}

	/**
	What is wrong, without the position.
	*/
	#[must_use]
	pub const fn message(&self) -> &str {
		self.inner.message.as_str()
	}

	/**
	The line and column of the error, if it is about a place in a document.
	*/
	#[must_use]
	pub const fn position(&self) -> Option<LineColumn> {
		match self.inner.position {
			Some(position) => Some(position.line_column),
			None => None,
		}
	}

	/**
	The 0-based byte offset of the error in the document, if it is about a place in a document.
	*/
	#[must_use]
	pub const fn offset(&self) -> Option<usize> {
		match self.inner.position {
			Some(position) => Some(position.offset),
			None => None,
		}
	}

	/**
	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.

	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.

	```rust
	let text = "name: 'api'\nport: 80\nhost: localhost";
	let error = soml::from_str::<soml::Value>(text).unwrap_err();

	assert_eq!(error.code_frame(text).unwrap(), "  1 | name: 'api'\n  2 | port: 80\n> 3 | host: localhost\n    |       ^");
	```

	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.
	*/
	#[must_use]
	pub fn code_frame(&self, text: &str) -> Option<String> {
		const CONTEXT_LINES: usize = 2;
		let position = self.inner.position?;

		// The text may not be the one the error came from, so the offset is kept inside it.
		let offset = character_start(text, position.offset);

		let line = text.as_bytes()[..offset]
			.iter()
			.filter(|&&byte| byte == b'\n')
			.count() + 1;
		// Note: Not using successors or rsplit because their adapters add work to these short scans.
		let mut starts = [0; CONTEXT_LINES + 1];
		let mut first = CONTEXT_LINES;
		starts[first] = line_start(text.as_bytes(), offset);
		while first > 0 && starts[first] > 0 {
			// The line before ends at the line feed before this one.
			starts[first - 1] = line_start(text.as_bytes(), starts[first] - 1);
			first -= 1;
		}
		let line_starts = &starts[first..];

		let first_line = line + 1 - line_starts.len();
		let gutter_width = line.ilog10() as usize + 1;
		let mut frame = String::with_capacity(384);

		for (index, &line_start) in line_starts.iter().enumerate() {
			let number = first_line + index;
			let is_error_line = number == line;
			let line_end = line_end(text.as_bytes(), line_start);
			let pointer = if is_error_line {
				text[line_start..offset].chars().count()
			} else {
				0
			};
			let (characters, pointer) = clip(&text[line_start..line_end], pointer);
			let marker = if is_error_line { '>' } else { ' ' };

			if index > 0 {
				frame.push('\n');
			}

			write!(frame, "{marker} {number:>gutter_width$} |")
				.expect("writing to a String does not fail");

			if !characters.is_empty() {
				frame.push(' ');
				frame.extend(characters.iter());
			}

			if is_error_line {
				write!(frame, "\n  {:gutter_width$} | ", "")
					.expect("writing to a String does not fail");
				frame.extend(
					characters[..pointer]
						.iter()
						.map(|&character| if character == '\t' { '\t' } else { ' ' }),
				);
				frame.push('^');
			}
		}

		Some(frame)
	}
}

/**
A character that a terminal could act on rather than show, as U+FFFD: a control character other than tab, and a bidirectional control.
*/
pub(crate) const fn sanitize(character: char) -> char {
	let is_bidirectional_control = matches!(character, '\u{61C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}');

	if (character.is_control() && character != '\t') || is_bidirectional_control {
		'\u{FFFD}'
	} else {
		character
	}
}

/**
The 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.
*/
fn clip(line: &str, pointer: usize) -> (Vec<char>, usize) {
	const MAX_LINE_WIDTH: usize = 100;

	let length = line.chars().count();

	if length <= MAX_LINE_WIDTH {
		return (line.chars().map(sanitize).collect(), pointer);
	}

	// The window is centered on the pointer, but it does not go past the end of the line.
	let start = pointer
		.saturating_sub(MAX_LINE_WIDTH / 2)
		.min(length - MAX_LINE_WIDTH);
	let end = start + MAX_LINE_WIDTH;
	let mut clipped = Vec::with_capacity(MAX_LINE_WIDTH + 2);

	if start > 0 {
		clipped.push('…');
	}

	clipped.extend(line.chars().skip(start).take(MAX_LINE_WIDTH).map(sanitize));

	if end < length {
		clipped.push('…');
	}

	// The leading `…` moves the pointer one character to the right.
	let pointer = pointer - start + usize::from(start > 0);
	(clipped, pointer)
}

impl Position {
	/**
	The position of a byte offset. Only called when an error is created, so a document that reads without error never pays for it.
	*/
	fn locate(source: &str, offset: usize) -> Self {
		let offset = character_start(source, offset);

		Self {
			line_column: LineColumn::locate(source, offset),
			offset,
		}
	}
}

/**
A 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.
*/
fn character_start(text: &str, offset: usize) -> usize {
	// Note: Not using split_at_checked because it rejects interior offsets instead of clamping them.
	text.floor_char_boundary(offset)
}

impl LineColumn {
	/**
	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.
	*/
	pub(crate) fn locate(source: &str, offset: usize) -> Self {
		let offset = character_start(source, offset);

		let before = &source.as_bytes()[..offset];
		let line_start = line_start(source.as_bytes(), offset);
		let line = before.iter().filter(|&&byte| byte == b'\n').count() + 1;

		// A UTF-8 continuation byte does not start a scalar value, so counting the other bytes counts the scalar values.
		let column = before[line_start..]
			.iter()
			.filter(|&&byte| byte & 0xC0 != 0x80)
			.count() + 1;

		Self { line, column }
	}
}

/**
Writes `line 2, column 7`.
*/
impl Display for LineColumn {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(formatter, "line {}, column {}", self.line, self.column)
	}
}

impl Display for Error {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self.inner.position {
			Some(position) => write!(
				formatter,
				"{} at {}",
				self.inner.message, position.line_column
			),
			None => formatter.write_str(&self.inner.message),
		}
	}
}

impl fmt::Debug for Error {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut debug = formatter.debug_struct("Error");
		debug.field("kind", &self.inner.kind);
		debug.field("message", &self.inner.message);

		if let Some(position) = self.inner.position {
			debug.field("line", &position.line_column.line);
			debug.field("column", &position.line_column.column);
		}

		debug.finish()
	}
}

impl std::error::Error for Error {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		self.inner
			.source
			.as_ref()
			.map(|error| error as &(dyn std::error::Error + 'static))
	}
}

impl serde_core::de::Error for Error {
	#[cold]
	fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
		let field = crate::abbreviate(field, 40);
		let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_field(
			&field, expected,
		);
		Self::data(error.to_string())
	}

	#[cold]
	fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
		let variant = crate::abbreviate(variant, 40);
		let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_variant(
			&variant, expected,
		);
		Self::data(error.to_string())
	}

	#[cold]
	fn custom<T: Display>(message: T) -> Self {
		Self::data(message.to_string())
	}

	#[cold]
	fn invalid_type(
		unexpected: serde_core::de::Unexpected<'_>,
		expected: &dyn serde_core::de::Expected,
	) -> Self {
		Self::unexpected("type", unexpected, expected)
	}

	#[cold]
	fn invalid_value(
		unexpected: serde_core::de::Unexpected<'_>,
		expected: &dyn serde_core::de::Expected,
	) -> Self {
		Self::unexpected("value", unexpected, expected)
	}
}

impl serde_core::ser::Error for Error {
	#[cold]
	fn custom<T: Display>(message: T) -> Self {
		Self::write(message.to_string())
	}
}