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
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
use crate::{Date, Duration, Error, Instant};
use serde_core::de::{
	self, Deserialize, Deserializer, EnumAccess, MapAccess, SeqAccess, VariantAccess, Visitor,
};
use serde_core::ser::{Serialize, Serializer};
use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
use std::fmt::{self, Display};
use std::str::FromStr;

/**
A SOML object: members by key.

The order of members is not part of a value in SOML, so an object is a `BTreeMap`. It iterates in canonical order, and two objects with the same members are equal. Keys are compared byte for byte, with no Unicode normalization, as the spec requires.
*/
pub type Object = BTreeMap<String, Value>;

/**
Any SOML value.

```rust
let value: soml::Value = "port: 8080\nhosts: ['a', 'b']".parse()?;

assert_eq!(value.get("port").and_then(soml::Value::as_i64), Some(8080));
assert_eq!(value.get("hosts").and_then(|hosts| hosts.get(1)).and_then(soml::Value::as_str), Some("b"));
# Ok::<(), soml::Error>(())
```

An int and a float are different types, as in the spec: `Value::Int(3)` and `Value::Float(3.0)` are not equal, and `as_f64()` does not convert an int.
*/
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Value {
	/**
	`null`.
	*/
	#[default]
	Null,
	/**
	`true` or `false`.
	*/
	Bool(bool),
	/**
	An int.
	*/
	Int(i64),
	/**
	A float. A float that came from a document is never NaN, and it is never negative zero.
	*/
	Float(f64),
	/**
	A string.
	*/
	String(String),
	/**
	A Gregorian calendar date.
	*/
	Date(Date),
	/**
	An instant.
	*/
	Instant(Instant),
	/**
	A duration.
	*/
	Duration(Duration),
	/**
	An array.
	*/
	Array(Vec<Self>),
	/**
	An object.
	*/
	Object(Object),
}

/**
Something that can index into a `Value`: a key for an object, or a position for an array.
*/
pub trait Index: private::Sealed {
	#[doc(hidden)]
	fn index_into(self, value: &Value) -> Option<&Value>;

	#[doc(hidden)]
	fn index_into_mut(self, value: &mut Value) -> Option<&mut Value>;
}

impl Index for &str {
	fn index_into(self, value: &Value) -> Option<&Value> {
		value.as_object()?.get(self)
	}

	fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
		value.as_object_mut()?.get_mut(self)
	}
}

impl Index for &String {
	fn index_into(self, value: &Value) -> Option<&Value> {
		self.as_str().index_into(value)
	}

	fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
		self.as_str().index_into_mut(value)
	}
}

impl Index for usize {
	fn index_into(self, value: &Value) -> Option<&Value> {
		value.as_array()?.get(self)
	}

	fn index_into_mut(self, value: &mut Value) -> Option<&mut Value> {
		value.as_array_mut()?.get_mut(self)
	}
}

mod private {
	pub trait Sealed {}
	impl Sealed for &str {}
	impl Sealed for &String {}
	impl Sealed for usize {}
}

impl Value {
	/**
	Checks representability without cloning a value or allocating a second tree. `depth` counts surrounding collections.
	*/
	pub(crate) fn check(&self, depth: usize) -> Result<(), Error> {
		match self {
			Self::Float(value) if value.is_nan() => Err(Error::write("NaN is not a SOML value")),
			Self::String(text) => crate::write::check_representable(text, "string"),
			Self::Array(items) => {
				let depth = crate::ser::nested_depth(depth)?;
				for item in items {
					item.check(depth)?;
				}
				Ok(())
			}
			Self::Object(object) => {
				let depth = crate::ser::nested_depth(depth)?;
				for (key, value) in object {
					value.check(depth)?;
					crate::write::check_representable(key, "key")?;
				}
				Ok(())
			}
			_ => Ok(()),
		}
	}

	/**
	The member of an object with this key, or the item of an array at this position. `None` for a missing member or item, and for a value of another type.
	*/
	#[must_use]
	pub fn get(&self, index: impl Index) -> Option<&Self> {
		index.index_into(self)
	}

	/**
	A mutable reference to the member of an object with this key, or the item of an array at this position.
	*/
	pub fn get_mut(&mut self, index: impl Index) -> Option<&mut Self> {
		index.index_into_mut(self)
	}

	/**
	Whether the value is `null`.
	*/
	#[must_use]
	pub const fn is_null(&self) -> bool {
		matches!(self, Self::Null)
	}

