soml-lang 0.0.2

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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/*!
The deserializer. It reads from the parsed tree, in which every value and key has its offset, so an error says where in the document it is. `from_value` converts a `Value` into the same tree without offsets, so there is one deserializer for both. `from_str` first reads a document with the deserializer in `stream`, which does not build the whole tree, and which uses this one for each scalar.
*/

pub(crate) mod stream;

use crate::parse::{Kind, Member, Node, Object as NodeObject};
use crate::{Error, Value};
use serde_core::de::value::{BorrowedStrDeserializer, MapDeserializer, StringDeserializer};
use serde_core::de::{
	self, DeserializeSeed, Deserializer, EnumAccess, Expected, IntoDeserializer, MapAccess,
	SeqAccess, Unexpected, VariantAccess, Visitor,
};
use serde_core::forward_to_deserialize_any;
use std::borrow::Cow;

/**
Narrows an `f64` to an `f32` through its shortest decimal, the text a document gives it, because rounding the `f64` again can give the `f32` next to the one that text names. It is exact for text with up to 15 significant digits, which includes every `f32` that is written, so `from_value` agrees with reading the document. A float read from a document is rounded once from its own text instead, which is exact for any number of digits.
*/
fn narrow(value: f64) -> f32 {
	if !value.is_finite() {
		return value as f32;
	}

	zmij::Buffer::new()
		.format_finite(value)
		.parse()
		.expect("zmij writes a valid float")
}

pub(crate) struct NodeDeserializer<'de> {
	pub node: Node<'de>,
	/**
	The document, for the line and column of an error. `None` for a value that did not come from a document.
	*/
	pub source: Option<&'de str>,
}

fn unexpected<'a>(kind: &'a Kind<'_>) -> Unexpected<'a> {
	match kind {
		Kind::Null => Unexpected::Unit,
		Kind::Bool(value) => Unexpected::Bool(*value),
		Kind::Int(value) => Unexpected::Signed(*value),
		Kind::Float(value) => Unexpected::Float(*value),
		Kind::String(value) => Unexpected::Str(value),
		Kind::Instant(_) => Unexpected::Other("an instant"),
		Kind::Duration(_) => Unexpected::Other("a duration"),
		Kind::Array(_) => Unexpected::Seq,
		Kind::Object(_) => Unexpected::Map,
	}
}

impl<'de> NodeDeserializer<'de> {
	/**
	Runs a visit and gives an error without a position the position of this value.
	*/
	pub(crate) fn located<T>(
		self,
		visit: impl FnOnce(Self) -> Result<T, Error>,
	) -> Result<T, Error> {
		let source = self.source;
		let offset = self.node.offset;
		visit(self).map_err(|error| error.or_at(source, offset.get()))
	}

	fn invalid_type(&self, expected: &dyn Expected) -> Error {
		de::Error::invalid_type(unexpected(&self.node.kind), expected)
	}

	fn visit_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		let source = self.source;

