use crate::config::Style;
use crate::options::StyleOption;
use crate::tokens::Stream;
pub fn columns(source: &str, stream: &Stream<'_>, style: &Style) -> Vec<Option<usize>> {
let minimum = style.count(StyleOption::SpacesBeforeTrailingComments);
let mut targets = vec![None; stream.gaps.len()];
let mut found: Vec<(usize, usize, usize)> = Vec::new(); let mut line = 0usize;
for index in 0..stream.gaps.len() {
line += stream.gaps[index].newlines;
let Some(comment) = stream.gaps[index].comments.last() else {
continue;
};
if comment.own_line {
continue;
}
let start_of_line = source[..comment.start].rfind('\n').map_or(0, |at| at + 1);
let code = source[start_of_line..comment.start].trim_end();
found.push((line, index, code.chars().count()));
}
let mut start = 0usize;
while start < found.len() {
let mut end = start + 1;
while end < found.len() && found[end].0 == found[end - 1].0 + 1 {
end += 1;
}
let widest = found[start..end]
.iter()
.map(|(_, _, code_end)| *code_end)
.max()
.unwrap_or(0);
for (_, index, _) in &found[start..end] {
targets[*index] = Some(widest + minimum);
}
start = end;
}
targets
}
pub fn align(output: &str, style: &Style) -> String {
let minimum = style.count(StyleOption::SpacesBeforeTrailingComments);
let lines: Vec<&str> = output.split_inclusive('\n').collect();
if lines.is_empty() {
return output.to_string();
}
let mut found: Vec<(usize, &str, &str)> = Vec::new();
for (index, line) in lines.iter().enumerate() {
if let Some((code, comment)) = split_trailing_comment(line) {
found.push((index, code.trim_end(), comment));
}
}
let mut rewritten: Vec<Option<String>> = vec![None; lines.len()];
let mut start = 0usize;
while start < found.len() {
let mut end = start + 1;
while end < found.len() && found[end].0 == found[end - 1].0 + 1 {
end += 1;
}
let column = found[start..end]
.iter()
.map(|(_, code, comment)| width(code) + start_spaces(code, comment, minimum))
.max()
.unwrap_or(0);
for (index, code, comment) in &found[start..end] {
let spaces = column.saturating_sub(width(code));
rewritten[*index] = Some(format!("{code}{}{comment}", " ".repeat(spaces)));
}
start = end;
}
let mut out = String::with_capacity(output.len());
for (index, line) in lines.iter().enumerate() {
match &rewritten[index] {
Some(replacement) => out.push_str(replacement),
None => out.push_str(line),
}
}
out
}
fn start_spaces(code: &str, comment: &str, minimum: usize) -> usize {
if code.trim_start().starts_with('{') && code.trim_end().ends_with('}') {
return minimum + 2;
}
if code.trim_start().starts_with('{') && code.trim_end().ends_with(',') {
return minimum + 1;
}
if comment.starts_with("/*") {
minimum.max(1)
} else {
minimum
}
}
fn split_trailing_comment(line: &str) -> Option<(&str, &str)> {
let bytes = line.as_bytes();
let mut index = 0usize;
let mut quote: Option<u8> = None;
let mut seen_code = false;
while index < bytes.len() {
let byte = bytes[index];
if let Some(open) = quote {
if byte == b'\\' {
index += 2;
continue;
}
if byte == open {
quote = None;
}
index += 1;
continue;
}
match byte {
b'"' | b'\'' => {
quote = Some(byte);
seen_code = true;
index += 1;
}
b'/' if index + 1 < bytes.len()
&& (bytes[index + 1] == b'/' || bytes[index + 1] == b'*') =>
{
if !seen_code {
return None;
}
let rest = &line[index..];
let ends_the_line = if bytes[index + 1] == b'/' {
true
} else {
rest.find("*/")
.is_some_and(|close| rest[close + 2..].trim().is_empty())
};
if !ends_the_line {
return None;
}
return Some((&line[..index], rest));
}
b' ' | b'\t' | b'\r' | b'\n' => index += 1,
_ => {
seen_code = true;
index += 1;
}
}
}
None
}
fn width(text: &str) -> usize {
crate::columns::Columns::new(&Style::default_style()).advance(0, text)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Style;
use crate::tokens::stream;
fn targets(source: &str, minimum: &str) -> Vec<Option<usize>> {
let mut style = Style::default_style();
style.set_from_text("SpacesBeforeTrailingComments", minimum);
let stream = stream(source);
columns(source, &stream, &style)
.into_iter()
.filter(|target| target.is_some())
.collect()
}
#[test]
fn a_run_of_comments_shares_one_column() {
let found = targets("enum E {\n A, // one\n CCCC,// two\n};\n", "1");
assert_eq!(found, vec![Some(10), Some(10)]);
}
#[test]
fn a_lone_comment_is_its_own_group() {
let found = targets("int solo;// alone\nint after;\n", "0");
assert_eq!(found, vec![Some(9)]);
}
#[test]
fn the_minimum_is_added_once() {
let found = targets("int solo; // alone\n", "2");
assert_eq!(found, vec![Some(11)]);
}
#[test]
fn a_run_is_aligned_and_a_lone_comment_is_not() {
let output = "enum E {\n A, // one\n CCCC,// two\n};\nint solo; // alone\n";
let mut style = Style::default_style();
style.set_from_text("SpacesBeforeTrailingComments", "1");
assert_eq!(
align(output, &style),
"enum E {\n A, // one\n CCCC, // two\n};\nint solo; // alone\n"
);
}
#[test]
fn a_comment_inside_a_string_is_not_a_comment() {
let mut style = Style::default_style();
style.set_from_text("SpacesBeforeTrailingComments", "0");
let output = "const char *s = \"// not a comment\";\n";
assert_eq!(align(output, &style), output);
}
#[test]
fn a_line_comment_sits_against_the_code_and_a_block_comment_does_not() {
let mut style = Style::default_style();
style.set_from_text("SpacesBeforeTrailingComments", "0");
assert_eq!(
align(" TK_GLOBAL, // x\n", &style),
" TK_GLOBAL,// x\n"
);
assert_eq!(
align(
" unsigned char left; /* a */\n unsigned char right; /* b */\n",
&style
),
" unsigned char left; /* a */\n unsigned char right; /* b */\n"
);
}
#[test]
fn an_own_line_comment_is_not_a_trailing_one() {
let found = targets("void f() {\n // note\n}\n", "1");
assert!(found.is_empty(), "{found:?}");
}
}