1use crate::scalar;
29use crate::{Value, parse, write};
30use std::borrow::Cow;
31use std::ops::Range;
32
33pub(crate) mod format;
34
35#[derive(Debug, Clone, PartialEq, Eq, Default)]
39pub struct Decor {
40 pub leading: String,
44 pub trailing: String,
48}
49
50#[derive(Debug, Clone, PartialEq)]
54pub enum Node {
55 Object(Object),
59 Array(Array),
63 Scalar(Scalar),
67}
68
69#[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#[derive(Debug, Clone, PartialEq)]
84pub struct Member {
85 key: Key,
86 pub(crate) after_colon: Cow<'static, str>,
90 value: Node,
91 separator: Separator,
92 span: Option<Range<usize>>,
93}
94
95impl 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#[derive(Debug, Clone, PartialEq, Default)]
113pub struct Array {
114 items: Vec<Item>,
115 closing: String,
116 span: Option<Range<usize>>,
117}
118
119#[derive(Debug, Clone, PartialEq)]
123pub struct Item {
124 value: Node,
125 separator: Separator,
126}
127
128#[derive(Debug, Clone, PartialEq, Default)]
132pub(crate) struct Separator {
133 pub(crate) decor: Decor,
134 pub(crate) has_comma: bool,
138 pub(crate) before_comma: String,
142}
143
144pub(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 fn print(&self, printer: &mut Printer);
156}
157
158pub(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#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct Key {
218 value: String,
219 raw: Option<String>,
223 span: Option<Range<usize>>,
224}
225
226#[derive(Debug, Clone, PartialEq)]
230pub struct Scalar {
231 value: Value,
232 raw: Option<String>,
233 span: Option<Range<usize>>,
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum StringStyle {
241 Bare,
245 Literal,
249 Escaped,
253 LiteralBlock,
257 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
279pub enum CommentKind {
280 Line,
284 Block,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294pub enum Radix {
295 Binary = 2,
299 Octal = 8,
303 Decimal = 10,
307 Hexadecimal = 16,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct Comment {
318 pub text: String,
322 pub kind: CommentKind,
326 pub span: Range<usize>,
330}
331
332impl Node {
333 pub fn new(value: impl Into<Value>) -> Result<Self, crate::Error> {
349 Ok(Self::laid_out(checked(value.into())?, Some("")))
350 }
351
352 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 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 #[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 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 #[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 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 #[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 #[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 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 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
529fn is_decor_on_one_line(decor: &str) -> bool {
533 !decor.contains('\n') && (!decor.contains('#') || !ends_in_line_comment(decor))
534}
535
536impl Object {
537 #[must_use]
541 pub const fn members(&self) -> &[Member] {
542 self.members.as_slice()
543 }
544
545 pub const fn members_mut(&mut self) -> &mut Vec<Member> {
549 &mut self.members
550 }
551
552 #[must_use]
556 pub const fn is_braced(&self) -> bool {
557 self.is_braced
558 }
559
560 #[must_use]
564 pub const fn closing_decor(&self) -> &str {
565 self.closing.as_str()
566 }
567
568 pub const fn closing_decor_mut(&mut self) -> &mut String {
572 &mut self.closing
573 }
574
575 pub(crate) fn position(&self, key: &str) -> Option<usize> {
579 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 #[must_use]
599 pub const fn items(&self) -> &[Item] {
600 self.items.as_slice()
601 }
602
603 pub const fn items_mut(&mut self) -> &mut Vec<Item> {
607 &mut self.items
608 }
609
610 #[must_use]
614 pub const fn closing_decor(&self) -> &str {
615 self.closing.as_str()
616 }
617
618 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 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 #[must_use]
659 pub const fn key(&self) -> &Key {
660 &self.key
661 }
662
663 pub const fn key_mut(&mut self) -> &mut Key {
667 &mut self.key
668 }
669
670 #[must_use]
674 pub const fn value(&self) -> &Node {
675 &self.value
676 }
677
678 pub const fn value_mut(&mut self) -> &mut Node {
682 &mut self.value
683 }
684
685 #[must_use]
689 pub const fn decor(&self) -> &Decor {
690 &self.separator.decor
691 }
692
693 pub const fn decor_mut(&mut self) -> &mut Decor {
697 &mut self.separator.decor
698 }
699
700 #[must_use]
704 pub const fn span(&self) -> Option<Range<usize>> {
705 copied_span(&self.span)
706 }
707}
708
709impl Item {
710 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 #[must_use]
728 pub const fn value(&self) -> &Node {
729 &self.value
730 }
731
732 pub const fn value_mut(&mut self) -> &mut Node {
736 &mut self.value
737 }
738
739 #[must_use]
743 pub const fn decor(&self) -> &Decor {
744 &self.separator.decor
745 }
746
747 pub const fn decor_mut(&mut self) -> &mut Decor {
751 &mut self.separator.decor
752 }
753}
754
755impl Separator {
756 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 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
795pub(crate) fn checked(value: Value) -> Result<Value, crate::Error> {
799 value.check(1)?;
801 Ok(value)
802}
803
804impl Key {
805 #[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 #[must_use]
837 pub const fn value(&self) -> &str {
838 self.value.as_str()
839 }
840
841 #[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 #[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 #[must_use]
870 pub const fn span(&self) -> Option<Range<usize>> {
871 copied_span(&self.span)
872 }
873}
874
875impl Key {
876 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
889impl 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 fn write(&self, output: &mut String) {
906 if let Some(raw) = &self.raw {
907 output.push_str(raw);
908 return;
909 }
910
911 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 #[must_use]
930 pub const fn value(&self) -> &Value {
931 &self.value
932 }
933
934 #[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 #[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 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 #[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 #[must_use]
999 pub const fn span(&self) -> Option<Range<usize>> {
1000 copied_span(&self.span)
1001 }
1002}
1003
1004pub(crate) struct Parts {
1008 pub outer: Decor,
1009 pub root: Node,
1010}
1011
1012pub(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 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 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 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 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 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 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 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 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 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 (entries, self.source[leading_start..end - 1].to_owned())
1228 }
1229}
1230
1231pub(crate) struct Printer {
1235 pub output: String,
1236 pub comments: Option<Vec<Comment>>,
1237 pub needs_line_feed: bool,
1241}
1242
1243impl Printer {
1244 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 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 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 if index > 0 && shares_line_with_next(&object.members, index - 1) {
1296 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 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 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 fn decor(&mut self, decor: &str) {
1358 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 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 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#[derive(Clone, Copy, PartialEq, Eq)]
1396pub(crate) enum DecorPart {
1397 LineFeed,
1401 LineComment,
1402 BlockComment,
1403}
1404
1405pub(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 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
1448pub(crate) fn indentation_of(line: &str) -> &str {
1452 &line[..line.len() - line.trim_start_matches([' ', '\t']).len()]
1453}
1454
1455pub(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
1466pub(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
1478pub(crate) fn has_line_feed(decor: &str) -> bool {
1482 first_line_end(decor).is_some()
1484}
1485
1486pub(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
1495const 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}