Repository Public
1//! ORIX Sonata2//! File: crates/sonata-parser/src/format.rs3//! Description: The canonical Sonata formatter: 4 spaces, one statement per line, comments4//! preserved, at most one blank line kept. Idempotent: format(format(x)) == format(x).5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::ast::*;10use crate::parser::parse;11use sonata_ir::{Diagnostic, Span};12use sonata_lexer::{Comment, NoteLit, NumLit, PitchClassLit, UnitSuffix, LETTER_NAMES};1314/// Formats a source text. Fails with the diagnostics when the source has lexical or syntax15/// errors: a file that does not parse is never rewritten.16pub fn format(src: &str) -> Result<String, Vec<Diagnostic>> {17 let parsed = parse(src, 0);18 if parsed.has_errors() {19 return Err(parsed.diagnostics.into_iter().filter(|d| d.is_error()).collect());20 }21 let mut p = Printer { src, out: String::new(), indent: 0, comments: &parsed.comments, next_comment: 0, last_end: 0, fresh: true };22 p.file(&parsed.file);23 Ok(p.out)24}2526struct Printer<'a> {27 src: &'a str,28 out: String,29 indent: usize,30 comments: &'a [Comment],31 next_comment: usize,32 /// End offset of the last source element already printed.33 last_end: u32,34 /// True right after an opening brace or at the start of the file (no blank line allowed).35 fresh: bool,36}3738pub(crate) fn number_text(value: NumLit, unit: Option<UnitSuffix>) -> String {39 let mut s = match value {40 NumLit::Int(v) => v.to_string(),41 NumLit::Float(v) => {42 let t = format!("{v}");43 if t.contains('.') || !v.is_finite() {44 t45 } else {46 format!("{t}.0")47 }48 }49 };50 if let Some(u) = unit {51 let one = matches!(value, NumLit::Int(1));52 s.push_str(match (u, one) {53 (UnitSuffix::Bars, true) => "bar",54 (UnitSuffix::Beats, true) => "beat",55 _ => u.as_str(),56 });57 }58 s59}6061fn accidental_text(a: i8) -> &'static str {62 match a {63 2 => "##",64 1 => "#",65 -1 => "b",66 -2 => "bb",67 _ => "",68 }69}7071pub fn note_text(n: NoteLit) -> String {72 format!("{}{}{}", LETTER_NAMES[n.letter as usize % 7], accidental_text(n.accidental), n.octave)73}7475pub fn pitch_class_text(p: PitchClassLit) -> String {76 format!("{}{}", LETTER_NAMES[p.letter as usize % 7], accidental_text(p.accidental))77}7879pub fn string_text(s: &str) -> String {80 let mut o = String::with_capacity(s.len() + 2);81 o.push('"');82 for c in s.chars() {83 match c {84 '\n' => o.push_str("\\n"),85 '\t' => o.push_str("\\t"),86 '"' => o.push_str("\\\""),87 '\\' => o.push_str("\\\\"),88 c if c.is_control() => o.push_str(&format!("\\u{{{:X}}}", c as u32)),89 c => o.push(c),90 }91 }92 o.push('"');93 o94}9596/// Prints an expression in canonical form (also used by hovers and diagnostics).97pub fn expr_text(e: &Expr) -> String {98 match &e.kind {99 ExprKind::Number { value, unit } => number_text(*value, *unit),100 ExprKind::Str { value } => string_text(value),101 ExprKind::Bool { value } => value.to_string(),102 ExprKind::Note { note } => note_text(*note),103 ExprKind::PitchClass { pitch_class } => pitch_class_text(*pitch_class),104 ExprKind::Ident { name } => name.clone(),105 ExprKind::List { items } => format!("[{}]", items.iter().map(expr_text).collect::<Vec<_>>().join(", ")),106 ExprKind::Range { start, end, inclusive } => format!("{}{}{}", expr_text(start), if *inclusive { "..=" } else { ".." }, expr_text(end)),107 ExprKind::Unary { op: UnOp::Neg, operand } => format!("-{}", expr_text(operand)),108 ExprKind::Unary { op: UnOp::Not, operand } => format!("not {}", expr_text(operand)),109 ExprKind::Binary { op, left, right } => {110 let plain_int = |x: &Expr| matches!(x.kind, ExprKind::Number { value: NumLit::Int(_), unit: None });111 if *op == BinOp::Div && plain_int(left) && plain_int(right) {112 format!("{}/{}", expr_text(left), expr_text(right))113 } else {114 format!("{} {} {}", expr_text(left), op.symbol(), expr_text(right))115 }116 }117 ExprKind::Call { callee, args } => format!("{}({})", callee.name, args_text(args)),118 ExprKind::Index { base, index } => format!("{}[{}]", expr_text(base), expr_text(index)),119 ExprKind::Member { base, name } => format!("{}.{}", expr_text(base), name.name),120 ExprKind::IfElse { cond, then, otherwise } => format!("if {} then {} else {}", expr_text(cond), expr_text(then), expr_text(otherwise)),121 ExprKind::Paren { inner } => format!("({})", expr_text(inner)),122 ExprKind::Error => "<error>".into(),123 }124}125126fn args_text(args: &[Arg]) -> String {127 args.iter()128 .map(|a| match &a.name {129 Some(n) => format!("{}: {}", n.name, expr_text(&a.value)),130 None => expr_text(&a.value),131 })132 .collect::<Vec<_>>()133 .join(", ")134}135136fn type_text(t: &TypeExpr) -> String {137 if t.args.is_empty() {138 t.name.name.clone()139 } else {140 format!("{}<{}>", t.name.name, t.args.iter().map(type_text).collect::<Vec<_>>().join(", "))141 }142}143144fn params_text(ps: &[Param]) -> String {145 ps.iter()146 .map(|p| {147 let mut s = p.name.name.clone();148 if let Some(t) = &p.ty {149 s.push_str(": ");150 s.push_str(&type_text(t));151 }152 if let Some(d) = &p.default {153 s.push_str(" = ");154 s.push_str(&expr_text(d));155 }156 s157 })158 .collect::<Vec<_>>()159 .join(", ")160}161162fn let_text(l: &LetDecl) -> String {163 let mut s = format!("{} {}", if l.is_const { "const" } else { "let" }, l.name.name);164 if let Some(t) = &l.ty {165 s.push_str(": ");166 s.push_str(&type_text(t));167 }168 s.push_str(" = ");169 s.push_str(&expr_text(&l.value));170 s171}172173fn point_text(p: &AutoPoint) -> String {174 let mut s = format!("{}: {}", expr_text(&p.at), expr_text(&p.value));175 if let Some(c) = &p.curve {176 s.push(' ');177 s.push_str(&c.name);178 }179 s180}181182impl<'a> Printer<'a> {183 fn blank_between(&self, from: u32, to: u32) -> bool {184 let (from, to) = (from as usize, (to as usize).min(self.src.len()));185 from < to && self.src.as_bytes()[from..to].iter().filter(|b| **b == b'\n').count() >= 2186 }187188 fn push_line(&mut self, text: &str) {189 for _ in 0..self.indent {190 self.out.push_str(" ");191 }192 self.out.push_str(text);193 self.out.push('\n');194 }195196 /// Emits the comments that start before `upto`, then the blank line owed to the next element.197 fn lead(&mut self, upto: u32) {198 self.comments_before(upto);199 if !self.fresh && self.blank_between(self.last_end, upto) {200 self.out.push('\n');201 }202 }203204 fn comments_before(&mut self, upto: u32) {205 while self.next_comment < self.comments.len() && self.comments[self.next_comment].span.start < upto {206 let c = &self.comments[self.next_comment];207 self.next_comment += 1;208 let text = c.text.trim_end();209 if !c.own_line && !self.out.is_empty() && self.out.ends_with('\n') && !self.fresh_line_is_blank() {210 // Trailing comment: glue it to the line it followed.211 self.out.pop();212 self.out.push_str(" ");213 self.out.push_str(text);214 self.out.push('\n');215 } else {216 if !self.fresh && self.blank_between(self.last_end, c.span.start) {217 self.out.push('\n');218 }219 self.push_line(text);220 }221 self.last_end = c.span.end;222 self.fresh = false;223 }224 }225226 fn fresh_line_is_blank(&self) -> bool {227 self.out.ends_with("\n\n")228 }229230 fn done(&mut self, span: Span) {231 self.last_end = span.end;232 self.fresh = false;233 }234235 fn open(&mut self, header: &str, start: u32) {236 self.lead(start);237 self.push_line(&format!("{header} {{"));238 self.indent += 1;239 self.fresh = true;240 // Comments on the opening line belong to it; measure blank lines from the brace.241 self.last_end = start;242 }243244 fn close(&mut self, end: u32) {245 self.comments_before(end.saturating_sub(1));246 self.indent -= 1;247 self.push_line("}");248 self.last_end = end;249 self.fresh = false;250 }251252 fn file(&mut self, f: &File) {253 if let Some(v) = &f.version {254 self.lead(v.span.start);255 self.push_line(&format!("sonata {}.{}", v.major, v.minor));256 self.done(v.span);257 }258 for item in &f.items {259 self.item(item);260 }261 self.comments_before(u32::MAX);262 }263264 fn item(&mut self, item: &Item) {265 let span = item.span();266 match item {267 Item::Import(i) => {268 self.lead(span.start);269 self.push_line(&format!("import {}", i.dotted()));270 }271 Item::Let(l) => {272 self.lead(span.start);273 self.push_line(&let_text(l));274 }275 Item::Fn(f) => {276 let ret = f.ret.as_ref().map(|t| format!(" -> {}", type_text(t))).unwrap_or_default();277 self.block(&format!("fn {}({}){}", f.name.name, params_text(&f.params), ret), span.start, &f.body);278 }279 Item::Pattern(p) => {280 self.block(&format!("pattern {}({})", p.name.name, params_text(&p.params)), span.start, &p.body);281 }282 Item::Composition(c) => {283 self.block(&format!("composition {}", string_text(&c.title.value)), span.start, &c.body);284 }285 Item::Instrument(d) => {286 let base = d.base.as_ref().map(|b| format!(": {}", b.name)).unwrap_or_default();287 self.open(&format!("instrument {}{}", d.name.name, base), span.start);288 for m in &d.members {289 match &m.kind {290 InstrMemberKind::Model { name } => {291 self.lead(m.span.start);292 self.push_line(&format!("model {}", name.name));293 }294 InstrMemberKind::Preset { name } => {295 self.lead(m.span.start);296 self.push_line(&format!("preset {}", name.name));297 }298 InstrMemberKind::Param { name, value } => {299 self.lead(m.span.start);300 self.push_line(&format!("{} {}", name.name, expr_text(value)));301 }302 InstrMemberKind::Slot { slot, kind, args } => {303 self.lead(m.span.start);304 self.push_line(&format!("{} {}({})", slot.name, kind.name, args_text(args)));305 }306 InstrMemberKind::Graph(g) => {307 self.open("graph", m.span.start);308 // Nodes and `out` keep their source order.309 let mut lines: Vec<(u32, Span, String)> =310 g.nodes.iter().map(|n| (n.span.start, n.span, format!("node {} = {}", n.name.name, expr_text(&n.value)))).collect();311 if let Some(o) = &g.out {312 lines.push((o.span.start, o.span, format!("out {}", expr_text(o))));313 }314 lines.sort_by_key(|l| l.0);315 for (start, span, text) in lines {316 // `out` spans start at the expression; comments before the keyword still precede it.317 self.lead(start);318 self.push_line(&text);319 self.done(span);320 }321 self.close(g.span.end);322 }323 }324 self.done(m.span);325 }326 self.close(span.end);327 }328 }329 self.done(span);330 }331332 fn block(&mut self, header: &str, start: u32, b: &Block) {333 self.open(header, start);334 for s in &b.stmts {335 self.stmt(s);336 }337 self.close(b.span.end);338 }339340 fn stmt(&mut self, s: &Stmt) {341 let start = s.span.start;342 let simple: Option<String> = match &s.kind {343 StmtKind::Let(l) => Some(let_text(l)),344 StmtKind::Assign { target, value } => Some(format!("{} = {}", target.name, expr_text(value))),345 StmtKind::Tempo { value, ramp } => Some(match ramp {346 Some(r) => format!("tempo {} ramp {}", expr_text(value), expr_text(r)),347 None => format!("tempo {}", expr_text(value)),348 }),349 StmtKind::Key { tonic, mode, .. } => Some(format!("key {} {}", pitch_class_text(*tonic), mode.name)),350 StmtKind::Signature { numerator, denominator } => Some(format!("signature {numerator}/{denominator}")),351 StmtKind::Seed { value } => Some(format!("seed {}", expr_text(value))),352 StmtKind::Tuning { value } => Some(format!("tuning {}", expr_text(value))),353 StmtKind::Swing { ratio, unit, body: None } => Some(swing_head(ratio, unit)),354 StmtKind::Clip { asset, options } => {355 let mut t = format!("clip {}", string_text(&asset.value));356 for (k, v) in options {357 t.push_str(&format!(" {} {}", k.name, expr_text(v)));358 }359 Some(t)360 }361 StmtKind::Marker { name, at } => Some(match at {362 Some(a) => format!("marker {} at {}", expr_text(name), expr_text(a)),363 None => format!("marker {}", expr_text(name)),364 }),365 StmtKind::Play { is_chord, what, modifiers } => {366 let mut t = format!("{} {}", if *is_chord { "chord" } else { "play" }, expr_text(what));367 for m in modifiers {368 t.push(' ');369 t.push_str(&match &m.kind {370 ModifierKind::Duration { value } => format!("duration {}", expr_text(value)),371 ModifierKind::Velocity { value } => format!("velocity {}", expr_text(value)),372 ModifierKind::Articulation { name } => name.name.clone(),373 ModifierKind::Tie => "tie".into(),374 ModifierKind::Bend { points } => format!("bend {{ {} }}", points.iter().map(point_text).collect::<Vec<_>>().join(", ")),375 });376 }377 Some(t)378 }379 StmtKind::Rest { duration } => Some(format!("rest {}", expr_text(duration))),380 StmtKind::Transpose { interval, body: None } => Some(format!("transpose {}", expr_text(interval))),381 StmtKind::Return { value } => Some(match value {382 Some(v) => format!("return {}", expr_text(v)),383 None => "return".into(),384 }),385 StmtKind::Send { bus, gain, pre_fader } => {386 let mut t = format!("send {}", bus.name);387 if let Some(g) = gain {388 t.push(' ');389 t.push_str(&expr_text(g));390 }391 if *pre_fader {392 t.push_str(" pre");393 }394 Some(t)395 }396 StmtKind::Default { what, value } => Some(format!("default {} {}", what.name, expr_text(value))),397 StmtKind::Setting { name, value } => Some(match value {398 Some(v) => format!("{} {}", name.name, expr_text(v)),399 None => name.name.clone(),400 }),401 StmtKind::Expr { expr } => Some(expr_text(expr)),402 _ => None,403 };404 if let Some(text) = simple {405 self.lead(start);406 self.push_line(&text);407 self.done(s.span);408 return;409 }410 match &s.kind {411 StmtKind::Swing { ratio, unit, body: Some(b) } => self.block(&swing_head(ratio, unit), start, b),412 StmtKind::Track { name, ty, body } => self.block(&format!("instrument {}: {}", name.name, ty.name), start, body),413 StmtKind::AudioTrack { name, body } => self.block(&format!("audio {}", name.name), start, body),414 StmtKind::Bus { name, body } => self.block(&format!("bus {}", name.name), start, body),415 StmtKind::Master { body } => self.block("master", start, body),416 StmtKind::Sequence { body } => self.block("sequence", start, body),417 StmtKind::Voice { body } => self.block("voice", start, body),418 StmtKind::Parallel { body } => self.block("parallel", start, body),419 StmtKind::At { position, body } => self.block(&format!("at {}", expr_text(position)), start, body),420 StmtKind::Repeat { count, body } => self.block(&format!("repeat {}", expr_text(count)), start, body),421 StmtKind::For { var, iter, body } => self.block(&format!("for {} in {}", var.name, expr_text(iter)), start, body),422 StmtKind::Tuplet { n, m, body } => self.block(&format!("tuplet {} in {}", expr_text(n), expr_text(m)), start, body),423 StmtKind::Transpose { interval, body: Some(b) } => self.block(&format!("transpose {}", expr_text(interval)), start, b),424 StmtKind::If { .. } => self.if_chain(s, "if"),425 StmtKind::Effects { items } => {426 self.open("effects", start);427 for it in items {428 self.lead(it.span.start);429 let mut t = String::new();430 if it.bypass {431 t.push_str("bypass ");432 }433 t.push_str(&it.kind.name);434 if let Some(p) = &it.preset {435 t.push(' ');436 t.push_str(&p.name);437 }438 if !it.args.is_empty() {439 t.push_str(&format!("({})", args_text(&it.args)));440 }441 self.push_line(&t);442 self.done(it.span);443 }444 self.close(s.span.end);445 }446 StmtKind::Automate { target, points } => {447 let mut head = format!("automate {}", target.head.name);448 if let Some(i) = target.index {449 head.push_str(&format!("[{i}]"));450 }451 if let Some(p) = &target.param {452 head.push('.');453 head.push_str(&p.name);454 }455 self.open(&head, start);456 for p in points {457 self.lead(p.span.start);458 self.push_line(&point_text(p));459 self.done(p.span);460 }461 self.close(s.span.end);462 }463 _ => {}464 }465 self.done(s.span);466 }467468 /// Prints `if … { } else if … { } else { }` keeping `} else {` on one line.469 fn if_chain(&mut self, s: &Stmt, keyword: &str) {470 let StmtKind::If { cond, then, otherwise } = &s.kind else { return };471 if keyword == "if" {472 self.open(&format!("if {}", expr_text(cond)), s.span.start);473 }474 for st in &then.stmts {475 self.stmt(st);476 }477 self.comments_before(then.span.end.saturating_sub(1));478 self.indent -= 1;479 self.last_end = then.span.end;480 self.fresh = false;481 match otherwise {482 None => self.push_line("}"),483 Some(b) => {484 let nested = b.stmts.len() == 1 && matches!(b.stmts[0].kind, StmtKind::If { .. }) && b.stmts[0].span == b.span;485 if nested {486 if let StmtKind::If { cond, .. } = &b.stmts[0].kind {487 self.push_line(&format!("}} else if {} {{", expr_text(cond)));488 }489 self.indent += 1;490 self.fresh = true;491 self.if_chain(&b.stmts[0], "else if");492 } else {493 self.push_line("} else {");494 self.indent += 1;495 self.fresh = true;496 for st in &b.stmts {497 self.stmt(st);498 }499 self.close(b.span.end);500 }501 }502 }503 self.done(s.span);504 }505}506507fn swing_head(ratio: &Expr, unit: &Option<Expr>) -> String {508 match unit {509 Some(u) => format!("swing {} of {}", expr_text(ratio), expr_text(u)),510 None => format!("swing {}", expr_text(ratio)),511 }512}513