Skip to main content

soml/
tree.rs

1/*!
2A lossless syntax tree, for tools that read and change SOML documents.
3
4A [`Document`](crate::Document) holds the tree. An unchanged tree prints the exact text it was parsed from, so comments, blank lines, indentation, member order, and the author's spelling of every value survive. A changed tree keeps all of that outside the change.
5
6Whitespace and comments between tokens are [`Decor`], and every piece of it belongs to exactly one node:
7
8- The text between an item and the next token (after the item's comma, if it has one) is split at its first line feed outside a block comment. The part up to and including that line feed is the item's trailing decor: usually a comment at the end of its line. The rest is the next item's leading decor: the comment lines above it, blank lines, and its indentation. When there is no line feed, as in `{a: 1, b: 2}`, all of it is the next item's leading decor. The one exception is the end of a document without a final line feed, where the rest of the last line, such as a comment, is the last member's trailing decor.
9- The text after the last item, before `}` or `]`, is the container's closing decor. The text before and after a braced top-level collection belongs to the document.
10- In a braced container, each item records whether it has a comma.
11
12# Formatting
13
14[`Document::format`](crate::Document::format) is the formatter in the spec's "Formatting" section. It keeps comments where they are (a comment on its own line stays on its own line, and a comment at the end of a line stays at the end of that line), member order, the spelling of every key, string, number, date, instant, and duration, block strings, and a top level with or without braces. It changes only layout: one tab of indentation per level, every member and item on its own line, no commas (a line break separates the members and items), no trailing spaces or tabs, at most one blank line in a row, and one line feed at the end. An object or an array whose brackets are on one line stays on one line, as in `ports: [80, 443]`, with a comma and a space between its members or items. To give a one-line container one member or item per line, put a line break anywhere inside it, also inside a comment or a block string.
15
16In detail, as the spec states:
17
18- No blank line directly after an opening bracket, directly before a closing one, or at the start or end of the document.
19- An empty `{}` or `[]` is written on one line. A container that holds only comments is not empty: on one line it stays on one line, as in `[/* note */]`, and otherwise its closing bracket begins a line of its own.
20- In a container on one line, no space is directly inside its brackets or before a comma, the comma after the last member or item goes, and block comments stay where they are among the members or items and commas, so `[1, /* end */]` becomes `[1 /* end */]`.
21- Where a comma goes, a comment between the value and the comma stays at the end of the value's line. Every other comment keeps its line.
22- A value on the line after its `key:` moves up to that line, unless it is a block string or a comment comes between them. Then each comment keeps its line, and the value goes on a new line, one level deeper.
23- In a container that spans lines, a comment between two items on one line, as in `1, /* c */ 2`, goes before the second item, on its line. At the end of a container or of the document, a comment with no line break before it stays at the end of the line before.
24- A block string begins on the line after its key, one level deeper, after any comments on the key's line. Its opening delimiter, its content, and its closing delimiter have one indentation: that of the line it begins on, which for an array item is the item's own. Its content keeps the indentation it has past the closing delimiter's, so its value does not change. A line of only spaces and tabs in a block string stays as written, as the spec's layout rules do not apply inside a block string.
25- The lines of a block comment keep their indentation, and only the line it starts on is indented. As on every line outside a block string, trailing spaces and tabs go, and runs of blank lines collapse to one. A block comment that spans lines is part of the line it ends on.
26*/
27
28use crate::scalar;
29use crate::{Value, parse, write};
30use std::borrow::Cow;
31use std::ops::Range;
32
33pub(crate) mod format;
34
35/**
36The whitespace and comments around a member or an array item, or around a top-level collection written with braces.
37*/
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
39pub struct Decor {
40	/**
41	The text before the item: the comment lines and blank lines above it, and its indentation. For a top-level collection, the text before it.
42	*/
43	pub leading: String,
44	/**
45	The text after the item and its comma, up to and including the line feed that ends its line, or for a top-level collection, the text after it: usually empty, a line feed, or a comment at the end of the line and a line feed. At the end of a document without a final line feed, it is the rest of the last line, such as a comment, without a line feed.
46	*/
47	pub trailing: String,
48}
49
50/**
51A node in the tree: an object, an array, or a scalar.
52*/
53#[derive(Debug, Clone, PartialEq)]
54pub enum Node {
55	/**
56	An object, with or without braces.
57	*/
58	Object(Object),
59	/**
60	An array.
61	*/
62	Array(Array),
63	/**
64	A string, number, bool, null, date, instant, or duration.
65	*/
66	Scalar(Scalar),
67}
68
69/**
70An object, with its members in the order they are written.
71*/
72#[derive(Debug, Clone, PartialEq)]
73pub struct Object {
74	members: Vec<Member>,
75	is_braced: bool,
76	closing: String,
77	span: Option<Range<usize>>,
78}
79
80/**
81A member of an object: a key and a value.
82*/
83#[derive(Debug, Clone, PartialEq)]
84pub struct Member {
85	key: Key,
86	/**
87	The text between the `:` and the value, usually one space, which is then not allocated.
88	*/
89	pub(crate) after_colon: Cow<'static, str>,
90	value: Node,
91	separator: Separator,
92	span: Option<Range<usize>>,
93}
94
95/**
96An empty object, written with braces, so it can be a member's value.
97*/
98impl Default for Object {
99	fn default() -> Self {
100		Self {
101			members: Vec::new(),
102			is_braced: true,
103			closing: String::new(),
104			span: None,
105		}
106	}
107}
108
109/**
110An array.
111*/
112#[derive(Debug, Clone, PartialEq, Default)]
113pub struct Array {
114	items: Vec<Item>,
115	closing: String,
116	span: Option<Range<usize>>,
117}
118
119/**
120An item of an array.
121*/
122#[derive(Debug, Clone, PartialEq)]
123pub struct Item {
124	value: Node,
125	separator: Separator,
126}
127
128/**
129The decor of a member or an item, and its comma.
130*/
131#[derive(Debug, Clone, PartialEq, Default)]
132pub(crate) struct Separator {
133	pub(crate) decor: Decor,
134	/**
135	Whether the item has a comma after it. An item on the same line as the next one always gets one when printed. In a top-level object without braces, commas are never printed.
136	*/
137	pub(crate) has_comma: bool,
138	/**
139	The text between the value and its comma, usually empty.
140	*/
141	pub(crate) before_comma: String,
142}
143
144/**
145A member of an object or an item of an array, which both have decor and may have a comma, so that inserting, removing, and printing them is one piece of code. A member of a top-level object without braces has decor too, and its comma is never printed.
146*/
147pub(crate) trait Entry {
148	fn separator(&self) -> &Separator;
149	fn separator_mut(&mut self) -> &mut Separator;
150	fn node_mut(&mut self) -> &mut Node;
151	fn is_on_one_line(&self) -> bool;
152	/**
153	Writes the entry without its separator's decor: a member's key, the text after its `:`, and its value, or an item's value.
154	*/
155	fn print(&self, printer: &mut Printer);
156}
157
158/**
159The entries of a container and its closing decor, to insert and remove entries. `is_braced` is false only for a top-level object without braces, where every entry starts a line.
160*/
161pub(crate) struct Entries<'a, T> {
162	pub list: &'a mut Vec<T>,
163	pub closing: &'a mut String,
164	pub is_braced: bool,
165}
166
167impl Entry for Member {
168	fn separator(&self) -> &Separator {
169		&self.separator
170	}
171
172	fn separator_mut(&mut self) -> &mut Separator {
173		&mut self.separator
174	}
175
176	fn node_mut(&mut self) -> &mut Node {
177		&mut self.value
178	}
179
180	fn is_on_one_line(&self) -> bool {
181		is_decor_on_one_line(&self.after_colon) && self.value.is_on_one_line()
182	}
183
184	fn print(&self, printer: &mut Printer) {
185		printer.member(self);
186	}
187}
188
189impl Entry for Item {
190	fn separator(&self) -> &Separator {
191		&self.separator
192	}
193
194	fn separator_mut(&mut self) -> &mut Separator {
195		&mut self.separator
196	}
197
198	fn node_mut(&mut self) -> &mut Node {
199		&mut self.value
200	}
201
202	fn is_on_one_line(&self) -> bool {
203		self.value.is_on_one_line()
204	}
205
206	fn print(&self, printer: &mut Printer) {
207		printer.node(&self.value);
208	}
209}
210
211/**
212A key of a member.
213
214Like the other nodes, a key compares equal to another only when it is also written the same way and is at the same place, so a parsed key `'port'` is not equal to `Key::new("port")`. Compare [`value`](Self::value) for the key itself.
215*/
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct Key {
218	value: String,
219	/**
220	The text the author wrote for a quoted key. A parsed bare key is written as its value, so it has none.
221	*/
222	raw: Option<String>,
223	span: Option<Range<usize>>,
224}
225
226/**
227A scalar: its value, and the text the author wrote for it.
228*/
229#[derive(Debug, Clone, PartialEq)]
230pub struct Scalar {
231	value: Value,
232	raw: Option<String>,
233	span: Option<Range<usize>>,
234}
235
236/**
237How a string or a key is written.
238*/
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum StringStyle {
241	/**
242	A bare key, without quotes. Only a key can be bare.
243	*/
244	Bare,
245	/**
246	`'...'`, with no escapes.
247	*/
248	Literal,
249	/**
250	`"..."`, with escapes.
251	*/
252	Escaped,
253	/**
254	`'''...'''`, a literal block string.
255	*/
256	LiteralBlock,
257	/**
258	`"""..."""`, a block string with escapes.
259	*/
260	EscapedBlock,
261}
262
263impl StringStyle {
264	const fn of(raw: &str) -> Self {
265		match raw.as_bytes() {
266			[b'\'', b'\'', b'\'', ..] => Self::LiteralBlock,
267			[b'"', b'"', b'"', ..] => Self::EscapedBlock,
268			[b'\'', ..] => Self::Literal,
269			[b'"', ..] => Self::Escaped,
270			_ => Self::Bare,
271		}
272	}
273}
274
275/**
276The two kinds of comment.
277*/
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
279pub enum CommentKind {
280	/**
281	`# ...`, to the end of its line.
282	*/
283	Line,
284	/**
285	`/* ... */`, which may span lines.
286	*/
287	Block,
288}
289
290/**
291The radix an int is written in. Its discriminant is the radix, so `radix as u32` is 2, 8, 10, or 16.
292*/
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294pub enum Radix {
295	/**
296	`0b`, as in `0b1010`.
297	*/
298	Binary = 2,
299	/**
300	`0o`, as in `0o644`.
301	*/
302	Octal = 8,
303	/**
304	No prefix, as in `-42`.
305	*/
306	Decimal = 10,
307	/**
308	`0x`, as in `0xFF`.
309	*/
310	Hexadecimal = 16,
311}
312
313/**
314A comment in a document.
315*/
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct Comment {
318	/**
319	The text of the comment, without its delimiters.
320	*/
321	pub text: String,
322	/**
323	Whether it is a `#` line comment or a `/* */` block comment.
324	*/
325	pub kind: CommentKind,
326	/**
327	The byte range of the comment, with its delimiters, in the document's current text.
328	*/
329	pub span: Range<usize>,
330}
331
332impl Node {
333	/**
334	A node for a value, printed in canonical form, with no decor. Use it to replace a value through [`Member::value_mut`] or [`Item::value_mut`], which keeps the decor around the value.
335
336	```rust
337	let mut document: soml::Document = "port: 1 # The default.".parse()?;
338	let root = document.root_mut().as_object_mut().unwrap();
339	*root.members_mut()[0].value_mut() = soml::tree::Node::new(8080)?;
340	assert_eq!(document.to_string(), "port: 8080 # The default.");
341	# Ok::<(), soml::Error>(())
342	```
343
344	# Errors
345
346	Returns an error when the value holds something SOML cannot represent: NaN, a carriage return, or nesting of 100 levels or more, because a node is always inside a collection.
347	*/
348	pub fn new(value: impl Into<Value>) -> Result<Self, crate::Error> {
349		Ok(Self::laid_out(checked(value.into())?, Some("")))
350	}
351
352	/**
353	Builds a node directly in its requested layout; no indentation means one line. A new value is laid out on lines of its own at `indentation`, as in canonical form, or on one line in a container that stays on one line.
354
355	With indentation, members and items are on their own lines, indented by `indentation` and one tab more, as in canonical form. Without it, a value is on one line, as in `{a: 1, b: [2, 3]}`, with a comma and a space between its members or items, for a value in a container that stays on one line.
356	*/
357	pub(crate) fn laid_out(value: Value, indentation: Option<&str>) -> Self {
358		let separator = |inner: Option<&str>, index, count| match inner {
359			Some(inner) => Separator::laid_out(inner, index == 0),
360			None => Separator::on_one_line(index, count),
361		};
362		// The closing bracket of a container with items goes on its own line.
363		let closing = |count: usize| {
364			if count == 0 {
365				String::new()
366			} else {
367				indentation.unwrap_or_default().to_owned()
368			}
369		};
370
371		match value {
372			Value::Object(object) => {
373				let count = object.len();
374				let inner = indentation
375					.filter(|_| count > 0)
376					.map(|indentation| [indentation, "\t"].concat());
377				let members = object
378					.into_iter()
379					.enumerate()
380					.map(|(index, (key, value))| Member {
381						key: Key::new(key),
382						after_colon: Cow::Borrowed(" "),
383						value: Self::laid_out(value, inner.as_deref()),
384						separator: separator(inner.as_deref(), index, count),
385						span: None,
386					})
387					.collect();
388
389				Self::Object(Object {
390					members,
391					is_braced: true,
392					closing: closing(count),
393					span: None,
394				})
395			}
396			Value::Array(items) => {
397				let count = items.len();
398				let inner = indentation
399					.filter(|_| count > 0)
400					.map(|indentation| [indentation, "\t"].concat());
401				let items = items
402					.into_iter()
403					.enumerate()
404					.map(|(index, value)| Item {
405						value: Self::laid_out(value, inner.as_deref()),
406						separator: separator(inner.as_deref(), index, count),
407					})
408					.collect();
409
410				Self::Array(Array {
411					items,
412					closing: closing(count),
413					span: None,
414				})
415			}
416			value => Self::Scalar(Scalar {
417				value,
418				raw: None,
419				span: None,
420			}),
421		}
422	}
423
424	/**
425	The object, if this node is one.
426	*/
427	#[must_use]
428	pub const fn as_object(&self) -> Option<&Object> {
429		match self {
430			Self::Object(object) => Some(object),
431			_ => None,
432		}
433	}
434
435	/**
436	The object, if this node is one, to change.
437	*/
438	pub const fn as_object_mut(&mut self) -> Option<&mut Object> {
439		match self {
440			Self::Object(object) => Some(object),
441			_ => None,
442		}
443	}
444
445	/**
446	The array, if this node is one.
447	*/
448	#[must_use]
449	pub const fn as_array(&self) -> Option<&Array> {
450		match self {
451			Self::Array(array) => Some(array),
452			_ => None,
453		}
454	}
455
456	/**
457	The array, if this node is one, to change.
458	*/
459	pub const fn as_array_mut(&mut self) -> Option<&mut Array> {
460		match self {
461			Self::Array(array) => Some(array),
462			_ => None,
463		}
464	}
465
466	/**
467	The scalar, if this node is one.
468	*/
469	#[must_use]
470	pub const fn as_scalar(&self) -> Option<&Scalar> {
471		match self {
472			Self::Scalar(scalar) => Some(scalar),
473			_ => None,
474		}
475	}
476
477	/**
478	The byte range of the node in the text the document was parsed from. `None` for a node that was added or replaced.
479	*/
480	#[must_use]
481	pub const fn span(&self) -> Option<Range<usize>> {
482		let span = match self {
483			Self::Object(object) => &object.span,
484			Self::Array(array) => &array.span,
485			Self::Scalar(scalar) => &scalar.span,
486		};
487		copied_span(span)
488	}
489
490	/**
491	Whether the node is printed on one line, with no line break anywhere in it, also not in a comment or a block string. A line comment in changed decor counts as a line break, because the printer ends its line. A top-level object without braces counts as more than one line, because its members are on lines of their own.
492
493	It checks what the printer would write without writing it, because the formatter asks this of every container. A key has no line break, and neither has a scalar that was added or replaced, whose string is written with escapes.
494	*/
495	pub(crate) fn is_on_one_line(&self) -> bool {
496		match self {
497			Self::Object(object) => {
498				object.is_braced
499					&& is_decor_on_one_line(&object.closing)
500					&& object.members.iter().all(|member| {
501						is_decor_on_one_line(&member.after_colon)
502							&& member.separator.is_on_one_line()
503							&& member.value.is_on_one_line()
504					})
505			}
506			Self::Array(array) => {
507				is_decor_on_one_line(&array.closing)
508					&& array
509						.items
510						.iter()
511						.all(|item| item.separator.is_on_one_line() && item.value.is_on_one_line())
512			}
513			Self::Scalar(scalar) => scalar.raw.as_deref().is_none_or(|raw| !raw.contains('\n')),
514		}
515	}
516}
517
518impl Separator {
519	/**
520	Whether its decor is printed on one line, as for `Node::is_on_one_line`.
521	*/
522	fn is_on_one_line(&self) -> bool {
523		is_decor_on_one_line(&self.decor.leading)
524			&& is_decor_on_one_line(&self.before_comma)
525			&& is_decor_on_one_line(&self.decor.trailing)
526	}
527}
528
529/**
530Whether decor in a braced container is printed on one line: it has no line feed, also not in a block comment, and does not end in a line comment, after which the printer ends the line before the next token, at the latest the closing bracket.
531*/
532fn is_decor_on_one_line(decor: &str) -> bool {
533	!decor.contains('\n') && (!decor.contains('#') || !ends_in_line_comment(decor))
534}
535
536impl Object {
537	/**
538	The members, in the order they are written.
539	*/
540	#[must_use]
541	pub const fn members(&self) -> &[Member] {
542		self.members.as_slice()
543	}
544
545	/**
546	The members, to add, remove, reorder, or change. A change here can make a document that is not valid, such as one with two members with the same key; [`Document::to_value`](crate::Document::to_value) finds that. [`Document::set`](crate::Document::set) and [`Document::remove`](crate::Document::remove) keep the document valid and lay out what they add.
547	*/
548	pub const fn members_mut(&mut self) -> &mut Vec<Member> {
549		&mut self.members
550	}
551
552	/**
553	Whether the object is written with braces. Only a top-level object can be written without them.
554	*/
555	#[must_use]
556	pub const fn is_braced(&self) -> bool {
557		self.is_braced
558	}
559
560	/**
561	The text after the last member: before the closing `}`, or at the end of a top-level object without braces.
562	*/
563	#[must_use]
564	pub const fn closing_decor(&self) -> &str {
565		self.closing.as_str()
566	}
567
568	/**
569	The text after the last member, to change.
570	*/
571	pub const fn closing_decor_mut(&mut self) -> &mut String {
572		&mut self.closing
573	}
574
575	/**
576	The position of the member with a key.
577	*/
578	pub(crate) fn position(&self, key: &str) -> Option<usize> {
579		// Note: Not using binary_search_by because members keep their written order and are not sorted.
580		self.members
581			.iter()
582			.position(|member| member.key.value == key)
583	}
584
585	pub(crate) fn entries_mut(&mut self) -> Entries<'_, Member> {
586		Entries {
587			list: &mut self.members,
588			closing: &mut self.closing,
589			is_braced: self.is_braced,
590		}
591	}
592}
593
594impl Array {
595	/**
596	The items, in order.
597	*/
598	#[must_use]
599	pub const fn items(&self) -> &[Item] {
600		self.items.as_slice()
601	}
602
603	/**
604	The items, to add, remove, reorder, or change.
605	*/
606	pub const fn items_mut(&mut self) -> &mut Vec<Item> {
607		&mut self.items
608	}
609
610	/**
611	The text after the last item, before the closing `]`.
612	*/
613	#[must_use]
614	pub const fn closing_decor(&self) -> &str {
615		self.closing.as_str()
616	}
617
618	/**
619	The text after the last item, to change.
620	*/
621	pub const fn closing_decor_mut(&mut self) -> &mut String {
622		&mut self.closing
623	}
624
625	pub(crate) fn entries_mut(&mut self) -> Entries<'_, Item> {
626		Entries {
627			list: &mut self.items,
628			closing: &mut self.closing,
629			is_braced: true,
630		}
631	}
632}
633
634impl Member {
635	/**
636	Creates a member, with no decor.
637
638	# Errors
639
640	Returns an error when the value holds something SOML cannot represent: NaN, a carriage return, or nesting of 100 levels or more, because a member is always inside an object, or when the key holds a carriage return.
641	*/
642	pub fn new(key: Key, value: impl Into<Value>) -> Result<Self, crate::Error> {
643		write::check_representable(key.value(), "key")?;
644		let value = Node::new(value)?;
645
646		Ok(Self {
647			key,
648			after_colon: Cow::Borrowed(" "),
649			value,
650			separator: Separator::default(),
651			span: None,
652		})
653	}
654
655	/**
656	The key.
657	*/
658	#[must_use]
659	pub const fn key(&self) -> &Key {
660		&self.key
661	}
662
663	/**
664	The key, to change.
665	*/
666	pub const fn key_mut(&mut self) -> &mut Key {
667		&mut self.key
668	}
669
670	/**
671	The value.
672	*/
673	#[must_use]
674	pub const fn value(&self) -> &Node {
675		&self.value
676	}
677
678	/**
679	The value, to change.
680	*/
681	pub const fn value_mut(&mut self) -> &mut Node {
682		&mut self.value
683	}
684
685	/**
686	The whitespace and comments around the member.
687	*/
688	#[must_use]
689	pub const fn decor(&self) -> &Decor {
690		&self.separator.decor
691	}
692
693	/**
694	The whitespace and comments around the member, to change.
695	*/
696	pub const fn decor_mut(&mut self) -> &mut Decor {
697		&mut self.separator.decor
698	}
699
700	/**
701	The byte range of the member, from its key to the end of its value, in the text the document was parsed from. `None` for a member that was added.
702	*/
703	#[must_use]
704	pub const fn span(&self) -> Option<Range<usize>> {
705		copied_span(&self.span)
706	}
707}
708
709impl Item {
710	/**
711	Creates an array item, with no decor.
712
713	# Errors
714
715	Returns an error when the value holds something SOML cannot represent: NaN, a carriage return, or nesting of 100 levels or more, because a node is always inside a collection.
716	*/
717	pub fn new(value: impl Into<Value>) -> Result<Self, crate::Error> {
718		Ok(Self {
719			value: Node::new(value)?,
720			separator: Separator::default(),
721		})
722	}
723
724	/**
725	The value.
726	*/
727	#[must_use]
728	pub const fn value(&self) -> &Node {
729		&self.value
730	}
731
732	/**
733	The value, to change.
734	*/
735	pub const fn value_mut(&mut self) -> &mut Node {
736		&mut self.value
737	}
738
739	/**
740	The whitespace and comments around the item.
741	*/
742	#[must_use]
743	pub const fn decor(&self) -> &Decor {
744		&self.separator.decor
745	}
746
747	/**
748	The whitespace and comments around the item, to change.
749	*/
750	pub const fn decor_mut(&mut self) -> &mut Decor {
751		&mut self.separator.decor
752	}
753}
754
755impl Separator {
756	/**
757	The decor of an item on its own line, as `Node::laid_out` lays it out: the first item's line feed is in its leading decor, because it follows the opening bracket, and every item's trailing decor ends its line.
758	*/
759	fn laid_out(indentation: &str, is_first: bool) -> Self {
760		Self {
761			decor: Decor {
762				leading: if is_first {
763					["\n", indentation].concat()
764				} else {
765					indentation.to_owned()
766				},
767				trailing: "\n".to_owned(),
768			},
769			has_comma: false,
770			before_comma: String::new(),
771		}
772	}
773}
774
775impl Separator {
776	/**
777	The separator between entries on one line, with a comma and a space between them.
778	*/
779	fn on_one_line(index: usize, count: usize) -> Self {
780		Self {
781			decor: Decor {
782				leading: if index == 0 {
783					String::new()
784				} else {
785					" ".to_owned()
786				},
787				trailing: String::new(),
788			},
789			has_comma: index + 1 < count,
790			before_comma: String::new(),
791		}
792	}
793}
794
795/**
796Checks that a value can be written, so that a tree never holds something that cannot be printed.
797*/
798pub(crate) fn checked(value: Value) -> Result<Value, crate::Error> {
799	// As an item of a top-level array: one collection around it. Validation stops at the nesting limit; dropping extremely deep hand-built values can still overflow the stack, as with `from_value`.
800	value.check(1)?;
801	Ok(value)
802}
803
804impl Key {
805	/**
806	A key, which is written bare when it can be and quoted otherwise. A key that holds a `.` is quoted.
807
808	```rust
809	let key = soml::tree::Key::new("the name");
810	assert_eq!(key.to_string(), "'the name'");
811
812	let key = soml::tree::Key::new("example.com");
813	assert_eq!(key.to_string(), "'example.com'");
814	```
815	*/
816	#[must_use]
817	pub fn new(value: impl Into<String>) -> Self {
818		Self {
819			value: value.into(),
820			raw: None,
821			span: None,
822		}
823	}
824
825	/**
826	The key, decoded, which is what makes two keys the same key.
827
828	```rust
829	let document: soml::Document = "'server': 1".parse()?;
830	let key = document.root().as_object().unwrap().members()[0].key();
831
832	assert_eq!(key.value(), "server");
833	# Ok::<(), soml::Error>(())
834	```
835	*/
836	#[must_use]
837	pub const fn value(&self) -> &str {
838		self.value.as_str()
839	}
840
841	/**
842	The text the author wrote for the key. `None` for a key that was added, which is written bare when it can be and quoted otherwise.
843	*/
844	#[must_use]
845	pub const fn raw(&self) -> Option<&str> {
846		match &self.raw {
847			Some(raw) => Some(raw.as_str()),
848			None if self.span.is_some() => Some(self.value.as_str()),
849			None => None,
850		}
851	}
852
853	/**
854	How the key is written: bare, `'...'`, or `"..."`.
855	*/
856	#[must_use]
857	pub fn style(&self) -> StringStyle {
858		match self.raw() {
859			Some(raw) => StringStyle::of(raw),
860			None if scalar::is_bare_key(&self.value) => StringStyle::Bare,
861			None if write::needs_escapes(&self.value) => StringStyle::Escaped,
862			None => StringStyle::Literal,
863		}
864	}
865
866	/**
867	The byte range of the key in the text the document was parsed from. `None` for a key that was added.
868	*/
869	#[must_use]
870	pub const fn span(&self) -> Option<Range<usize>> {
871		copied_span(&self.span)
872	}
873}
874
875impl Key {
876	/**
877	Writes the original or canonical key directly into the destination.
878	*/
879	fn write(&self, output: &mut String) {
880		match self.raw() {
881			Some(raw) => output.push_str(raw),
882			None => {
883				write::write_key(output, &self.value).expect("writing to a String does not fail")
884			}
885		}
886	}
887}
888
889/**
890The text the author wrote, or for a key that was added, the key written bare when it can be and quoted otherwise.
891*/
892impl std::fmt::Display for Key {
893	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
894		match self.raw() {
895			Some(raw) => formatter.write_str(raw),
896			None => write::write_key(formatter, &self.value),
897		}
898	}
899}
900
901impl Scalar {
902	/**
903	The text the author wrote, or the canonical form of a value that was added or replaced.
904	*/
905	fn write(&self, output: &mut String) {
906		if let Some(raw) = &self.raw {
907			output.push_str(raw);
908			return;
909		}
910
911		// A tree holds only scalars that can be written.
912		let kind = match &self.value {
913			Value::Null => parse::Kind::Null,
914			Value::Bool(value) => parse::Kind::Bool(*value),
915			Value::Int(value) => parse::Kind::Int(*value),
916			Value::Float(value) => parse::Kind::Float(*value),
917			Value::String(value) => parse::Kind::String(Cow::Borrowed(value)),
918			Value::Date(value) => parse::Kind::Date(*value),
919			Value::Instant(value) => parse::Kind::Instant(*value),
920			Value::Duration(value) => parse::Kind::Duration(*value),
921			Value::Array(_) | Value::Object(_) => unreachable!("a scalar cannot hold a collection"),
922		};
923		write::write_value(output, &kind.into(), 0);
924	}
925
926	/**
927	The value. Never an array or an object.
928	*/
929	#[must_use]
930	pub const fn value(&self) -> &Value {
931		&self.value
932	}
933
934	/**
935	The text the author wrote for the value, such as `0xFF`, `'text'`, or `90m`. `None` for a value that was added or replaced, which is printed in canonical form.
936	*/
937	#[must_use]
938	pub const fn raw(&self) -> Option<&str> {
939		match &self.raw {
940			Some(raw) => Some(raw.as_str()),
941			None => None,
942		}
943	}
944
945	/**
946	How a string is written. `None` for a value that is not a string.
947	*/
948	#[must_use]
949	pub fn string_style(&self) -> Option<StringStyle> {
950		let Value::String(text) = &self.value else {
951			return None;
952		};
953
954		Some(match &self.raw {
955			Some(raw) => StringStyle::of(raw),
956			None if write::needs_escapes(text) => StringStyle::Escaped,
957			None => StringStyle::Literal,
958		})
959	}
960
961	/**
962	Whether the value is a string written as a block string.
963	*/
964	pub(crate) fn is_block_string(&self) -> bool {
965		self.raw().is_some_and(|raw| {
966			matches!(
967				StringStyle::of(raw),
968				StringStyle::LiteralBlock | StringStyle::EscapedBlock
969			)
970		})
971	}
972
973	/**
974	The radix an int is written in. `None` for a value that is not an int.
975	*/
976	#[must_use]
977	pub const fn radix(&self) -> Option<Radix> {
978		let Value::Int(_) = self.value else {
979			return None;
980		};
981
982		Some(
983			match match self.raw() {
984				Some(raw) => Some(raw.as_bytes()),
985				None => None,
986			} {
987				Some([b'0', b'x', ..]) => Radix::Hexadecimal,
988				Some([b'0', b'o', ..]) => Radix::Octal,
989				Some([b'0', b'b', ..]) => Radix::Binary,
990				_ => Radix::Decimal,
991			},
992		)
993	}
994
995	/**
996	The byte range of the value in the text the document was parsed from. `None` for a value that was added or replaced.
997	*/
998	#[must_use]
999	pub const fn span(&self) -> Option<Range<usize>> {
1000		copied_span(&self.span)
1001	}
1002}
1003
1004/**
1005The parts of a parsed document: the decor before the top-level collection, the collection, and the decor after it.
1006*/
1007pub(crate) struct Parts {
1008	pub outer: Decor,
1009	pub root: Node,
1010}
1011
1012/**
1013Builds the tree of a document from the parser's tree of it, `parsed`, which has its values and where they are. The builder adds the keys as written and the text around them.
1014*/
1015pub(crate) fn build(source: &str, parsed: parse::Node<'_>) -> Parts {
1016	let builder = Builder {
1017		source,
1018		bytes: source.as_bytes(),
1019	};
1020
1021	let start = parsed.offset.get().expect("a parsed node has an offset");
1022
1023	// The parser rejects a document with only comments and whitespace, so a token is at `start`.
1024	if !matches!(builder.bytes[start], b'{' | b'[') {
1025		return Parts {
1026			outer: Decor::default(),
1027			root: Node::Object(builder.bare_object(parsed)),
1028		};
1029	}
1030
1031	let (root, end) = builder.value(parsed);
1032
1033	Parts {
1034		outer: Decor {
1035			leading: source[..start].to_owned(),
1036			trailing: source[end..].to_owned(),
1037		},
1038		root,
1039	}
1040}
1041
1042struct Builder<'a> {
1043	source: &'a str,
1044	bytes: &'a [u8],
1045}
1046
1047impl Builder<'_> {
1048	/**
1049	The index after the spaces, tabs, line feeds, and comments at `index`.
1050	*/
1051	fn skip_trivia(&self, index: usize) -> usize {
1052		crate::parse::skip_trivia(self.bytes, index)
1053			.expect("the parser checked the comments")
1054			.0
1055	}
1056
1057	/**
1058	Splits the decor between `start` and `end` after its first line feed outside a block comment. Returns the index of the split, which is `start` when there is no line feed.
1059	*/
1060	fn split_after_line_feed(&self, start: usize, end: usize) -> usize {
1061		first_line_end(&self.source[start..end]).map_or(start, |end| start + end)
1062	}
1063
1064	fn bare_object(&self, parsed: parse::Node<'_>) -> Object {
1065		let parse::Kind::Object(object) = parsed.kind else {
1066			unreachable!("a document without brackets is an object");
1067		};
1068
1069		let count = object.members.len();
1070		let mut members = Vec::with_capacity(count);
1071		let mut leading_start = 0;
1072
1073		for (index, (key, parsed_member)) in object.members.into_iter().enumerate() {
1074			let key_start = parsed_member
1075				.key_offset
1076				.get()
1077				.expect("a parsed key has an offset");
1078			let (mut member, value_end) = self.member(key, parsed_member);
1079			member.separator.decor.leading = self.source[leading_start..key_start].to_owned();
1080			let next = self.skip_trivia(value_end);
1081			let mut split = self.split_after_line_feed(value_end, next);
1082
1083			// The last line of a document without a final line feed ends at the end of the text, so a comment there is the last member's.
1084			if index + 1 == count && split == value_end {
1085				split = self.bytes.len();
1086			}
1087
1088			member.separator.decor.trailing = self.source[value_end..split].to_owned();
1089			members.push(member);
1090			leading_start = split;
1091		}
1092
1093		Object {
1094			// From the first member to the end of the last, as in the JS reference. The text around them is decor.
1095			span: Some(parsed.offset.get().expect("a parsed node has an offset")..parsed.end),
1096			members,
1097			is_braced: false,
1098			closing: self.source[leading_start..].to_owned(),
1099		}
1100	}
1101
1102	/**
1103	A member, without its decor, and the index after its value.
1104	*/
1105	fn member(&self, key: Cow<'_, str>, parsed: parse::Member<'_>) -> (Member, usize) {
1106		let start = parsed.key_offset.get().expect("a parsed key has an offset");
1107		let end = parsed.key_end;
1108		let raw =
1109			matches!(self.bytes[start], b'\'' | b'"').then(|| self.source[start..end].to_owned());
1110
1111		let key = Key {
1112			value: key.into_owned(),
1113			raw,
1114			span: Some(start..end),
1115		};
1116
1117		// Past the `:`.
1118		let after_colon_start = end + 1;
1119		let value_start = parsed
1120			.value
1121			.offset
1122			.get()
1123			.expect("a parsed node has an offset");
1124		let (value, value_end) = self.value(parsed.value);
1125
1126		let member = Member {
1127			key,
1128			after_colon: match &self.source[after_colon_start..value_start] {
1129				" " => Cow::Borrowed(" "),
1130				text => Cow::Owned(text.to_owned()),
1131			},
1132			value,
1133			separator: Separator::default(),
1134			span: Some(start..value_end),
1135		};
1136
1137		(member, value_end)
1138	}
1139
1140	/**
1141	A value, and the index after it.
1142	*/
1143	fn value(&self, parsed: parse::Node<'_>) -> (Node, usize) {
1144		let start = parsed.offset.get().expect("a parsed node has an offset");
1145		let end = parsed.end;
1146
1147		let node = match parsed.kind {
1148			parse::Kind::Object(object) => {
1149				let (members, closing) =
1150					self.entries(start, end, object.members, |(key, member)| {
1151						self.member(key, member)
1152					});
1153
1154				Node::Object(Object {
1155					members,
1156					is_braced: true,
1157					closing,
1158					span: Some(start..end),
1159				})
1160			}
1161			parse::Kind::Array(items) => {
1162				let (items, closing) = self.entries(start, end, items, |item| {
1163					let (value, end) = self.value(item);
1164					let item = Item {
1165						value,
1166						separator: Separator::default(),
1167					};
1168					(item, end)
1169				});
1170
1171				Node::Array(Array {
1172					items,
1173					closing,
1174					span: Some(start..end),
1175				})
1176			}
1177			kind => Node::Scalar(Scalar {
1178				value: parse::Node::from(kind).into_value(),
1179				raw: Some(self.source[start..end].to_owned()),
1180				span: Some(start..end),
1181			}),
1182		};
1183
1184		(node, end)
1185	}
1186
1187	/**
1188	Reads the entries of a braced container from `start` to `end`, with `read` making one entry of a parsed one, without its separator, and returning the index after it. Returns the entries and the closing decor.
1189	*/
1190	fn entries<P, T: Entry>(
1191		&self,
1192		start: usize,
1193		end: usize,
1194		parsed: Vec<P>,
1195		mut read: impl FnMut(P) -> (T, usize),
1196	) -> (Vec<T>, String) {
1197		let mut entries = Vec::with_capacity(parsed.len());
1198		let mut leading_start = start + 1;
1199
1200		for parsed in parsed {
1201			let item_start = self.skip_trivia(leading_start);
1202			let (mut entry, value_end) = read(parsed);
1203			let separator = entry.separator_mut();
1204			separator.decor.leading = self.source[leading_start..item_start].to_owned();
1205
1206			let after_value = self.skip_trivia(value_end);
1207			let mut trailing_start = value_end;
1208
1209			if self.bytes[after_value] == b',' {
1210				separator.has_comma = true;
1211				separator.before_comma = self.source[value_end..after_value].to_owned();
1212				trailing_start = after_value + 1;
1213			}
1214
1215			let next = if separator.has_comma {
1216				self.skip_trivia(trailing_start)
1217			} else {
1218				after_value
1219			};
1220			let split = self.split_after_line_feed(trailing_start, next);
1221			separator.decor.trailing = self.source[trailing_start..split].to_owned();
1222			entries.push(entry);
1223			leading_start = split;
1224		}
1225
1226		// The text before the closing bracket.
1227		(entries, self.source[leading_start..end - 1].to_owned())
1228	}
1229}
1230
1231/**
1232Writes a tree, and finds the comments in it on the way.
1233*/
1234pub(crate) struct Printer {
1235	pub output: String,
1236	pub comments: Option<Vec<Comment>>,
1237	/**
1238	Whether changed decor ended inside a line comment, so a line feed must come before anything else is printed. It is dropped at the end of the document, so a document that ends in a comment prints back unchanged.
1239	*/
1240	pub needs_line_feed: bool,
1241}
1242
1243impl Printer {
1244	/**
1245	A printer with no output, which also collects the comments when `collects_comments` is true.
1246	*/
1247	pub(crate) fn new(collects_comments: bool) -> Self {
1248		Self {
1249			output: String::new(),
1250			comments: collects_comments.then(Vec::new),
1251			needs_line_feed: false,
1252		}
1253	}
1254
1255	/**
1256	Writes text that is not decor.
1257	*/
1258	fn write(&mut self, text: &str) {
1259		self.end_line_comment();
1260		self.output.push_str(text);
1261	}
1262
1263	fn end_line_comment(&mut self) {
1264		if self.needs_line_feed {
1265			self.output.push('\n');
1266			self.needs_line_feed = false;
1267		}
1268	}
1269
1270	pub(crate) fn document(&mut self, outer: &Decor, root: &Node) {
1271		self.decor(&outer.leading);
1272		self.node(root);
1273		self.decor(&outer.trailing);
1274	}
1275
1276	fn node(&mut self, node: &Node) {
1277		match node {
1278			Node::Object(object) => self.object(object),
1279			Node::Array(array) => self.array(array),
1280			Node::Scalar(scalar) => self.scalar(scalar),
1281		}
1282	}
1283
1284	fn object(&mut self, object: &Object) {
1285		if !object.is_braced {
1286			// A top-level object without braces needs at least one member.
1287			if object.members.is_empty() {
1288				self.write("{}");
1289			}
1290
1291			for (index, member) in object.members.iter().enumerate() {
1292				let decor = &member.separator.decor;
1293
1294				// Members are separated by a line break, which an added member may not have in its decor.
1295				if index > 0 && shares_line_with_next(&object.members, index - 1) {
1296					// The next write ends the line once, also after a line comment, which needs a line feed of its own.
1297					self.needs_line_feed = true;
1298				}
1299
1300				self.decor(&decor.leading);
1301				self.member(member);
1302				self.decor(&decor.trailing);
1303			}
1304
1305			self.decor(&object.closing);
1306			return;
1307		}
1308
1309		self.write("{");
1310		self.entries(&object.members);
1311		self.decor(&object.closing);
1312		self.write("}");
1313	}
1314
1315	fn member(&mut self, member: &Member) {
1316		self.end_line_comment();
1317		member.key.write(&mut self.output);
1318		self.output.push(':');
1319		self.decor(&member.after_colon);
1320		self.node(&member.value);
1321	}
1322
1323	fn array(&mut self, array: &Array) {
1324		self.write("[");
1325		self.entries(&array.items);
1326		self.decor(&array.closing);
1327		self.write("]");
1328	}
1329
1330	/**
1331	The members or items of a braced container, each with its comma when it has one. An item that is on the same line as the next one gets a comma too, because a line break or a comma must separate them, so a change through the node API cannot join two items.
1332	*/
1333	fn entries<T: Entry>(&mut self, entries: &[T]) {
1334		for (index, entry) in entries.iter().enumerate() {
1335			let separator = entry.separator();
1336			self.decor(&separator.decor.leading);
1337			entry.print(self);
1338			// Printed also when the comma was dropped, so a comment before it is not lost.
1339			self.decor(&separator.before_comma);
1340
1341			if separator.has_comma || shares_line_with_next(entries, index) {
1342				self.write(",");
1343			}
1344
1345			self.decor(&separator.decor.trailing);
1346		}
1347	}
1348
1349	fn scalar(&mut self, scalar: &Scalar) {
1350		self.end_line_comment();
1351		scalar.write(&mut self.output);
1352	}
1353
1354	/**
1355	Writes decor, and records the comments in it. Decor holds only whitespace and comments, so a `#` or the opening of a block comment in it always starts a comment.
1356	*/
1357	fn decor(&mut self, decor: &str) {
1358		// A pending line comment needs a line feed after it. Decor that starts with a line feed gives it, and one more would add a blank line. Other decor would become part of the comment, so `end_line_comment` writes the line feed first.
1359		if decor.starts_with('\n') {
1360			self.needs_line_feed = false;
1361		} else if !decor.is_empty() {
1362			self.end_line_comment();
1363		}
1364
1365		let start = self.output.len();
1366		self.output.push_str(decor);
1367
1368		for (part, range) in decor_parts(decor) {
1369			// A line comment at the end of changed decor would otherwise swallow whatever is printed next.
1370			self.needs_line_feed = part == DecorPart::LineComment && range.end == decor.len();
1371
1372			if let Some(comments) = &mut self.comments
1373				&& part != DecorPart::LineFeed
1374			{
1375				let delimited = &decor[range.clone()];
1376				// An unterminated block comment, which only changed decor can have, runs to the end.
1377				let (kind, text) = match delimited.strip_prefix("/*") {
1378					Some(body) => (CommentKind::Block, body.strip_suffix("*/").unwrap_or(body)),
1379					None => (CommentKind::Line, &delimited[1..]),
1380				};
1381
1382				comments.push(Comment {
1383					text: text.to_owned(),
1384					kind,
1385					span: start + range.start..start + range.end,
1386				});
1387			}
1388		}
1389	}
1390}
1391
1392/**
1393What a part of decor is.
1394*/
1395#[derive(Clone, Copy, PartialEq, Eq)]
1396pub(crate) enum DecorPart {
1397	/**
1398	A line feed outside a comment.
1399	*/
1400	LineFeed,
1401	LineComment,
1402	BlockComment,
1403}
1404
1405/**
1406The line feeds and comments in decor, with their ranges. Decor holds only whitespace and comments, so a `#` or the opening of a block comment in it always starts a comment. A block comment without its end, which only changed decor can have, runs to the end.
1407*/
1408pub(crate) fn decor_parts(decor: &str) -> impl Iterator<Item = (DecorPart, Range<usize>)> + '_ {
1409	let bytes = decor.as_bytes();
1410	let mut index = 0;
1411
1412	std::iter::from_fn(move || {
1413		while index < bytes.len() {
1414			let start = index;
1415
1416			let part = match bytes[index] {
1417				b' ' | b'\t' => {
1418					index = scalar::skip_spaces(bytes, index);
1419					continue;
1420				}
1421				b'\n' => {
1422					index += 1;
1423					DecorPart::LineFeed
1424				}
1425				b'#' => {
1426					// The line feed that ends the comment is not part of it, so the next part is that line feed.
1427					index = scalar::line_end(bytes, index);
1428					DecorPart::LineComment
1429				}
1430				b'/' if bytes.get(index + 1) == Some(&b'*') => {
1431					index = crate::parse::block_comment_end(bytes, index)
1432						.map_or(bytes.len(), |end| end + 2);
1433					DecorPart::BlockComment
1434				}
1435				_ => {
1436					index += 1;
1437					continue;
1438				}
1439			};
1440
1441			return Some((part, start..index));
1442		}
1443
1444		None
1445	})
1446}
1447
1448/**
1449The spaces and tabs at the start of a line.
1450*/
1451pub(crate) fn indentation_of(line: &str) -> &str {
1452	&line[..line.len() - line.trim_start_matches([' ', '\t']).len()]
1453}
1454
1455/**
1456Whether the entry at `index` is on the same line as the next one, so a comma must separate them.
1457*/
1458pub(crate) fn shares_line_with_next<T: Entry>(entries: &[T], index: usize) -> bool {
1459	let separator = entries[index].separator();
1460
1461	entries.get(index + 1).is_some_and(|next| {
1462		!has_line_feed(&separator.decor.trailing) && !has_line_feed(&next.separator().decor.leading)
1463	})
1464}
1465
1466/**
1467Whether decor ends in a line comment, without the line feed that ends it, as changed decor and the last line of a document can.
1468*/
1469pub(crate) fn ends_in_line_comment(decor: &str) -> bool {
1470	if decor.is_empty() || decor.ends_with('\n') || !decor.contains('#') {
1471		return false;
1472	}
1473	decor_parts(decor)
1474		.last()
1475		.is_some_and(|(part, range)| part == DecorPart::LineComment && range.end == decor.len())
1476}
1477
1478/**
1479Whether decor has a line feed outside its block comments.
1480*/
1481pub(crate) fn has_line_feed(decor: &str) -> bool {
1482	// Note: Not using a separate any scan because reusing first_line_end benchmarks faster in complete formatting.
1483	first_line_end(decor).is_some()
1484}
1485
1486/**
1487The index after the first line feed in decor that is not inside a block comment, which is where its first line ends.
1488*/
1489pub(crate) fn first_line_end(decor: &str) -> Option<usize> {
1490	decor_parts(decor)
1491		.find(|(part, _)| *part == DecorPart::LineFeed)
1492		.map(|(_, range)| range.end)
1493}
1494
1495/**
1496Copies a span's endpoints without requiring a non-const Clone call.
1497*/
1498const fn copied_span(span: &Option<Range<usize>>) -> Option<Range<usize>> {
1499	match span {
1500		Some(span) => Some(span.start..span.end),
1501		None => None,
1502	}
1503}