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, usize)> = Vec::new(); let mut line = 0usize;
for (index, gap) in stream.gaps.iter().enumerate() {
line += gap.newlines;
let Some(comment) = gap.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(),
comment.text.trim_end().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 entries: Vec<(usize, usize, usize)> = found[start..end]
.iter()
.map(|(_, _, code_end, comment_width)| (*code_end, *comment_width, minimum))
.collect();
let limit = style.count(StyleOption::ColumnLimit);
let columns = run_columns(&entries, limit);
for (offset, (_, index, code_end, _)) in found[start..end].iter().enumerate() {
targets[*index] = Some(match columns[offset] {
Some(column) => column,
None => code_end + 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();
let mut in_block = false;
for (index, line) in lines.iter().enumerate() {
if let Some((code, comment)) = split_trailing_comment(line, &mut in_block) {
found.push((index, code.trim_end(), comment));
}
}
let mut rewritten: Vec<Option<String>> = vec![None; lines.len()];
let comment_only: Vec<bool> = lines
.iter()
.map(|line| line.trim_start().starts_with("//") || line.trim_start().starts_with("/*"))
.collect();
let continues_through_comments =
|from: usize, to: usize| from < to && (from + 1..to).all(|between| comment_only[between]);
let mut trailing_column: Vec<Option<usize>> = 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
|| continues_through_comments(found[end - 1].0, found[end].0))
{
end += 1;
}
let limit = style.count(StyleOption::ColumnLimit);
let entries: Vec<(usize, usize, usize)> = found[start..end]
.iter()
.map(|(_, code, comment)| {
(
width(code),
width(comment.trim_end()),
start_spaces(code, comment, minimum),
)
})
.collect();
let columns = run_columns(&entries, limit);
for (offset, (index, code, comment)) in found[start..end].iter().enumerate() {
let spaces = match columns[offset] {
Some(column) => {
trailing_column[*index] = Some(column);
column.saturating_sub(width(code))
}
None => start_spaces(code, comment, minimum),
};
rewritten[*index] = Some(format!("{code}{}{comment}", " ".repeat(spaces)));
}
start = end;
}
let indentation = |line: &str| {
line.chars()
.take_while(|character| *character == ' ')
.count()
};
for index in 1..lines.len() {
if !comment_only[index] {
continue;
}
let Some(column) = trailing_column[index - 1] else {
continue;
};
let trimmed = lines[index].trim_start();
if !trimmed.starts_with("///") {
continue;
}
if indentation(lines[index]) <= indentation(lines[index - 1]) {
continue;
}
let ending = if trimmed.ends_with('\n') { "\n" } else { "" };
rewritten[index] = Some(format!(
"{}{}{ending}",
" ".repeat(column),
trimmed.trim_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 run_columns(entries: &[(usize, usize, usize)], limit: usize) -> Vec<Option<usize>> {
let mut columns = vec![None; entries.len()];
let mut pending: Vec<(usize, usize)> = vec![(0, entries.len())];
while let Some((start, end)) = pending.pop() {
if start >= end {
continue;
}
let column = (start..end)
.map(|at| entries[at].0 + entries[at].2)
.max()
.unwrap_or(0);
let too_long = (start..end).find(|at| limit > 0 && column + entries[*at].1 > limit);
match too_long {
Some(at) => {
pending.push((at + 1, end));
pending.push((start, at));
}
None => {
columns[start..end].fill(Some(column));
}
}
}
columns
}
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<'a>(line: &'a str, in_block: &mut bool) -> Option<(&'a str, &'a 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 *in_block {
if byte == b'*' && index + 1 < bytes.len() && bytes[index + 1] == b'/' {
*in_block = false;
index += 2;
continue;
}
index += 1;
continue;
}
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'*' => {
match line[index + 2..].find("*/") {
Some(close) => {
let after = index + 2 + close + 2;
if line[after..].trim().is_empty() {
if !seen_code {
return None;
}
return Some((&line[..index], &line[index..]));
}
index = after;
seen_code = true;
}
None => {
*in_block = true;
return None;
}
}
}
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 a_comment_past_the_column_limit_keeps_its_own_start_and_splits_the_run() {
let source = "\
#include <algorithm> // any_of
#include <array> // array
#include <type_traits> // conditional, integral_constant, is_signed, true_type, false_type
#include <utility> // move
";
let style = Style::default_style();
let expected = "\
#include <algorithm> // any_of
#include <array> // array
#include <type_traits> // conditional, integral_constant, is_signed, true_type, false_type
#include <utility> // move
";
assert_eq!(align(source, &style), expected);
}
#[test]
fn a_url_inside_a_block_comment_is_not_a_trailing_comment() {
let source = "/*!\n@brief x\nhttp://example.com/a (b).\n*/\nint x;\n";
let style = Style::default_style();
assert_eq!(align(source, &style), source);
}
#[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:?}");
}
}