use crate::{compile_with, CompileOptions, Diagnostic, Song, Span};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FormatOptions {
pub width: usize,
pub normalize: bool,
}
impl Default for FormatOptions {
fn default() -> Self {
Self {
width: 100,
normalize: false,
}
}
}
pub fn format(
src: &str,
fmt: &FormatOptions,
opts: &CompileOptions<'_>,
) -> Result<String, Vec<Diagnostic>> {
let (song, diags) = compile_with(src, opts);
let Some(original) = song else {
return Err(diags.into_iter().filter(|d| d.is_error()).collect());
};
let reference = strip(&original);
let same = |text: &str| -> bool {
compile_with(text, opts)
.0
.is_some_and(|s| strip(&s) == reference)
};
let mut best = src.to_string();
let tidied = tidy(src);
if same(&tidied) {
best = tidied;
}
let spaced = tidy_with_spaces(&best);
if same(&spaced) {
best = spaced;
}
if fmt.normalize {
best = normalize_lines(&best, &same);
}
if fmt.width > 0 {
best = wrap_lines(&best, fmt.width, &same);
}
Ok(best)
}
fn strip(song: &Song) -> Song {
let mut s = song.clone();
for e in &mut s.events {
e.span = Span::default();
}
for shot in &mut s.shots {
*shot.song = strip(&shot.song);
}
s
}
fn split_comment(line: &str) -> (&str, &str) {
match line.find(';') {
Some(i) => line.split_at(i),
None => (line, ""),
}
}
fn track_name_len(code: &str) -> Option<usize> {
let n = code.chars().take_while(|c| c.is_ascii_uppercase()).count();
let rest = &code[n..];
(n > 0 && rest.starts_with([' ', '\t'])).then_some(n)
}
fn tidy(src: &str) -> String {
let mut out = String::new();
let mut blank = 0;
for raw in src.lines() {
let line = raw.trim_end();
if line.is_empty() {
blank += 1;
continue;
}
if blank > 0 && !out.is_empty() {
out.push('\n');
}
blank = 0;
out.push_str(line);
out.push('\n');
}
out
}
fn tidy_with_spaces(src: &str) -> String {
let mut out = String::new();
for line in src.split_inclusive('\n') {
let body = line.strip_suffix('\n').unwrap_or(line);
out.push_str(&squeeze_line(body));
if line.ends_with('\n') {
out.push('\n');
}
}
out
}
fn squeeze_line(line: &str) -> String {
let (code, comment) = split_comment(line);
let Some(n) = track_name_len(code) else {
return line.to_string();
};
let (name, body) = code.split_at(n);
let mut s = String::from(name);
let mut in_quote = false;
let mut pending_space = false;
let mut started = false;
for c in body.chars() {
if c == '\'' {
in_quote = !in_quote;
}
if !in_quote && c.is_whitespace() {
pending_space = true;
continue;
}
if pending_space {
s.push(' ');
pending_space = false;
}
started = true;
s.push(c);
}
if !comment.is_empty() {
if started {
s.push_str(" ");
}
s.push_str(comment.trim_end());
}
s
}
fn break_points(body: &str) -> Vec<usize> {
let mut v = Vec::new();
let (mut quote, mut brace) = (false, 0i32);
for (i, c) in body.char_indices() {
match c {
'\'' => quote = !quote,
'{' if !quote => brace += 1,
'}' if !quote => brace -= 1,
' ' if !quote && brace == 0 => v.push(i),
_ => {}
}
}
v
}
fn wrap_lines(src: &str, width: usize, same: &dyn Fn(&str) -> bool) -> String {
let lines: Vec<String> = src.lines().map(str::to_string).collect();
let mut current = lines.clone();
for i in 0..lines.len() {
let line = &lines[i];
if line.chars().count() <= width || line.contains(';') {
continue;
}
let Some(n) = track_name_len(line) else {
continue;
};
let name = &line[..n];
let body = &line[n + 1..];
let points = break_points(body);
let head = n + 1;
let mut pieces: Vec<&str> = Vec::new();
let mut start = 0;
let mut last_ok: Option<usize> = None;
for &p in &points {
if head + body[start..p].chars().count() > width {
if let Some(l) = last_ok.take() {
pieces.push(&body[start..l]);
start = l + 1;
if head + body[start..p].chars().count() > width {
last_ok = Some(p);
continue;
}
}
}
last_ok = Some(p);
}
pieces.push(&body[start..]);
if pieces.len() < 2 {
continue;
}
let wrapped = pieces
.iter()
.map(|p| format!("{name} {p}"))
.collect::<Vec<_>>()
.join("\n");
let saved = current[i].clone();
current[i] = wrapped;
let mut text = current.join("\n");
text.push('\n');
if !same(&text) {
current[i] = saved;
}
}
let mut text = current.join("\n");
if !text.is_empty() {
text.push('\n');
}
text
}
const ABBREVIATIONS: &[(&str, &str)] = &[
("mpof", "@vib off"),
("epof", "@detune off"),
("enof", "@arp off"),
("mp", "@vib"),
("ep", "@detune"),
("en", "@arp"),
];
fn normalize_code(code: &str) -> Option<String> {
let chars: Vec<char> = code.chars().collect();
let mut out = String::new();
let mut changed = false;
let mut in_quote = false;
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c == '\'' {
in_quote = !in_quote;
}
if in_quote || !c.is_ascii_lowercase() {
out.push(c);
i += 1;
continue;
}
let start = i;
while i < chars.len() && chars[i].is_ascii_lowercase() {
i += 1;
}
let word: String = chars[start..i].iter().collect();
let prev = start.checked_sub(1).map(|p| chars[p]);
let named = prev
.is_some_and(|p| matches!(p, '$' | '@' | '%' | '!' | '_') || p.is_ascii_alphanumeric());
let next_ok = chars
.get(i)
.is_none_or(|n| !(n.is_ascii_alphanumeric() || *n == '_'));
let replaced = if named || !next_ok {
None
} else {
ABBREVIATIONS.iter().find_map(|(short, long)| {
if word == *short {
Some((String::new(), *long))
} else {
let head = word.strip_suffix(short)?;
(head.len() == 1 && "abcdefgr".contains(head))
.then(|| (format!("{head} "), *long))
}
})
};
match replaced {
Some((head, long)) => {
out.push_str(&head);
out.push_str(long);
changed = true;
}
None => out.push_str(&word),
}
}
changed.then_some(out)
}
fn normalize_lines(src: &str, same: &dyn Fn(&str) -> bool) -> String {
let lines: Vec<String> = src.lines().map(str::to_string).collect();
let mut current = lines.clone();
let join = |v: &[String]| {
let mut t = v.join("\n");
if !t.is_empty() {
t.push('\n');
}
t
};
for i in 0..lines.len() {
let (code, comment) = split_comment(&lines[i]);
if track_name_len(code).is_none() {
continue;
}
let Some(new_code) = normalize_code(code) else {
continue;
};
let saved = current[i].clone();
current[i] = format!("{new_code}{comment}");
if !same(&join(¤t)) {
current[i] = saved;
}
}
join(¤t)
}