use crate::ast::{ArrayForm, AstNode, NumberValue, ObjectEntry};
use tower_lsp::lsp_types::FormattingOptions;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToonFormattingOptions {
pub indent_size: u32,
}
impl Default for ToonFormattingOptions {
fn default() -> Self {
Self { indent_size: 2 }
}
}
impl From<&FormattingOptions> for ToonFormattingOptions {
fn from(opts: &FormattingOptions) -> Self {
Self {
indent_size: opts.tab_size.clamp(1, 8),
}
}
}
struct FormattingContext {
options: ToonFormattingOptions,
indent_level: u32,
output: String,
}
impl FormattingContext {
fn new(options: ToonFormattingOptions) -> Self {
Self { options, indent_level: 0, output: String::new() }
}
fn indent(&self) -> String {
" ".repeat((self.indent_level * self.options.indent_size) as usize)
}
fn push(&mut self, s: &str) {
self.output.push_str(s);
}
fn newline(&mut self) {
self.output.push('\n');
}
}
pub fn format_document(ast: &AstNode, options: ToonFormattingOptions) -> Option<String> {
let mut ctx = FormattingContext::new(options);
format_node(ast, &mut ctx, false);
if !ctx.output.ends_with('\n') {
ctx.newline();
}
Some(ctx.output)
}
fn format_node(node: &AstNode, ctx: &mut FormattingContext, is_value: bool) {
match node {
AstNode::Document { children, .. } => {
for child in children {
format_node(child, ctx, false);
}
}
AstNode::Object { entries, .. } => {
for entry in entries {
format_object_entry(entry, ctx);
}
}
AstNode::Array { items, form, .. } => {
format_array(items, *form, ctx, is_value);
}
AstNode::String { value, .. } => {
if value.contains('\n') {
ctx.push(&format!("\"\"\"{}\"\"\"", value));
} else if needs_quotes(value) {
ctx.push(&format!("\"{}\"", escape_string(value)));
} else {
ctx.push(value);
}
}
AstNode::Number { value, .. } => {
ctx.push(&format_number(*value));
}
AstNode::Bool { value, .. } => {
ctx.push(if *value { "true" } else { "false" });
}
AstNode::Null { .. } => {
ctx.push("null");
}
AstNode::Reference { path, .. } => {
ctx.push(&format!("${{{}}}", path));
}
}
}
fn format_object_entry(entry: &ObjectEntry, ctx: &mut FormattingContext) {
ctx.push(&ctx.indent());
ctx.push(&entry.key);
ctx.push(": ");
match &entry.value {
AstNode::Object { .. } => {
ctx.newline();
ctx.indent_level += 1;
format_node(&entry.value, ctx, false);
ctx.indent_level -= 1;
}
AstNode::Array { form: ArrayForm::Expanded | ArrayForm::Tabular, .. } => {
ctx.newline();
ctx.indent_level += 1;
format_node(&entry.value, ctx, true);
ctx.indent_level -= 1;
}
_ => {
format_node(&entry.value, ctx, true);
ctx.newline();
}
}
}
fn format_array(items: &[AstNode], form: ArrayForm, ctx: &mut FormattingContext, _is_value: bool) {
match form {
ArrayForm::Inline => {
if items.len() > 3 {
ctx.push("[\n");
ctx.indent_level += 1;
for item in items {
ctx.push(&ctx.indent());
format_node(item, ctx, true);
ctx.push(",\n");
}
ctx.indent_level -= 1;
ctx.push(&ctx.indent());
ctx.push("]");
} else {
ctx.push("[");
for (i, item) in items.iter().enumerate() {
if i > 0 {
ctx.push(", ");
}
format_node(item, ctx, true);
}
ctx.push("]");
}
}
ArrayForm::Expanded => {
for item in items {
ctx.push(&ctx.indent());
ctx.push("- ");
format_node(item, ctx, true);
ctx.newline();
}
}
ArrayForm::Tabular => {
for item in items {
format_tabular_row(item, ctx);
}
}
}
}
fn format_tabular_row(node: &AstNode, ctx: &mut FormattingContext) {
if let AstNode::Object { entries, .. } = node {
ctx.push(&ctx.indent());
ctx.push("| ");
for (i, entry) in entries.iter().enumerate() {
if i > 0 {
ctx.push(" | ");
}
format_node(&entry.value, ctx, true);
}
ctx.push(" |");
ctx.newline();
}
}
fn needs_quotes(s: &str) -> bool {
s.is_empty()
|| s.contains(':')
|| s.contains(',')
|| s.contains('[')
|| s.contains(']')
|| s.contains('{')
|| s.contains('}')
|| s.contains('|')
|| s.contains('-')
|| s.contains('"')
|| s.contains('\\')
|| s.starts_with(' ')
|| s.ends_with(' ')
|| s == "true"
|| s == "false"
|| s == "null"
|| s.parse::<f64>().is_ok()
}
fn escape_string(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
fn format_number(value: NumberValue) -> String {
match value {
NumberValue::PosInt(n) => n.to_string(),
NumberValue::NegInt(n) => n.to_string(),
NumberValue::Float(n) => {
if n.fract() == 0.0 && n.is_finite() { format!("{:.1}", n) } else { n.to_string() }
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::parse_with_errors;
fn parse(source: &str) -> AstNode {
let (ast, errors) = parse_with_errors(source);
assert!(errors.is_empty(), "Parse errors: {:?}", errors);
ast.expect("Expected valid AST")
}
#[test]
fn test_format_2_space_indent() {
let source = "user:\n name: Alice\n age: 30"; let ast = parse(source);
let opts = ToonFormattingOptions { indent_size: 2 };
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("user:"), "Missing 'user:' key");
assert!(result.contains(" name: Alice"), "Expected 2-space indent for 'name'");
assert!(result.contains(" age: 30"), "Expected 2-space indent for 'age'");
}
#[test]
fn test_format_4_space_indent() {
let source = "user:\n name: Alice\n age: 30"; let ast = parse(source);
let opts = ToonFormattingOptions { indent_size: 4 };
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("user:"), "Missing 'user:' key");
assert!(result.contains(" name: Alice"), "Expected 4-space indent for 'name'");
assert!(result.contains(" age: 30"), "Expected 4-space indent for 'age'");
}
#[test]
fn test_format_uses_spaces_not_tabs() {
let source = "user:\n name: Alice\n age: 30";
let ast = parse(source);
let opts = ToonFormattingOptions { indent_size: 2 };
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("user:"), "Missing 'user:' key");
assert!(result.contains(" name: Alice"), "Expected space indent for 'name'");
assert!(!result.contains('\t'), "Output should not contain tabs");
}
#[test]
fn test_format_preserves_inline_array() {
let source = "values[3]:";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("values"), "Missing 'values' key");
assert!(result.contains('['), "Expected opening bracket");
assert!(result.contains(']'), "Expected closing bracket");
}
#[test]
fn test_format_preserves_expanded_array() {
let source = "items:\n - first\n - second\n - third";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("items:"), "Missing 'items:' key");
assert!(result.contains(" - first"), "Expected expanded format for 'first'");
assert!(result.contains(" - second"), "Expected expanded format for 'second'");
assert!(result.contains(" - third"), "Expected expanded format for 'third'");
}
#[test]
fn test_format_preserves_tabular_array() {
let source = "data[2]{x,y}:\n 1,2\n 3,4";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let result = format_document(&ast, opts).expect("Formatting failed");
assert!(result.contains("data"), "Missing 'data' key");
assert!(result.contains('|'), "Expected pipe delimiters in tabular format");
assert!(result.contains('1'), "Expected value '1'");
assert!(result.contains('2'), "Expected value '2'");
assert!(result.contains('3'), "Expected value '3'");
assert!(result.contains('4'), "Expected value '4'");
}
#[test]
fn test_format_produces_equivalent_ast() {
let source = "user:\n name: Bob\n age:30\n active:true"; let ast = parse(source);
let opts = ToonFormattingOptions::default();
let formatted = format_document(&ast, opts).expect("Formatting failed");
let (new_ast_opt, errors) = parse_with_errors(&formatted);
assert!(errors.is_empty(), "Formatted output has parse errors: {:?}", errors);
let new_ast = new_ast_opt.expect("Expected valid AST");
assert_eq!(ast.kind(), new_ast.kind(), "AST kinds don't match");
}
#[test]
fn test_format_empty_document() {
let source = "";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let result = format_document(&ast, opts);
assert!(result.is_some(), "Should handle empty document");
let formatted = result.unwrap();
assert!(
formatted.is_empty() || formatted == "\n",
"Empty document should format to empty or newline"
);
}
#[test]
fn test_format_assumes_valid_ast() {
let source = "valid: data";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let result = format_document(&ast, opts);
assert!(result.is_some(), "Should format valid AST");
}
#[test]
fn test_format_multiline_array_trailing_comma() {
let source = "list[4]: 1, 2, 3, 4";
let ast = parse(source);
let opts = ToonFormattingOptions::default();
let formatted = format_document(&ast, opts).unwrap();
assert_eq!(formatted, "list: [\n 1,\n 2,\n 3,\n 4,\n]\n");
}
}