		match self.node.kind {
			Kind::Null => visitor.visit_unit(),
			Kind::Bool(value) => visitor.visit_bool(value),
			Kind::Int(value) => visitor.visit_i64(value),
			Kind::Float(value) => visitor.visit_f64(value),
			Kind::String(Cow::Borrowed(value)) => visitor.visit_borrowed_str(value),
			Kind::String(Cow::Owned(value)) => visitor.visit_string(value),
			// serde has no instant or duration type, so these are given as their canonical text. That is what jiff, chrono, and humantime types read, and what `serde_json::Value` can hold.
			// TODO: When serde lets a format choose its own buffer type (https://github.com/serde-rs/serde/pull/2912), buffer the `Node` itself, so that `#[serde(flatten)]`, untagged enums, and internally tagged enums keep instants, durations, positions, and exact floats. Then remove that limitation from the readme and the crate docs.
			Kind::Instant(value) => visitor.visit_string(value.to_string()),
			Kind::Duration(value) => visitor.visit_string(value.to_string()),
			Kind::Array(items) => {
				let count = items.len();
				let mut sequence = SeqDeserializer {
					items: items.into_iter(),
					source,
				};

				let value = visitor.visit_seq(&mut sequence)?;

				// A visitor that stops early, such as a tuple's, would otherwise drop the rest silently.
				if sequence.items.len() > 0 {
					return Err(de::Error::invalid_length(
						count,
						&"fewer items in the array",
					));
				}

				Ok(value)
			}
			Kind::Object(object) => {
				let count = object.members.len();
				let mut map = ObjectDeserializer::new(object, source);
				let value = visitor.visit_map(&mut map)?;

				if map.value.is_some() || map.members.len() > 0 {
					return Err(de::Error::invalid_length(
						count,
						&"fewer members in the object",
					));
				}

				Ok(value)
			}
		}
	}

	/**
	The borrowed native token, or its canonical text for a value without source text.
	*/
	fn text(&self, value: &impl std::fmt::Display) -> Cow<'de, str> {
		self.source_text()
			.map_or_else(|| Cow::Owned(value.to_string()), Cow::Borrowed)
	}

	/**
	Reads a `Value`, which keeps an instant and a duration as themselves.
	*/
	fn visit_value<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		match self.node.kind {
			Kind::Instant(value) => visitor.visit_enum(TokenEnum {
				name: crate::instant::TOKEN,
				text: self.text(&value),
			}),
			Kind::Duration(value) => visitor.visit_enum(TokenEnum {
				name: crate::duration::TOKEN,
				text: self.text(&value),
			}),
			_ => self.visit_any(visitor),
		}
	}

	/**
	The text of the value in the document, or `None` for a value that did not come from a document.
	*/
	fn source_text(&self) -> Option<&'de str> {
		Some(&self.source?[self.node.offset.get()?..self.node.end])
	}

	fn visit_float<V: Visitor<'de>>(self, visitor: V, is_f32: bool) -> Result<V::Value, Error> {
		match self.node.kind {
			// An int reads into a float only when the float holds it exactly.
			Kind::Int(value) => {
				let magnitude = value.unsigned_abs();
				// Only significant binary digits require precision. Zero has no significant digits, and this also handles i64::MIN without overflow.
				let significant_bits = u64::BITS
					.saturating_sub(magnitude.leading_zeros() + magnitude.trailing_zeros());
				let precision = if is_f32 {
					f32::MANTISSA_DIGITS
				} else {
					f64::MANTISSA_DIGITS
				};
				if significant_bits > precision {
					return Err(Error::data(format!(
						"The int {value} cannot be converted to a float exactly"
					)));
				}

				visitor.visit_f64(value as f64)
			}
			Kind::Float(value) if is_f32 => {
				let float = self.source_text().map_or_else(
					|| narrow(value),
					|text| {
						crate::scalar::without_underscores(text)
							.parse()
							.expect("a SOML float is a valid Rust float")
					},
				);

				// Zero has one value whatever its sign.
				visitor.visit_f32(if float == 0.0 { 0.0 } else { float })
			}
			_ => self.visit_if(
				|kind| !matches!(kind, Kind::Instant(_) | Kind::Duration(_)),
				visitor,
			),
		}
	}

	/**
	Visits the value when it is of a kind the caller accepts, and gives a type error otherwise.
	*/
	fn visit_if<V: Visitor<'de>>(
		self,
		is_accepted: impl FnOnce(&Kind<'_>) -> bool,
		visitor: V,
	) -> Result<V::Value, Error> {
		if is_accepted(&self.node.kind) {
			self.visit_any(visitor)
		} else {
			Err(self.invalid_type(&visitor))
		}
	}

	/**
	An instant or a duration for `soml::Instant` or `soml::Duration`, which reads only from that type, never from a string.
	*/
	fn visit_token<V: Visitor<'de>>(self, name: &str, visitor: V) -> Result<V::Value, Error> {
		match (name, &self.node.kind) {
			(crate::instant::TOKEN, Kind::Instant(value)) => self.visit_text(value, visitor),
			(crate::duration::TOKEN, Kind::Duration(value)) => self.visit_text(value, visitor),
			(crate::instant::TOKEN, _) => Err(self.invalid_type(&"an instant")),
			_ => Err(self.invalid_type(&"a duration")),
		}
	}

	/**
	Gives an instant or a duration as its text: the text in the document, which needs no copy, or else its canonical text.
	*/
	fn visit_text<V: Visitor<'de>>(
		&self,
		value: &impl std::fmt::Display,
		visitor: V,
	) -> Result<V::Value, Error> {
		match self.text(value) {
			Cow::Borrowed(text) => visitor.visit_borrowed_str(text),
			Cow::Owned(text) => visitor.visit_string(text),
		}
	}

	/**
	A SOML duration for a `std::time::Duration`, which serde reads as a struct with `secs` and `nanos`.
	*/
	fn visit_std_duration<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		let Kind::Duration(duration) = self.node.kind else {
			return self.visit_if(|kind| matches!(kind, Kind::Object(_)), visitor);
		};

		let duration = std::time::Duration::try_from(duration)?;

		visitor.visit_map(MapDeserializer::new(
			[
				("secs", duration.as_secs()),
				("nanos", u64::from(duration.subsec_nanos())),
			]
			.into_iter(),
		))
	}

	fn visit_enum<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		let source = self.source;

		match self.node.kind {
			Kind::String(Cow::Borrowed(variant)) => {
				visitor.visit_enum(BorrowedStrDeserializer::new(variant))
			}
			Kind::String(Cow::Owned(variant)) => {
				visitor.visit_enum(StringDeserializer::new(variant))
			}
			Kind::Object(object) if object.members.len() == 1 => {
				let (key, member) = object
					.members
					.into_iter()
					.next()
					.expect("the object has one member");

				visitor.visit_enum(VariantDeserializer {
					key,
					member,
					source,
				})
			}
			_ => Err(self
				.invalid_type(&"an enum variant, which is a string, or an object with one member")),
		}
	}
}

