use crate::error::{GeneratorError, GeneratorResult};
use log::debug;
#[derive(Debug, Clone)]
pub struct FormatterConfig {
pub indent_width: usize,
pub use_tabs: bool,
pub line_width: usize,
pub bracket_style: BracketStyle,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BracketStyle {
AllmanStyle, KandRStyle, }
impl Default for FormatterConfig {
fn default() -> Self {
FormatterConfig {
indent_width: 2,
use_tabs: false,
line_width: 100,
bracket_style: BracketStyle::KandRStyle,
}
}
}
pub struct CodeFormatter {
config: FormatterConfig,
}
impl CodeFormatter {
pub fn new(config: FormatterConfig) -> Self {
CodeFormatter { config }
}
pub fn default() -> Self {
Self::new(FormatterConfig::default())
}
pub fn format(&self, code: &str) -> GeneratorResult<String> {
debug!("Formatting code ({} chars)", code.len());
let mut result = String::with_capacity(code.len());
let mut indent_level = 0;
let mut in_string = false;
let mut string_char = '"';
let mut prev_char = ' ';
let mut line_length = 0;
let chars: Vec<char> = code.chars().collect();
let mut i = 0;
while i < chars.len() {
let ch = chars[i];
if (ch == '"' || ch == '\'' || ch == '`') && prev_char != '\\' {
if !in_string {
in_string = true;
string_char = ch;
} else if ch == string_char {
in_string = false;
}
result.push(ch);
line_length += 1;
prev_char = ch;
i += 1;
continue;
}
if in_string {
result.push(ch);
line_length += 1;
prev_char = ch;
i += 1;
continue;
}
if ch.is_whitespace() {
if ch == '\n' {
result.push('\n');
result.push_str(&self.indent_str(indent_level));
line_length = indent_level * self.config.indent_width;
prev_char = '\n';
i += 1;
continue;
}
if prev_char != ' ' && prev_char != '\n' && prev_char != '{' && prev_char != '(' && prev_char != ':' && prev_char != ',' {
result.push(' ');
line_length += 1;
}
prev_char = ' ';
i += 1;
continue;
}
match ch {
'{' => {
result.push(ch);
result.push('\n');
indent_level += 1;
result.push_str(&self.indent_str(indent_level));
line_length = indent_level * self.config.indent_width;
}
'}' => {
if !result.ends_with('\n') && !result.ends_with(' ') {
result.push('\n');
}
indent_level = indent_level.saturating_sub(1);
result.push_str(&self.indent_str(indent_level));
result.push(ch);
line_length = indent_level * self.config.indent_width + 1;
}
';' => {
result.push(ch);
result.push('\n');
result.push_str(&self.indent_str(indent_level));
line_length = indent_level * self.config.indent_width;
}
',' => {
result.push(ch);
result.push(' ');
line_length += 2;
}
'(' | '[' => {
result.push(ch);
line_length += 1;
}
')' | ']' => {
result.push(ch);
line_length += 1;
}
':' => {
result.push(ch);
result.push(' ');
line_length += 2;
}
_ => {
result.push(ch);
line_length += 1;
}
}
prev_char = ch;
i += 1;
}
while result.ends_with('\n') || result.ends_with(' ') {
if result.ends_with('\n') {
break;
}
result.pop();
}
Ok(result)
}
pub fn minify(&self, code: &str) -> GeneratorResult<String> {
debug!("Minifying code ({} chars)", code.len());
let mut result = String::new();
let mut in_string = false;
let mut string_char = '"';
let mut prev_was_space = false;
for (i, ch) in code.chars().enumerate() {
if (ch == '"' || ch == '\'' || ch == '`') && (i == 0 || code.chars().nth(i - 1) != Some('\\')) {
if !in_string {
in_string = true;
string_char = ch;
} else if ch == string_char {
in_string = false;
}
}
if in_string {
result.push(ch);
prev_was_space = false;
continue;
}
if ch.is_whitespace() {
if !prev_was_space
&& !result.ends_with('(')
&& !result.ends_with('{')
&& !result.ends_with('[')
&& !result.ends_with(',')
{
result.push(' ');
prev_was_space = true;
}
continue;
}
if ch == '/' {
if let Some(next) = code.chars().nth(i + 1) {
if next == '/' {
break;
} else if next == '*' {
let rest = &code[i + 2..];
if let Some(end) = rest.find("*/") {
continue;
}
}
}
}
result.push(ch);
prev_was_space = false;
}
Ok(result.trim().to_string())
}
fn indent_str(&self, level: usize) -> String {
if self.config.use_tabs {
"\t".repeat(level)
} else {
" ".repeat(level * self.config.indent_width)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_simple() {
let formatter = CodeFormatter::default();
let code = "var x = { a: 1, b: 2 };";
let formatted = formatter.format(code).unwrap();
assert!(formatted.contains("a: 1"));
}
#[test]
fn test_minify_removes_whitespace() {
let formatter = CodeFormatter::default();
let code = "var x = 1 ;";
let minified = formatter.minify(code).unwrap();
assert_eq!(minified, "var x = 1 ;");
}
#[test]
fn test_preserve_strings() {
let formatter = CodeFormatter::default();
let code = r#"var x = "hello world";"#;
let formatted = formatter.format(code).unwrap();
assert!(formatted.contains("hello world"));
}
}