	/**
	The bool, if the value is one.
	*/
	#[must_use]
	pub const fn as_bool(&self) -> Option<bool> {
		match self {
			Self::Bool(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The int, if the value is one.
	*/
	#[must_use]
	pub const fn as_i64(&self) -> Option<i64> {
		match self {
			Self::Int(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The float, if the value is one. An int is not converted, because an int and a float are different types.
	*/
	#[must_use]
	pub const fn as_f64(&self) -> Option<f64> {
		match self {
			Self::Float(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The string, if the value is one.
	*/
	#[must_use]
	pub const fn as_str(&self) -> Option<&str> {
		match self {
			Self::String(value) => Some(value.as_str()),
			_ => None,
		}
	}

	/**
	The date, if the value is one.
	*/
	#[must_use]
	pub const fn as_date(&self) -> Option<Date> {
		match self {
			Self::Date(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The instant, if the value is one.
	*/
	#[must_use]
	pub const fn as_instant(&self) -> Option<Instant> {
		match self {
			Self::Instant(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The duration, if the value is one.
	*/
	#[must_use]
	pub const fn as_duration(&self) -> Option<Duration> {
		match self {
			Self::Duration(value) => Some(*value),
			_ => None,
		}
	}

	/**
	The items, if the value is an array.
	*/
	#[must_use]
	pub const fn as_array(&self) -> Option<&Vec<Self>> {
		match self {
			Self::Array(value) => Some(value),
			_ => None,
		}
	}

	/**
	The items, if the value is an array, to change.
	*/
	pub const fn as_array_mut(&mut self) -> Option<&mut Vec<Self>> {
		match self {
			Self::Array(value) => Some(value),
			_ => None,
		}
	}

	/**
	The members, if the value is an object.
	*/
	#[must_use]
	pub const fn as_object(&self) -> Option<&Object> {
		match self {
			Self::Object(value) => Some(value),
			_ => None,
		}
	}

	/**
	The members, if the value is an object, to change.
	*/
	pub const fn as_object_mut(&mut self) -> Option<&mut Object> {
		match self {
			Self::Object(value) => Some(value),
			_ => None,
		}
	}
}

/**
Reads a document, which is always an object or an array.
*/
impl FromStr for Value {
	type Err = Error;

	fn from_str(text: &str) -> Result<Self, Error> {
		crate::parse::parse(text).map(crate::parse::Node::into_value)
	}
}

macro_rules! from_integer {
	($($type:ty),*) => {
		$(
			impl From<$type> for Value {
				fn from(value: $type) -> Self {
					Self::Int(value.into())
				}
			}
		)*
	};
}

// Only the types that always fit an `i64`. A `u64`, an `i128`, or a `usize` can be too large, and `From` cannot fail.
from_integer!(i8, i16, i32, i64, u8, u16, u32);

impl From<f64> for Value {
	fn from(value: f64) -> Self {
		Self::Float(value)
	}
}

impl From<f32> for Value {
	/**
	Uses the shortest decimal that reads back as the same `f32`, so `0.1f32` becomes `0.1`, not `0.10000000149011612`.
	*/
	fn from(value: f32) -> Self {
		Self::Float(crate::ser::widen(value))
	}
}

impl From<bool> for Value {
	fn from(value: bool) -> Self {
		Self::Bool(value)
	}
}

impl From<String> for Value {
	fn from(value: String) -> Self {
		Self::String(value)
	}
}

impl From<&str> for Value {
	fn from(value: &str) -> Self {
		Self::String(value.to_owned())
	}
}

impl From<Date> for Value {
	fn from(value: Date) -> Self {
		Self::Date(value)
	}
}

impl From<Instant> for Value {
	fn from(value: Instant) -> Self {
		Self::Instant(value)
	}
}

impl From<Duration> for Value {
	fn from(value: Duration) -> Self {
		Self::Duration(value)
	}
}

impl<T: Into<Self>> From<Vec<T>> for Value {
	fn from(value: Vec<T>) -> Self {
		value.into_iter().collect()
	}
}

impl<T: Into<Self>, const N: usize> From<[T; N]> for Value {
	fn from(value: [T; N]) -> Self {
		value.into_iter().collect()
	}
}

impl From<Object> for Value {
	fn from(value: Object) -> Self {
		Self::Object(value)
	}
}

impl<T: Into<Self>> From<Option<T>> for Value {
	fn from(value: Option<T>) -> Self {
		value.map_or(Self::Null, Into::into)
	}
}

impl<T: Into<Self>> FromIterator<T> for Value {
	fn from_iter<I: IntoIterator<Item = T>>(iterator: I) -> Self {
		Self::Array(iterator.into_iter().map(Into::into).collect())
	}
}

impl<K: Into<String>, V: Into<Self>> FromIterator<(K, V)> for Value {
	fn from_iter<I: IntoIterator<Item = (K, V)>>(iterator: I) -> Self {
		Self::Object(
			iterator
				.into_iter()
				.map(|(key, value)| (key.into(), value.into()))
				.collect(),
		)
	}
}

/**
Reads a date, instant, or duration from its text, through a newtype struct named by its token, which the SOML deserializer gives only for a value of that type, and from a string for other formats.
*/
pub(crate) struct TextVisitor<F> {
	/**
	The type, with an article, for error messages: `an instant`.
	*/
	pub expecting: &'static str,
	pub parse: F,
}

impl<'de, T, F: FnOnce(&str) -> Result<T, String>> Visitor<'de> for TextVisitor<F> {
	type Value = T;

	fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		formatter.write_str(self.expecting)
	}

	fn visit_str<E: de::Error>(self, text: &str) -> Result<T, E> {
		(self.parse)(text).map_err(E::custom)
	}

	fn visit_newtype_struct<D: Deserializer<'de>>(self, deserializer: D) -> Result<T, D::Error> {
		deserializer.deserialize_str(self)
	}
}

/**
Serializes a value's canonical text, with `collect_str`, so that it allocates nothing for a serializer that writes text directly.
*/
pub(crate) struct CanonicalText<'a, T: Display>(pub &'a T);

impl<T: Display> Serialize for CanonicalText<'_, T> {
	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		serializer.collect_str(self.0)
	}
}

impl Serialize for Value {
	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		match self {
			Self::Null => serializer.serialize_unit(),
			Self::Bool(value) => serializer.serialize_bool(*value),
			Self::Int(value) => serializer.serialize_i64(*value),
			Self::Float(value) => serializer.serialize_f64(*value),
			Self::String(value) => serializer.serialize_str(value),
			Self::Date(value) => value.serialize(serializer),
			Self::Instant(value) => value.serialize(serializer),
			Self::Duration(value) => value.serialize(serializer),
			Self::Array(value) => serializer.collect_seq(value),
			Self::Object(value) => serializer.collect_map(value),
		}
	}
}

/**
The name that tells the SOML deserializer that a `Value` is being read, so that it gives a date, instant, or duration as itself, through `visit_enum`, rather than as its text.
*/
pub(crate) const TOKEN: &str = "$soml::Value";

impl<'de> Deserialize<'de> for Value {
	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
		deserializer.deserialize_newtype_struct(TOKEN, ValueVisitor)
	}
}

struct ValueVisitor;

impl<'de> Visitor<'de> for ValueVisitor {
	type Value = Value;

	fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		formatter.write_str("any SOML value")
	}

	fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
		crate::ser::integer(value)
			.map(Value::Int)
			.map_err(E::custom)
	}

	fn visit_i128<E: de::Error>(self, value: i128) -> Result<Value, E> {
		crate::ser::integer(value)
			.map(Value::Int)
			.map_err(E::custom)
	}

	fn visit_u128<E: de::Error>(self, value: u128) -> Result<Value, E> {
		crate::ser::integer(value)
			.map(Value::Int)
			.map_err(E::custom)
	}

	// An `f32` from another format, with its own shortest digits, as `From<f32>` makes it.
	fn visit_f32<E>(self, value: f32) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_str<E>(self, value: &str) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_string<E>(self, value: String) -> Result<Value, E> {
		Ok(Value::from(value))
	}

	fn visit_unit<E>(self) -> Result<Value, E> {
		Ok(Value::Null)
	}

	fn visit_none<E: de::Error>(self) -> Result<Value, E> {
		self.visit_unit()
	}

	fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
		Value::deserialize(deserializer)
	}

	fn visit_newtype_struct<D: Deserializer<'de>>(
		self,
		deserializer: D,
	) -> Result<Value, D::Error> {
		// `Value::deserialize` asks for a newtype struct named `TOKEN`. A format that does not know the token, such as JSON, calls this with its own deserializer, so the value is read as any other value.
		deserializer.deserialize_any(self)
	}

	fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Value, A::Error> {
		// The size hint of another format can come from its input, so it is capped to keep a false hint from allocating much memory.
		let mut items = Vec::with_capacity(crate::ser::capacity::<Value>(sequence.size_hint()));

		// Note: Not using Iterator::try_collect because it is unstable on the minimum Rust version.
		while let Some(item) = sequence.next_element()? {
			items.push(item);
		}

		Ok(Value::Array(items))
	}

	fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
		let mut object = Object::new();

		while let Some(key) = map.next_key::<String>()? {
			match object.entry(key) {
				Entry::Vacant(entry) => {
					entry.insert(map.next_value()?);
				}
				// Another format, such as JSON, can give a key twice. SOML treats a duplicate key as an error, so a `Value` does not keep the last one.
				Entry::Occupied(entry) => {
					return Err(de::Error::custom(Error::data(format!(
						"Duplicate key “{}”",
						crate::abbreviate(entry.key(), 40)
					))));
				}
			}
		}

		Ok(Value::Object(object))
	}

	/**
	The SOML deserializer gives a date, instant, or duration as a variant named by its private token, which no other format produces.
	*/
	fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Value, A::Error> {
		let (name, variant): (&str, _) = data.variant()?;

		match name {
			crate::date::TOKEN => variant.newtype_variant().map(Value::Date),
			crate::instant::TOKEN => variant.newtype_variant().map(Value::Instant),
			crate::duration::TOKEN => variant.newtype_variant().map(Value::Duration),
			_ => Err(de::Error::custom("A SOML value cannot hold an enum")),
		}
	}
}