/**
A bool or an integer type. `visit_any` gives an instant or a duration as its text, for types that read text, so these name the instant or the duration in their type error instead.
*/
macro_rules! deserialize_scalar {
	($($method:ident)*) => {
		$(
			fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
				self.located(|this| this.visit_if(|kind| !matches!(kind, Kind::Instant(_) | Kind::Duration(_)), visitor))
			}
		)*
	};
}

impl<'de> Deserializer<'de> for NodeDeserializer<'de> {
	type Error = Error;

	fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| this.visit_any(visitor))
	}

	fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| this.visit_float(visitor, true))
	}

	fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| this.visit_float(visitor, false))
	}

	fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.deserialize_str(visitor)
	}

	fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| {
			this.visit_if(
				|kind| matches!(kind, Kind::String(_) | Kind::Instant(_) | Kind::Duration(_)),
				visitor,
			)
		})
	}

	fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.deserialize_str(visitor)
	}

	fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| {
			this.visit_if(
				|kind| matches!(kind, Kind::String(_) | Kind::Array(_)),
				visitor,
			)
		})
	}

	fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.deserialize_bytes(visitor)
	}

	fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		if matches!(self.node.kind, Kind::Null) {
			return visitor.visit_none();
		}

		visitor.visit_some(self)
	}

	fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| match this.node.kind {
			Kind::Null => visitor.visit_unit(),
			_ => Err(this.invalid_type(&visitor)),
		})
	}

	fn deserialize_unit_struct<V: Visitor<'de>>(
		self,
		_name: &'static str,
		visitor: V,
	) -> Result<V::Value, Error> {
		self.deserialize_unit(visitor)
	}

	fn deserialize_newtype_struct<V: Visitor<'de>>(
		self,
		name: &'static str,
		visitor: V,
	) -> Result<V::Value, Error> {
		match name {
			crate::value::TOKEN => self.located(|this| this.visit_value(visitor)),
			crate::spanned::TOKEN => visitor.visit_map(SpannedDeserializer {
				span: self.node.offset.get().map(|start| (start, self.node.end)),
				value: Some(self),
				step: 0,
			}),
			crate::instant::TOKEN | crate::duration::TOKEN => {
				self.located(|this| this.visit_token(name, visitor))
			}
			_ => visitor.visit_newtype_struct(self),
		}
	}

	fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| this.visit_if(|kind| matches!(kind, Kind::Array(_)), visitor))
	}

	fn deserialize_tuple<V: Visitor<'de>>(
		self,
		_length: usize,
		visitor: V,
	) -> Result<V::Value, Error> {
		self.deserialize_seq(visitor)
	}

	fn deserialize_tuple_struct<V: Visitor<'de>>(
		self,
		_name: &'static str,
		_length: usize,
		visitor: V,
	) -> Result<V::Value, Error> {
		self.deserialize_seq(visitor)
	}

	fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.located(|this| this.visit_if(|kind| matches!(kind, Kind::Object(_)), visitor))
	}

	fn deserialize_struct<V: Visitor<'de>>(
		mut self,
		name: &'static str,
		fields: &'static [&'static str],
		visitor: V,
	) -> Result<V::Value, Error> {
		// The shape serde gives `std::time::Duration`, in any field order, as the writer recognizes it.
		if name == "Duration"
			&& fields.len() == 2
			&& fields.contains(&"secs")
			&& fields.contains(&"nanos")
		{
			return self.located(|this| this.visit_std_duration(visitor));
		}

		// An adjacently tagged enum asks for its tag and its content, in that order, and buffers the content when it comes first, which loses its SOML type and its position.
		if let [tag, content] = fields
			&& let Kind::Object(object) = &mut self.node.kind
			&& let Some(tag_position) = object.position(tag)
			&& let Some(content_position) = object.position(content)
			&& content_position < tag_position
		{
			object.members.swap(content_position, tag_position);
		}

		self.deserialize_map(visitor)
	}

	fn deserialize_enum<V: Visitor<'de>>(
		self,
		_name: &'static str,
		_variants: &'static [&'static str],
		visitor: V,
	) -> Result<V::Value, Error> {
		self.located(|this| this.visit_enum(visitor))
	}

	fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		self.deserialize_str(visitor)
	}

	fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		// A parsed tree is already checked, and a tree from a `Value` has no text to check, so an ignored value needs no work.
		visitor.visit_unit()
	}

	deserialize_scalar! {
		deserialize_bool deserialize_i8 deserialize_i16 deserialize_i32 deserialize_i64 deserialize_i128
		deserialize_u8 deserialize_u16 deserialize_u32 deserialize_u64 deserialize_u128
	}
}

