use std::borrow::Cow;
use super::{
Decor, DecorPart, Entry, Member, Node, Object, Scalar, decor_parts, ends_in_line_comment,
has_line_feed, indentation_of, shares_line_with_next,
};
#[derive(Default)]
struct Gap<'a> {
end_of_line: Vec<Cow<'a, str>>,
lines: Vec<Option<Vec<Cow<'a, str>>>>,
inline: Vec<Cow<'a, str>>,
}
impl<'a> Gap<'a> {
fn read(decor: &'a str) -> Self {
Self::scan(decor, false, false)
}
fn read_document_start(decor: &'a str) -> Self {
Self::scan(decor, true, false)
}
fn scan(decor: &'a str, starts_line: bool, is_end: bool) -> Self {
let mut gap = Self::default();
let mut current = Vec::new();
let mut has_line_break = starts_line;
for (part, range) in decor_parts(decor) {
match part {
DecorPart::LineComment => {
current.push(decor[range].trim_end_matches([' ', '\t']).into())
}
DecorPart::BlockComment => {
if !has_line_break && decor[range.clone()].contains('\n') {
gap.end_of_line.append(&mut current);
}
current.push(block_comment(&decor[range]));
}
DecorPart::LineFeed if !has_line_break => {
gap.end_of_line.append(&mut current);
has_line_break = true;
}
DecorPart::LineFeed if current.is_empty() => {
if gap.lines.last().is_none_or(Option::is_some) {
gap.lines.push(None);
}
}
DecorPart::LineFeed => gap.lines.push(Some(std::mem::take(&mut current))),
}
}
if is_end && !has_line_break {
gap.end_of_line.append(&mut current);
}
gap.inline = current;
gap
}
fn read_end(decor: &'a str) -> Self {
Self::scan(decor, false, true)
}
fn lines_after_opening(&self) -> &[Option<Vec<Cow<'a, str>>>] {
self.lines.strip_prefix(&[None]).unwrap_or(&self.lines)
}
fn has_comments(&self) -> bool {
!self.end_of_line.is_empty()
|| self.lines.iter().any(Option::is_some)
|| !self.inline.is_empty()
}
fn all(&self) -> impl Iterator<Item = &str> {
self.end_of_line
.iter()
.chain(self.lines.iter().flatten().flatten())
.chain(&self.inline)
.map(AsRef::as_ref)
}
fn lines_before_closing(&self) -> impl Iterator<Item = Option<&[Cow<'a, str>]>> {
let lines = if self.inline.is_empty() {
self.lines.strip_suffix(&[None]).unwrap_or(&self.lines)
} else {
&self.lines
};
lines
.iter()
.map(Option::as_deref)
.chain((!self.inline.is_empty()).then_some(Some(self.inline.as_slice())))
}
}
fn joined_decor<'a>(before: &'a str, line_break: &str, after: &'a str) -> Cow<'a, str> {
if before.is_empty() && line_break.is_empty() {
return Cow::Borrowed(after);
}
if after.is_empty() && line_break.is_empty() {
return Cow::Borrowed(before);
}
Cow::Owned([before, line_break, after].concat())
}
fn block_comment(text: &str) -> Cow<'_, str> {
let mut previous_is_blank = false;
let mut start = 0;
let mut lines = text.split('\n');
let changed = loop {
let Some(line) = lines.next() else {
return Cow::Borrowed(text);
};
let trimmed = line.trim_end_matches([' ', '\t']);
let is_blank = trimmed.is_empty();
if trimmed.len() != line.len() || is_blank && previous_is_blank {
break line;
}
previous_is_blank = is_blank;
start += line.len() + 1;
};
let mut output = String::with_capacity(text.len());
let prefix = &text[..start];
output.push_str(prefix.strip_suffix('\n').unwrap_or(prefix));
let mut is_first = start == 0;
for line in std::iter::once(changed).chain(lines) {
let line = line.trim_end_matches([' ', '\t']);
if line.is_empty() && previous_is_blank {
continue;
}
if !is_first {
output.push('\n');
}
output.push_str(line);
previous_is_blank = line.is_empty();
is_first = false;
}
Cow::Owned(output)
}
#[derive(Default)]
struct Formatter {
output: String,
line: String,
indentation: usize,
is_line_closed: bool,
}
impl Formatter {
fn start_line(&mut self, indentation: usize) {
self.indentation = indentation;
}
fn push(&mut self, text: &str, indentation: usize) {
if self.is_line_closed {
self.end_line();
self.start_line(indentation);
}
self.line.push_str(text);
}
fn end_line(&mut self) {
if !self.line.is_empty() {
self.output
.extend(std::iter::repeat_n('\t', self.indentation));
self.output.push_str(&self.line);
self.line.clear();
}
self.output.push('\n');
self.is_line_closed = false;
}
fn comments<'a>(&mut self, comments: impl IntoIterator<Item = &'a str>, indentation: usize) {
for comment in comments {
if self.is_line_closed {
self.end_line();
self.start_line(indentation);
} else if !self.line.is_empty() {
self.line.push(' ');
}
self.line.push_str(comment);
self.is_line_closed = comment.starts_with('#');
}
}
fn comments_before(&mut self, comments: &[Cow<'_, str>], indentation: usize) {
if !comments.is_empty() {
self.comments(comments.iter().map(AsRef::as_ref), indentation);
if !self.is_line_closed {
self.line.push(' ');
}
}
}
fn lines<'a>(
&mut self,
lines: impl IntoIterator<Item = Option<&'a [Cow<'a, str>]>>,
indentation: usize,
) {
for line in lines {
if let Some(comments) = line {
self.start_line(indentation);
self.comments(comments.iter().map(AsRef::as_ref), indentation);
}
self.end_line();
}
}
fn node(&mut self, node: &Node, indentation: usize, is_one_line: bool) {
match node {
Node::Object(object) if is_one_line || node.is_on_one_line() => self.one_line(
'{',
'}',
&object.members,
&object.closing,
indentation,
Self::member,
),
Node::Array(array) if is_one_line || node.is_on_one_line() => self.one_line(
'[',
']',
&array.items,
&array.closing,
indentation,
|formatter, item, indentation, is_one_line| {
formatter.node(&item.value, indentation, is_one_line)
},
),
Node::Object(object) => self.container(
'{',
'}',
&object.members,
&object.closing,
indentation,
Self::member,
),
Node::Array(array) => self.container(
'[',
']',
&array.items,
&array.closing,
indentation,
|formatter, item, indentation, is_one_line| {
formatter.node(&item.value, indentation, is_one_line)
},
),
Node::Scalar(scalar) => self.scalar(scalar, indentation),
}
}
fn member(&mut self, member: &Member, indentation: usize, is_one_line: bool) {
self.push("", indentation);
member.key.write(&mut self.line);
self.line.push(':');
let gap = Gap::read(&member.after_colon);
let is_block_string =
matches!(&member.value, Node::Scalar(scalar) if scalar.is_block_string());
if has_line_feed(&member.after_colon) && gap.has_comments() {
self.comments(gap.end_of_line.iter().map(AsRef::as_ref), indentation + 1);
self.end_line();
self.lines(
gap.lines.iter().filter_map(Option::as_deref).map(Some),
indentation + 1,
);
self.start_line(indentation + 1);
if is_block_string {
if !gap.inline.is_empty() {
self.comments(gap.inline.iter().map(AsRef::as_ref), indentation + 1);
self.end_line();
self.start_line(indentation + 1);
}
} else {
self.comments_before(&gap.inline, indentation + 1);
}
} else {
self.comments(gap.all(), indentation + 1);
if is_block_string {
self.end_line();
self.start_line(indentation + 1);
} else {
self.line.push(' ');
}
}
self.node(&member.value, self.indentation, is_one_line);
}
fn scalar(&mut self, scalar: &Scalar, indentation: usize) {
let Some(text) = scalar.raw.as_deref() else {
self.push("", indentation);
scalar.write(&mut self.line);
return;
};
let Some((opening, rest)) = text.split_once('\n') else {
self.push(text, indentation);
return;
};
self.push(opening, indentation);
self.end_line();
let (content, closing) = match rest.rsplit_once('\n') {
Some((content, closing)) => (Some(content), closing),
None => (None, rest),
};
let old_indentation = indentation_of(closing);
for line in content.into_iter().flat_map(|content| content.split('\n')) {
if line.bytes().all(|byte| byte == b' ' || byte == b'\t') {
self.output.push_str(line);
} else {
self.output.extend(std::iter::repeat_n('\t', indentation));
self.output
.push_str(line.strip_prefix(old_indentation).expect(
"every content line of a block string starts with the indentation of its closing delimiter",
));
}
self.output.push('\n');
}
self.start_line(indentation);
self.line.push_str(&closing[old_indentation.len()..]);
}
fn container<T: Entry>(
&mut self,
opening: char,
closing: char,
entries: &[T],
closing_decor: &str,
indentation: usize,
mut entry: impl FnMut(&mut Self, &T, usize, bool),
) {
let inner = indentation + 1;
self.push(opening.encode_utf8(&mut [0; 4]), indentation);
let Some(first) = entries.first() else {
let gap = Gap::read_end(closing_decor);
let mut lines = gap.lines_before_closing().peekable();
if lines.peek() == Some(&None) {
lines.next();
}
if gap.end_of_line.is_empty() && lines.peek().is_none() {
self.line.push(closing);
return;
}
self.comments(gap.end_of_line.iter().map(AsRef::as_ref), inner);
self.end_line();
self.lines(lines, inner);
self.start_line(indentation);
self.line.push(closing);
return;
};
let gap = Gap::read(&first.separator().decor.leading);
self.comments(gap.end_of_line.iter().map(AsRef::as_ref), inner);
self.end_line();
self.lines(
gap.lines_after_opening().iter().map(Option::as_deref),
inner,
);
self.start_line(inner);
self.comments_before(&gap.inline, inner);
for (index, current) in entries.iter().enumerate() {
let separator = current.separator();
self.start_line(inner);
entry(self, current, inner, false);
self.comments(Gap::read(&separator.before_comma).all(), inner);
let next = entries.get(index + 1);
let trailing = &separator.decor.trailing;
let after = next.map_or(closing_decor, |next| &next.separator().decor.leading);
let line_break = if ends_in_line_comment(trailing) && !after.starts_with('\n') {
"\n"
} else {
""
};
let decor = joined_decor(trailing, line_break, after);
self.gap_after(
Gap::scan(&decor, false, next.is_none()),
next.is_none(),
inner,
);
}
self.start_line(indentation);
self.line.push(closing);
}
fn one_line<T: Entry>(
&mut self,
opening: char,
closing: char,
entries: &[T],
closing_decor: &str,
indentation: usize,
mut entry: impl FnMut(&mut Self, &T, usize, bool),
) {
self.push(opening.encode_utf8(&mut [0; 4]), indentation);
let mut has_written = false;
for (index, current) in entries.iter().enumerate() {
let separator = current.separator();
self.inline_comments(&separator.decor.leading, &mut has_written);
if has_written {
self.line.push(' ');
}
entry(self, current, indentation, true);
has_written = true;
self.inline_comments(&separator.before_comma, &mut has_written);
if index + 1 < entries.len() {
self.line.push(',');
}
self.inline_comments(&separator.decor.trailing, &mut has_written);
}
self.inline_comments(closing_decor, &mut has_written);
self.line.push(closing);
}
fn inline_comments(&mut self, decor: &str, has_written: &mut bool) {
for (_, range) in decor_parts(decor) {
if *has_written {
self.line.push(' ');
}
self.line.push_str(&decor[range]);
*has_written = true;
}
}
fn bare_object(&mut self, object: &Object) {
let Some(first) = object.members.first() else {
self.start_line(0);
self.line.push_str("{}");
self.gap_after(Gap::read_end(&object.closing), true, 0);
return;
};
let gap = Gap::read_document_start(&first.separator.decor.leading);
self.lines(gap.lines_after_opening().iter().map(Option::as_deref), 0);
self.start_line(0);
self.comments_before(&gap.inline, 0);
for (index, member) in object.members.iter().enumerate() {
self.start_line(0);
self.member(member, 0, false);
let next = object.members.get(index + 1);
let after = next.map_or(object.closing.as_str(), |next| {
next.separator.decor.leading.as_str()
});
let trailing = &member.separator.decor.trailing;
let ends_line_comment =
ends_in_line_comment(trailing) && (next.is_some() || !after.is_empty());
let separates_members = shares_line_with_next(&object.members, index);
let line_break = if !after.starts_with('\n') && (ends_line_comment || separates_members)
{
"\n"
} else {
""
};
let decor = joined_decor(trailing, line_break, after);
self.gap_after(Gap::scan(&decor, false, next.is_none()), next.is_none(), 0);
}
}
fn gap_after(&mut self, gap: Gap<'_>, is_last: bool, indentation: usize) {
self.comments(gap.end_of_line.iter().map(AsRef::as_ref), indentation);
self.end_line();
if is_last {
self.lines(gap.lines_before_closing(), indentation);
} else {
self.lines(gap.lines.iter().map(Option::as_deref), indentation);
self.start_line(indentation);
self.comments_before(&gap.inline, indentation);
}
}
}
pub(crate) fn document(outer: &Decor, root: &Node, capacity: usize) -> String {
let mut formatter = Formatter {
output: String::with_capacity(capacity),
line: String::with_capacity(128),
..Formatter::default()
};
if let Node::Object(object) = root
&& !object.is_braced
{
formatter.bare_object(object);
} else {
let before = Gap::read_document_start(&outer.leading);
formatter.lines(before.lines_after_opening().iter().map(Option::as_deref), 0);
formatter.start_line(0);
formatter.comments_before(&before.inline, 0);
formatter.node(root, 0, false);
formatter.gap_after(Gap::read_end(&outer.trailing), true, 0);
}
formatter.output
}