1pub mod step;
8pub mod translate;
9mod write;
10
11pub use translate::{from_abc, from_abc_number};
12pub use write::{ExportOptions, to_abc};
13
14use crate::{Error, Pitch, Result};
15
16pub fn abc_note(pitch: &Pitch) -> Result<String> {
21 let name = pitch.name();
22 let mut chars = name.chars();
23 let step = chars
24 .next()
25 .ok_or_else(|| Error::Pitch("cannot write empty pitch name as ABC".to_string()))?;
26 if !matches!(step, 'A'..='G') {
27 return Err(Error::Pitch(format!(
28 "cannot write pitch step {step:?} as ABC"
29 )));
30 }
31
32 let accidental = chars
33 .map(|modifier| match modifier {
34 '#' => Ok('^'),
35 'b' => Ok('_'),
36 _ => Err(Error::Pitch(format!(
37 "cannot write accidental modifier {modifier:?} as ABC"
38 ))),
39 })
40 .collect::<Result<String>>()?;
41 let octave = pitch.octave().unwrap_or(4);
42
43 if octave >= 5 {
44 Ok(format!(
45 "{accidental}{}{}",
46 step.to_ascii_lowercase(),
47 "'".repeat((octave - 5) as usize)
48 ))
49 } else {
50 Ok(format!(
51 "{accidental}{step}{}",
52 ",".repeat((4 - octave).max(0) as usize)
53 ))
54 }
55}
56
57pub fn abc_rest() -> &'static str {
59 "z"
60}
61
62pub fn abc_chord(pitches: &[Pitch]) -> Result<String> {
64 let notes = pitches.iter().map(abc_note).collect::<Result<Vec<_>>>()?;
65 if notes.is_empty() {
66 Ok(abc_rest().to_string())
67 } else {
68 Ok(format!("[{}]", notes.join("")))
69 }
70}
71
72pub fn abc_duration(numerator: u32, denominator: u32) -> Result<String> {
74 if denominator == 0 {
75 return Err(Error::Music21Object(
76 "ABC duration denominator cannot be zero".to_string(),
77 ));
78 }
79
80 let divisor = num::integer::gcd(numerator, denominator);
81 let top = numerator / divisor;
82 let bottom = denominator / divisor;
83
84 if bottom == 1 {
85 if top == 1 {
86 Ok(String::new())
87 } else {
88 Ok(top.to_string())
89 }
90 } else if top == 1 {
91 Ok(format!("/{bottom}"))
92 } else {
93 Ok(format!("{top}/{bottom}"))
94 }
95}
96
97pub fn pitch_name_from_abc_note(token: &str) -> Result<Option<String>> {
101 let token = token.trim();
102 if token.is_empty() {
103 return Err(Error::Pitch("ABC note token cannot be empty".to_string()));
104 }
105
106 let token = token
107 .strip_prefix('{')
108 .and_then(|inner| inner.strip_suffix('}'))
109 .unwrap_or(token);
110
111 let mut chars = token.char_indices().peekable();
112 let mut accidental = String::new();
113
114 while let Some((_, ch)) = chars.peek().copied() {
115 match ch {
116 '^' => {
117 accidental.push('#');
118 chars.next();
119 }
120 '_' => {
121 accidental.push('b');
122 chars.next();
123 }
124 '=' => {
125 accidental.clear();
126 accidental.push('n');
127 chars.next();
128 }
129 _ => break,
130 }
131 }
132
133 let Some((_, step)) = chars.next() else {
134 return Err(Error::Pitch(format!(
135 "ABC note token {token:?} is missing a pitch step"
136 )));
137 };
138
139 if matches!(step, 'z' | 'Z' | 'x' | 'X') {
140 ensure_duration_suffix(token, chars.map(|(_, ch)| ch))?;
141 return Ok(None);
142 }
143
144 if !matches!(step, 'A'..='G' | 'a'..='g') {
145 return Err(Error::Pitch(format!(
146 "ABC note token {token:?} has invalid pitch step {step:?}"
147 )));
148 }
149
150 let mut octave = if step.is_ascii_lowercase() { 5 } else { 4 };
151 while let Some((_, ch)) = chars.peek().copied() {
152 match ch {
153 '\'' => {
154 octave += 1;
155 chars.next();
156 }
157 ',' => {
158 octave -= 1;
159 chars.next();
160 }
161 _ => break,
162 }
163 }
164
165 ensure_duration_suffix(token, chars.map(|(_, ch)| ch))?;
166 Ok(Some(format!(
167 "{}{accidental}{octave}",
168 step.to_ascii_uppercase()
169 )))
170}
171
172pub fn pitch_names_from_abc_chord(token: &str) -> Result<Vec<String>> {
176 let token = token.trim();
177 let Some(open) = token.find('[') else {
178 return match pitch_name_from_abc_note(token)? {
179 Some(pitch_name) => Ok(vec![pitch_name]),
180 None => Ok(Vec::new()),
181 };
182 };
183 let Some(close_offset) = token[open + 1..].find(']') else {
184 return Err(Error::Pitch(format!(
185 "ABC chord token {token:?} is missing a closing bracket"
186 )));
187 };
188 let close = open + 1 + close_offset;
189 ensure_duration_suffix(token, token[close + 1..].chars())?;
190
191 let mut names = Vec::new();
192 let inner = &token[open + 1..close];
193 let mut start = 0;
194 while start < inner.len() {
195 let end = next_abc_note_end(inner, start)?;
196 if let Some(name) = pitch_name_from_abc_note(&inner[start..end])? {
197 names.push(name);
198 }
199 start = end;
200 }
201
202 Ok(names)
203}
204
205fn next_abc_note_end(value: &str, start: usize) -> Result<usize> {
206 let mut end = start;
207 let mut saw_step = false;
208
209 for (offset, ch) in value[start..].char_indices() {
210 let idx = start + offset;
211 if !saw_step {
212 end = idx + ch.len_utf8();
213 match ch {
214 '^' | '_' | '=' => {}
215 'A'..='G' | 'a'..='g' | 'z' | 'Z' | 'x' | 'X' => saw_step = true,
216 _ => {
217 return Err(Error::Pitch(format!(
218 "ABC chord token has invalid note character {ch:?}"
219 )));
220 }
221 }
222 continue;
223 }
224
225 if matches!(ch, '\'' | ',' | '/' | '0'..='9') {
226 end = idx + ch.len_utf8();
227 } else {
228 break;
229 }
230 }
231
232 if saw_step {
233 Ok(end)
234 } else {
235 Err(Error::Pitch(
236 "ABC chord token is missing a pitch step".to_string(),
237 ))
238 }
239}
240
241fn ensure_duration_suffix(token: &str, suffix: impl IntoIterator<Item = char>) -> Result<()> {
242 let invalid = suffix
243 .into_iter()
244 .find(|ch| !ch.is_ascii_digit() && *ch != '/');
245
246 if let Some(ch) = invalid {
247 Err(Error::Pitch(format!(
248 "ABC token {token:?} has unsupported suffix character {ch:?}"
249 )))
250 } else {
251 Ok(())
252 }
253}
254
255#[cfg(test)]
256mod tests {
257
258 #[test]
259 fn abc_notes_are_written_and_read_back() {
260 use super::{abc_note, pitch_name_from_abc_note};
261 use crate::pitch::Pitch;
262
263 assert_eq!(abc_note(&Pitch::from_name("C4").unwrap()).unwrap(), "C");
264 assert_eq!(abc_note(&Pitch::from_name("C#5").unwrap()).unwrap(), "^c");
265 assert_eq!(abc_note(&Pitch::from_name("Bb3").unwrap()).unwrap(), "_B,");
266 assert_eq!(
267 pitch_name_from_abc_note("^c'").unwrap().as_deref(),
268 Some("C#6")
269 );
270 assert_eq!(
271 pitch_name_from_abc_note("_B,").unwrap().as_deref(),
272 Some("Bb3")
273 );
274 assert_eq!(
275 pitch_name_from_abc_note("=F").unwrap().as_deref(),
276 Some("Fn4")
277 );
278 assert_eq!(pitch_name_from_abc_note("z").unwrap(), None);
279 assert!(pitch_name_from_abc_note("?").is_err());
280 }
281
282 use super::{
283 abc_chord, abc_duration, abc_note, abc_rest, pitch_name_from_abc_note,
284 pitch_names_from_abc_chord,
285 };
286 use crate::{Pitch, Result};
287
288 fn pitches(names: &[&str]) -> Result<Vec<Pitch>> {
289 names.iter().map(|name| Pitch::from_name(*name)).collect()
290 }
291
292 #[test]
293 fn writes_pitch_tokens_with_accidentals_and_octaves() -> Result<()> {
294 assert_eq!(abc_note(&Pitch::from_name("C4")?)?, "C");
295 assert_eq!(abc_note(&Pitch::from_name("C#4")?)?, "^C");
296 assert_eq!(abc_note(&Pitch::from_name("Eb4")?)?, "_E");
297 assert_eq!(abc_note(&Pitch::from_name("C5")?)?, "c");
298 assert_eq!(abc_note(&Pitch::from_name("B3")?)?, "B,");
299 Ok(())
300 }
301
302 #[test]
303 fn writes_chord_and_rest_tokens_without_score_layout() -> Result<()> {
304 assert_eq!(abc_rest(), "z");
305 assert_eq!(abc_chord(&pitches(&["C4", "E4", "G4"])?)?, "[CEG]");
306 assert_eq!(abc_chord(&[])?, "z");
307 Ok(())
308 }
309
310 #[test]
311 fn writes_duration_suffixes() -> Result<()> {
312 assert_eq!(abc_duration(1, 1)?, "");
313 assert_eq!(abc_duration(4, 1)?, "4");
314 assert_eq!(abc_duration(1, 4)?, "/4");
315 assert_eq!(abc_duration(4, 10)?, "2/5");
316 assert!(abc_duration(1, 0).is_err());
317 Ok(())
318 }
319
320 #[test]
321 fn reads_pitch_names_from_note_tokens() -> Result<()> {
322 assert_eq!(pitch_name_from_abc_note("C")?.as_deref(), Some("C4"));
323 assert_eq!(pitch_name_from_abc_note("c")?.as_deref(), Some("C5"));
324 assert_eq!(pitch_name_from_abc_note("B,,")?.as_deref(), Some("B2"));
325 assert_eq!(pitch_name_from_abc_note("c''")?.as_deref(), Some("C7"));
326 assert_eq!(pitch_name_from_abc_note("^g2")?.as_deref(), Some("G#5"));
327 assert_eq!(pitch_name_from_abc_note("_g''")?.as_deref(), Some("Gb7"));
328 assert_eq!(pitch_name_from_abc_note("=c")?.as_deref(), Some("Cn5"));
329 assert_eq!(pitch_name_from_abc_note("z4")?, None);
330 Ok(())
331 }
332
333 #[test]
334 fn reads_pitch_names_from_chord_tokens() -> Result<()> {
335 assert_eq!(
336 pitch_names_from_abc_chord("[CEG]4")?,
337 vec!["C4", "E4", "G4"]
338 );
339 assert_eq!(
340 pitch_names_from_abc_chord("[^C_Eg']2")?,
341 vec!["C#4", "Eb4", "G6"]
342 );
343 Ok(())
344 }
345}