struct SeqDeserializer<'de> {
	items: std::vec::IntoIter<Node<'de>>,
	source: Option<&'de str>,
}

impl<'de> SeqAccess<'de> for SeqDeserializer<'de> {
	type Error = Error;

	fn next_element_seed<T: DeserializeSeed<'de>>(
		&mut self,
		seed: T,
	) -> Result<Option<T::Value>, Error> {
		self.items
			.next()
			.map(|node| {
				// An error that a type makes after reading, such as a check in `#[serde(try_from)]`, is about this item.
				NodeDeserializer {
					node,
					source: self.source,
				}
				.located(|this| seed.deserialize(this))
			})
			.transpose()
	}

	fn size_hint(&self) -> Option<usize> {
		Some(self.items.len())
	}
}

struct ObjectDeserializer<'de> {
	members: std::vec::IntoIter<(Cow<'de, str>, Member<'de>)>,
	value: Option<Node<'de>>,
	source: Option<&'de str>,
}

impl<'de> ObjectDeserializer<'de> {
	fn new(object: NodeObject<'de>, source: Option<&'de str>) -> Self {
		Self {
			members: object.members.into_iter(),
			value: None,
			source,
		}
	}
}

impl<'de> MapAccess<'de> for ObjectDeserializer<'de> {
	type Error = Error;

	fn next_key_seed<K: DeserializeSeed<'de>>(
		&mut self,
		seed: K,
	) -> Result<Option<K::Value>, Error> {
		// Note: Not using map(...).transpose() because it benchmarks slower for map entries.
		let Some((key, member)) = self.members.next() else {
			return Ok(None);
		};

		let key = seed
			.deserialize(KeyDeserializer { key })
			.map_err(|error| error.or_at(self.source, member.key_offset.get()))?;
		self.value = Some(member.value);
		Ok(Some(key))
	}

	fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Error> {
		let node = self
			.value
			.take()
			.expect("serde calls next_key_seed before next_value_seed");

		// An error that a type makes after reading, such as a check in `#[serde(try_from)]`, is about this value.
		NodeDeserializer {
			node,
			source: self.source,
		}
		.located(|this| seed.deserialize(this))
	}

	fn size_hint(&self) -> Option<usize> {
		Some(self.members.len())
	}
}

/**
A map key, which is always a string. It reads into an integer type only from canonical decimal text, such as `404` or `-1`, and into a bool from `true` or `false`.
*/
struct KeyDeserializer<'de> {
	key: Cow<'de, str>,
}

impl KeyDeserializer<'_> {
	/**
	Reads the key as an integer of the smallest serde type that holds it.
	*/
	fn visit_integer<'de, V: Visitor<'de>>(&self, visitor: V) -> Result<V::Value, Error> {
		let key = self.key.as_ref();
		let digits = key.strip_prefix('-').unwrap_or(key);
		let is_canonical = key.len() <= 40
			&& !digits.is_empty()
			&& (digits == "0" || !digits.starts_with('0'))
			&& key != "-0"
			&& digits.bytes().all(|byte| byte.is_ascii_digit());

		if is_canonical {
			if let Ok(value) = key.parse() {
				return visitor.visit_i64(value);
			}

			if key.starts_with('-') {
				if let Ok(value) = key.parse() {
					return visitor.visit_i128(value);
				}
			} else if let Ok(value) = key.parse::<u128>() {
				if let Ok(value) = u64::try_from(value) {
					return visitor.visit_u64(value);
				}
				if let Ok(value) = i128::try_from(value) {
					return visitor.visit_i128(value);
				}
				return visitor.visit_u128(value);
			}
		}

		Err(Error::data(format!(
			"Expected the key “{}” to be an integer in decimal, like 404",
			crate::abbreviate(key, 40)
		)))
	}
}

macro_rules! deserialize_integer_key {
	($($method:ident)*) => {
		$(
			fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
				self.visit_integer(visitor)
			}
		)*
	};
}

impl<'de> Deserializer<'de> for KeyDeserializer<'de> {
	type Error = Error;

	fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		match self.key {
			Cow::Borrowed(key) => visitor.visit_borrowed_str(key),
			Cow::Owned(key) => visitor.visit_string(key),
		}
	}

	deserialize_integer_key! {
		deserialize_i8 deserialize_i16 deserialize_i32 deserialize_i64 deserialize_i128
		deserialize_u8 deserialize_u16 deserialize_u32 deserialize_u64 deserialize_u128
	}

	fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		match self.key.as_ref() {
			"true" => visitor.visit_bool(true),
			"false" => visitor.visit_bool(false),
			key => Err(Error::data(format!(
				"Expected the key “{}” to be true or false",
				crate::abbreviate(key, 40)
			))),
		}
	}

	fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Error> {
		visitor.visit_some(self)
	}

	fn deserialize_newtype_struct<V: Visitor<'de>>(
		self,
		name: &'static str,
		visitor: V,
	) -> Result<V::Value, Error> {
		// A key is a string, and these read only from their own types.
		match name {
			crate::instant::TOKEN => Err(Error::data(
				"A key is a string, so it cannot be read as an instant",
			)),
			crate::duration::TOKEN => Err(Error::data(
				"A key is a string, so it cannot be read as a duration",
			)),
			_ => visitor.visit_newtype_struct(self),
		}
	}

	fn deserialize_enum<V: Visitor<'de>>(
		self,
		_name: &'static str,
		_variants: &'static [&'static str],
		visitor: V,
	) -> Result<V::Value, Error> {
		match self.key {
			Cow::Borrowed(key) => visitor.visit_enum(BorrowedStrDeserializer::new(key)),
			Cow::Owned(key) => visitor.visit_enum(StringDeserializer::new(key)),
		}
	}

	forward_to_deserialize_any! {
		f32 f64 char str string bytes byte_buf unit unit_struct seq tuple tuple_struct map struct identifier ignored_any
	}
}

/**
An enum variant written as an object with one member, `{variant: value}`.
*/
struct VariantDeserializer<'de> {
	key: Cow<'de, str>,
	member: Member<'de>,
	source: Option<&'de str>,
}

impl<'de> EnumAccess<'de> for VariantDeserializer<'de> {
	type Error = Error;
	type Variant = NodeDeserializer<'de>;

	fn variant_seed<V: DeserializeSeed<'de>>(
		self,
		seed: V,
	) -> Result<(V::Value, Self::Variant), Error> {
		let variant = seed
			.deserialize(KeyDeserializer { key: self.key })
			.map_err(|error| error.or_at(self.source, self.member.key_offset.get()))?;

		Ok((
			variant,
			NodeDeserializer {
				node: self.member.value,
				source: self.source,
			},
		))
	}
}

impl<'de> VariantAccess<'de> for NodeDeserializer<'de> {
	type Error = Error;

	fn unit_variant(self) -> Result<(), Error> {
		self.located(|this| match this.node.kind {
			Kind::Null => Ok(()),
			_ => Err(this.invalid_type(&"null for a unit variant")),
		})
	}

	fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Error> {
		self.located(|this| seed.deserialize(this))
	}

	fn tuple_variant<V: Visitor<'de>>(self, _length: usize, visitor: V) -> Result<V::Value, Error> {
		self.deserialize_seq(visitor)
	}

	fn struct_variant<V: Visitor<'de>>(
		self,
		_fields: &'static [&'static str],
		visitor: V,
	) -> Result<V::Value, Error> {
		self.deserialize_map(visitor)
	}
}

/**
An instant or a duration for `Value`'s visitor, as a variant named by its private token, which no other format produces.
*/
struct TokenEnum<'de> {
	name: &'static str,
	text: Cow<'de, str>,
}

impl TokenEnum<'_> {
	/**
	The error for a visitor that reads the variant as anything but the text.
	*/
	#[cold]
	fn not_text() -> Error {
		de::Error::custom("expected the text of an instant or a duration")
	}
}

impl<'de> EnumAccess<'de> for TokenEnum<'de> {
	type Error = Error;
	type Variant = Self;

	fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self), Error> {
		let name: BorrowedStrDeserializer<'_, Error> = BorrowedStrDeserializer::new(self.name);
		Ok((seed.deserialize(name)?, self))
	}
}

impl<'de> VariantAccess<'de> for TokenEnum<'de> {
	type Error = Error;

	fn unit_variant(self) -> Result<(), Error> {
		Err(TokenEnum::not_text())
	}

	fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Error> {
		match self.text {
			Cow::Borrowed(text) => seed.deserialize(BorrowedStrDeserializer::new(text)),
			Cow::Owned(text) => seed.deserialize(StringDeserializer::new(text)),
		}
	}

	fn tuple_variant<V: Visitor<'de>>(
		self,
		_length: usize,
		_visitor: V,
	) -> Result<V::Value, Error> {
		Err(TokenEnum::not_text())
	}

	fn struct_variant<V: Visitor<'de>>(
		self,
		_fields: &'static [&'static str],
		_visitor: V,
	) -> Result<V::Value, Error> {
		Err(TokenEnum::not_text())
	}
}

impl Node<'_> {
	/**
	Converts a parsed tree into a `Value`, directly, without going through serde.
	*/
	pub(crate) fn into_value(self) -> Value {
		match self.kind {
			Kind::Null => Value::Null,
			Kind::Bool(value) => Value::Bool(value),
			Kind::Int(value) => Value::Int(value),
			Kind::Float(value) => Value::Float(value),
			Kind::String(value) => Value::String(value.into_owned()),
			Kind::Instant(value) => Value::Instant(value),
			Kind::Duration(value) => Value::Duration(value),
			Kind::Array(items) => Value::Array(items.into_iter().map(Node::into_value).collect()),
			// Note: Not using unzip because it would allocate two intermediate vectors.
			Kind::Object(object) => Value::Object(
				object
					.members
					.into_iter()
					.map(|(key, member)| (key.into_owned(), member.value.into_value()))
					.collect(),
			),
		}
	}
}

impl From<Value> for Node<'static> {
	fn from(value: Value) -> Self {
		let kind = match value {
			Value::Null => Kind::Null,
			Value::Bool(value) => Kind::Bool(value),
			Value::Int(value) => Kind::Int(value),
			Value::Float(value) => Kind::Float(value),
			Value::String(value) => Kind::String(Cow::Owned(value)),
			Value::Instant(value) => Kind::Instant(value),
			Value::Duration(value) => Kind::Duration(value),
			Value::Array(items) => Kind::Array(items.into_iter().map(Self::from).collect()),
			Value::Object(object) => Kind::Object(NodeObject::new(
				object
					.into_iter()
					.map(|(key, value)| (Cow::Owned(key), Member::new(Self::from(value))))
					.collect(),
			)),
		};

		kind.into()
	}
}

/**
A value with its byte range for `Spanned`, as a map of the start, the end, and the value. The start and the end are left out for a value that did not come from a document. The value is read with the same deserializer, so it keeps its SOML type, such as an instant.
*/
struct SpannedDeserializer<'de> {
	span: Option<(usize, usize)>,
	value: Option<NodeDeserializer<'de>>,
	/**
	How many keys have been given.
	*/
	step: usize,
}

impl<'de> MapAccess<'de> for SpannedDeserializer<'de> {
	type Error = Error;

	fn next_key_seed<K: DeserializeSeed<'de>>(
		&mut self,
		seed: K,
	) -> Result<Option<K::Value>, Error> {
		// Without a span, only the value is given.
		if self.span.is_none() && self.step == 0 {
			self.step = 2;
		}

		let key = match self.step {
			0 => crate::spanned::START,
			1 => crate::spanned::END,
			2 => crate::spanned::VALUE,
			_ => return Ok(None),
		};

		self.step += 1;
		seed.deserialize(BorrowedStrDeserializer::new(key))
			.map(Some)
	}

	fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Error> {
		let (start, end) = self.span.unwrap_or_default();

		// `next_key_seed` already moved `step` past the key it gave, so 1 is the start and 2 is the end.
		match self.step {
			1 => seed.deserialize((start as u64).into_deserializer()),
			2 => seed.deserialize((end as u64).into_deserializer()),
			_ => seed.deserialize(
				self.value
					.take()
					.expect("serde calls next_key_seed before next_value_seed"),
			),
		}
	}
}