1use std::str::FromStr;
2
3use crate::{
4 chord::Chord,
5 chord::root::{pitch_class, step_num},
6 defaults::{FloatType, IntegerType},
7 duration::{Duration, DurationType},
8 error::{Error, Result},
9 interval::Interval,
10 pitch::Pitch,
11 stream::{Stream, StreamElement},
12};
13use std::collections::BTreeSet;
14
15mod figure;
16mod parse;
17mod realize;
18mod tables;
19
20pub use figure::{
21 ChordSymbolFigure, alter_to_chord_symbol_string, chord_symbol_figure_from_chord,
22 chord_symbol_from_chord, chord_symbol_kind_from_chord,
23};
24pub(crate) use figure::{chord_symbol_spellings, chord_symbol_spellings_with_root};
25pub use tables::{
26 CHORD_KIND_ALIASES, Music21ChordType, abbreviations_for_kind, current_abbreviation_for_kind,
27 known_chord_symbol_types, notation_for_kind, resolve_kind_alias,
28};
29
30use parse::*;
31pub use realize::{
32 ChordStepModification, ChordStepModificationType, ChordVoicing, inversion_is_valid_for_kind,
33 sound_chord_kind, sound_chord_notation, voice_chord_notation,
34};
35use tables::*;
36
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub enum ChordQuality {
41 Major,
43 Minor,
45 Dominant,
47 Diminished,
49 Augmented,
51 HalfDiminished,
53 Suspended2,
55 Suspended4,
57 Power,
59 Pedal,
61}
62
63#[derive(Clone, Debug, Eq, PartialEq)]
65#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
66pub struct ChordAlteration {
67 degree: u8,
68 semitones: IntegerType,
69}
70
71impl ChordAlteration {
72 pub fn new(degree: u8, semitones: IntegerType) -> Self {
74 Self { degree, semitones }
75 }
76
77 pub fn degree(&self) -> u8 {
79 self.degree
80 }
81
82 pub fn semitones(&self) -> IntegerType {
84 self.semitones
85 }
86}
87
88#[derive(Clone, Debug, PartialEq)]
90#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
91#[must_use]
92pub struct ChordSymbol {
93 figure: String,
94 root: Pitch,
95 bass: Option<Pitch>,
96 quality: ChordQuality,
97 extensions: Vec<u8>,
98 alterations: Vec<ChordAlteration>,
99 #[cfg_attr(feature = "serde", serde(default))]
100 omissions: Vec<u8>,
101 #[cfg_attr(feature = "serde", serde(default))]
102 additions: Vec<ChordAlteration>,
103 #[cfg_attr(feature = "serde", serde(default))]
105 kind: Option<String>,
106 #[cfg_attr(feature = "serde", serde(default))]
109 modifications: Vec<ChordStepModification>,
110 #[cfg_attr(feature = "serde", serde(default = "no_time"))]
113 duration: Duration,
114 #[cfg_attr(feature = "serde", serde(default))]
117 kind_text: crate::display::Drawn<Option<String>>,
118 #[cfg_attr(feature = "serde", serde(default))]
119 placement: crate::display::Drawn<Option<crate::notation::Placement>>,
120 #[cfg_attr(feature = "serde", serde(default))]
123 lyrics: Vec<crate::notation::Lyric>,
124 #[cfg_attr(feature = "serde", serde(default))]
127 transposed: Option<Vec<Pitch>>,
128 #[cfg_attr(feature = "serde", serde(default))]
131 numeral: Option<Box<NumeralFigure>>,
132}
133
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
137pub enum KeyDisplay {
138 Hidden,
140 Shown,
142}
143
144#[derive(Clone, Debug, PartialEq)]
147#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
148pub struct NumeralFigure {
149 pub figure: String,
151 pub degree: u8,
153 pub front_alteration: Option<FloatType>,
155 pub fifths: IntegerType,
157 pub mode: String,
160 pub key: KeyDisplay,
162}
163
164impl NumeralFigure {
165 pub fn of(numeral: &crate::roman::RomanNumeral, root: &Pitch, key: KeyDisplay) -> Self {
168 let figure = numeral.figure();
169 let figure = figure.split('/').next().unwrap_or(figure).to_string();
170 let degree = numeral.degree();
171 let written = numeral.written_accidental();
172 let home = numeral.key();
173 let above_tonic = (IntegerType::from(pitch_class(root))
174 - IntegerType::from(pitch_class(home.tonic_pitch())))
175 .rem_euclid(12);
176 let mode = match (home.mode(), degree) {
178 ("major", _) => "major",
179 (_, 6) if above_tonic == 8 => "natural minor",
180 (_, 6) => "melodic minor",
181 (_, 7) if above_tonic == 10 => "natural minor",
182 (_, 7) => "harmonic minor",
183 _ => "minor",
184 };
185 Self {
186 figure,
187 degree,
188 front_alteration: (written != 0).then_some(FloatType::from(written)),
189 fifths: home.sharps(),
190 mode: mode.to_string(),
191 key,
192 }
193 }
194}
195
196fn no_time() -> Duration {
198 Duration::from_type(DurationType::Zero)
199}
200
201fn music21_kind(shorthand: &str) -> Option<(&'static Music21ChordType, usize)> {
206 let mut cut = shorthand.len();
207 for marker in ["add", "alter", "omit", "subtract"] {
208 if let Some(at) = shorthand.find(marker) {
209 cut = cut.min(at);
210 }
211 }
212 let mut head = &shorthand[..cut];
213 if let Some(at) = head.find('#')
214 && head[at + 1..].starts_with(|c: char| c.is_ascii_digit())
215 {
216 head = &head[..at];
217 }
218 if let Some(at) = head.find('b')
219 && at < head.len() - 1
220 && head[at + 1..].starts_with(|c: char| c.is_ascii_digit())
221 && !head.contains("ob9")
222 && !head.contains("øb9")
223 {
224 head = &head[..at];
225 }
226 MUSIC21_CHORD_TYPES
227 .iter()
228 .find(|chord_type| chord_type.abbreviations.contains(&head))
229 .map(|chord_type| (chord_type, head.len()))
230}
231
232fn python_int(text: &str) -> Option<i64> {
239 let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
240 if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
241 return None;
242 }
243 text.parse().ok()
244}
245
246fn music21_modifications(remaining: &str) -> Option<Vec<ChordStepModification>> {
247 const MARKERS: [(&str, ChordStepModificationType); 4] = [
248 ("add", ChordStepModificationType::Add),
249 ("alter", ChordStepModificationType::Alter),
250 ("omit", ChordStepModificationType::Subtract),
251 ("subtract", ChordStepModificationType::Subtract),
252 ];
253 let mut out = Vec::new();
254 let first_marker = MARKERS
255 .iter()
256 .filter_map(|(marker, _)| remaining.find(marker))
257 .min();
258 if let Some(start) = first_marker {
259 let mut text = &remaining[start..];
260 while let Some((at, marker, kind)) = MARKERS
261 .iter()
262 .filter_map(|(marker, kind)| text.find(marker).map(|at| (at, *marker, *kind)))
263 .min_by_key(|(at, _, _)| *at)
264 {
265 let mut rest = &text[at + marker.len()..];
266 let mut alter = 0;
267 while let Some(sign) = rest.chars().next().filter(|c| matches!(c, 'b' | '-' | '#')) {
268 alter += if sign == '#' { 1 } else { -1 };
269 rest = &rest[1..];
270 }
271 let digits = rest.chars().take_while(char::is_ascii_digit).count().min(2);
272 let degree_text = &rest[..digits];
273 if let Ok(degree) = degree_text.parse::<u8>() {
274 out.push(ChordStepModification::new(kind, degree, alter).ok()?);
275 }
276 text = &rest[digits..];
277 }
278 }
279
280 let before: String = remaining[..first_marker.unwrap_or(remaining.len())].replace(',', "");
283 let mut items: Vec<String> = Vec::new();
284 if before.contains(['b', '#']) {
285 let chars: Vec<char> = before.chars().collect();
286 let mut current = String::new();
287 let mut index = 0;
288 while index < chars.len() {
289 if matches!(chars[index], 'b' | '#') {
290 if !current.is_empty() {
291 items.push(std::mem::take(&mut current));
292 }
293 let mut group = String::new();
294 while index < chars.len() && matches!(chars[index], 'b' | '#') {
295 group.push(chars[index]);
296 index += 1;
297 }
298 while index < chars.len() && !matches!(chars[index], 'b' | '#') {
299 group.push(chars[index]);
300 index += 1;
301 }
302 items.push(group);
303 } else {
304 current.push(chars[index]);
305 index += 1;
306 }
307 }
308 if !current.is_empty() {
309 items.push(current);
310 }
311 } else if !before.is_empty() {
312 items.push(before);
313 }
314
315 let mut tokens: Vec<String> = Vec::new();
319 for item in items {
320 let unsigned: String = item.chars().filter(|c| !matches!(c, 'b' | '#')).collect();
321 let number = python_int(&unsigned)?;
322 if number > 20 {
323 let chars: Vec<char> = item.chars().collect();
326 let mut prefix = String::new();
327 let mut skip = false;
328 for (index, &ch) in chars.iter().enumerate() {
329 if skip {
330 skip = false;
331 continue;
332 }
333 if ch == '1' {
334 let mut token = String::from(ch);
335 if let Some(next) = chars.get(index + 1) {
336 token.push(*next);
337 }
338 tokens.push(token);
339 skip = true;
340 } else if matches!(ch, 'b' | '#') {
341 prefix.push(ch);
342 } else {
343 prefix.push(ch);
344 tokens.push(std::mem::take(&mut prefix));
345 }
346 }
347 } else {
348 tokens.push(item);
349 }
350 }
351 for token in tokens {
352 let alter = if token.contains('b') {
353 -(token.matches('b').count() as IntegerType)
354 } else {
355 token.matches('#').count() as IntegerType
356 };
357 let nonzero = |c: &char| matches!(c, '1'..='9');
360 let digits: String = token
361 .chars()
362 .skip_while(|c| !nonzero(c))
363 .take_while(nonzero)
364 .collect();
365 if let Ok(degree) = digits.parse::<u8>() {
366 out.push(
367 ChordStepModification::new(ChordStepModificationType::Add, degree, alter).ok()?,
368 );
369 }
370 }
371 Some(out)
372}
373
374impl ChordSymbol {
375 pub fn parse(figure: impl Into<String>) -> Result<Self> {
380 Self::parse_with(figure.into(), false)
381 }
382
383 pub fn parse_music21(figure: impl Into<String>) -> Result<Self> {
397 let figure = figure.into();
398 let compact: String = figure.chars().filter(|c| !c.is_whitespace()).collect();
399 let refused_root = || {
400 Error::Chord(format!(
401 "Chord {compact} does not begin with a valid root note."
402 ))
403 };
404 let (root_text, rest) = match compact.find(',') {
405 Some(at) => {
406 let root = compact[..at].to_string();
407 let rest = compact.replace(',', "").replace(root.as_str(), "");
408 (root, rest)
409 }
410 None => {
411 let mut letters = compact.char_indices();
412 match letters.next() {
413 Some((_, first)) if "ABCDEFGabcdefg".contains(first) => {}
414 _ => return Err(refused_root()),
415 }
416 let end = letters
417 .find(|(_, c)| !matches!(c, '#' | '-'))
418 .map_or(compact.len(), |(at, _)| at);
419 let root = compact[..end].to_string();
420 let rest = compact.replacen(root.as_str(), "", 1);
421 (root, rest)
422 }
423 };
424 let root = Pitch::from_name(&root_text)?;
427 let mut bass = None;
430 let mut remaining = rest.clone();
431 if let Some(slash) = compact.find('/') {
432 let after = &compact[slash + 1..];
433 let mut letters = after.char_indices();
434 if let Some((_, first)) = letters.next()
435 && "ABCDEFGabcdefg".contains(first)
436 {
437 let end = letters
438 .find(|(_, c)| !matches!(c, '#' | '-'))
439 .map_or(after.len(), |(at, _)| at);
440 let written = &after[..end];
441 bass = Some(Pitch::from_name(written)?);
442 remaining = rest.replace(&format!("/{written}"), "");
443 }
444 }
445 let (kind, taken) = match music21_kind(&remaining) {
446 Some((chord_type, taken)) => (chord_type.kind.to_string(), taken),
447 None => (String::new(), 0),
448 };
449 let refused = || {
450 let mut said = remaining[taken..].replace(',', "");
451 for marker in ["add", "alter", "omit", "subtract"] {
452 if let Some(at) = said.find(marker) {
453 said.truncate(at);
454 }
455 }
456 Error::Chord(format!(
457 "Invalid chord abbreviation '{said}'; see music21.harmony.CHORD_TYPES for valid abbreviations or specify all alterations."
458 ))
459 };
460 let modifications = music21_modifications(&remaining[taken..]).ok_or_else(refused)?;
461 let own = Self::parse_with(format!("C{remaining}"), false).ok();
465 Ok(Self {
466 figure: figure.trim().to_string(),
467 root,
468 bass,
469 quality: own.as_ref().map_or(ChordQuality::Major, |own| own.quality),
470 extensions: own
471 .as_ref()
472 .map(|own| own.extensions.clone())
473 .unwrap_or_default(),
474 alterations: own.map(|own| own.alterations).unwrap_or_default(),
475 omissions: Vec::new(),
476 additions: Vec::new(),
477 kind: Some(kind),
478 modifications,
479 duration: no_time(),
480 kind_text: crate::display::Drawn(None),
481 placement: crate::display::Drawn(None),
482 lyrics: Vec::new(),
483 transposed: None,
484 numeral: None,
485 })
486 }
487
488 fn parse_with(figure: String, music21: bool) -> Result<Self> {
489 let trimmed = figure.trim();
490 if trimmed.is_empty() {
491 return Err(Error::Chord("chord symbol cannot be empty".to_string()));
492 }
493 let compact: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
496
497 let (body, bass_segment) = match compact.split_once('/') {
498 Some((body, bass)) => (body, Some(bass)),
499 None => (compact.as_str(), None),
500 };
501 let body_parts = split_music21_pitch_modifiers(body);
502 let bass_parts = bass_segment.map(split_music21_pitch_modifiers);
503 let bass = bass_parts
504 .as_ref()
505 .map(|parts| parse_pitch_only(&parts.base, music21))
506 .transpose()?;
507
508 let (root_name, suffix) = parse_pitch_prefix(&body_parts.base, music21)?;
509 let root = Pitch::from_name(root_name)?;
510 let suffix_without_additions = strip_addition_groups(suffix);
511 let mut additions = parse_additions(suffix);
512 let mut omissions = parse_omissions(suffix);
513 for pitch_name in body_parts
514 .additions
515 .iter()
516 .chain(bass_parts.iter().flat_map(|parts| parts.additions.iter()))
517 {
518 if let Some(addition) = pitch_name_addition(&root, pitch_name) {
519 additions.push(addition);
520 }
521 }
522 for pitch_name in body_parts
523 .omissions
524 .iter()
525 .chain(bass_parts.iter().flat_map(|parts| parts.omissions.iter()))
526 {
527 if let Some(omission) = pitch_name_degree(&root, pitch_name)
528 && !omissions.contains(&omission)
529 {
530 omissions.push(omission);
531 }
532 }
533
534 let mut alterations = parse_alterations(&suffix_without_additions);
535 add_implicit_music21_alterations(&suffix_without_additions, &mut alterations);
536 let extensions = parse_extensions(&suffix_without_additions, &alterations);
537 let quality = parse_quality(&suffix_without_additions, &alterations);
538 let full_suffix = &body[body_parts.base.len() - suffix.len()..];
545 let (kind, modifications) = match music21_kind(full_suffix) {
546 Some((chord_type, taken)) => match music21_modifications(&full_suffix[taken..]) {
547 Some(modifications) => (Some(chord_type.kind.to_string()), modifications),
548 None => (None, Vec::new()),
549 },
550 None => (None, Vec::new()),
551 };
552
553 Ok(Self {
554 figure: trimmed.to_string(),
555 root,
556 bass,
557 quality,
558 extensions,
559 alterations,
560 omissions,
561 additions,
562 kind,
563 modifications,
564 duration: no_time(),
565 kind_text: crate::display::Drawn(None),
566 placement: crate::display::Drawn(None),
567 lyrics: Vec::new(),
568 transposed: None,
569 numeral: None,
570 })
571 }
572
573 pub fn no_chord(text: Option<String>) -> Self {
577 Self {
578 figure: "N.C.".to_string(),
579 root: Pitch::from_name("C").expect("C is a pitch name"),
580 bass: None,
581 quality: ChordQuality::Major,
582 extensions: Vec::new(),
583 alterations: Vec::new(),
584 omissions: Vec::new(),
585 additions: Vec::new(),
586 kind: Some("none".to_string()),
587 modifications: Vec::new(),
588 duration: no_time(),
589 kind_text: crate::display::Drawn(Some(text.unwrap_or_else(|| "N.C.".to_string()))),
590 placement: crate::display::Drawn(None),
591 lyrics: Vec::new(),
592 transposed: None,
593 numeral: None,
594 }
595 }
596
597 pub fn lyrics(&self) -> &[crate::notation::Lyric] {
599 &self.lyrics
600 }
601
602 pub fn lyrics_mut(&mut self) -> &mut Vec<crate::notation::Lyric> {
604 &mut self.lyrics
605 }
606
607 pub fn add_lyric(&mut self, text: &str, number: Option<IntegerType>, apply_raw: bool) {
610 crate::notation::verses::add(&mut self.lyrics, text, number, apply_raw);
611 }
612
613 pub fn is_no_chord(&self) -> bool {
615 self.kind.as_deref() == Some("none")
616 }
617
618 pub fn kind_text(&self) -> Option<&str> {
621 self.kind_text.0.as_deref()
622 }
623
624 pub fn set_kind_text(&mut self, text: Option<String>) {
626 self.kind_text.0 = text.filter(|text| !text.is_empty());
627 }
628
629 pub fn placement(&self) -> Option<crate::notation::Placement> {
631 self.placement.0
632 }
633
634 pub fn set_placement(&mut self, placement: Option<crate::notation::Placement>) {
636 self.placement.0 = placement;
637 }
638
639 pub fn duration(&self) -> &Duration {
643 &self.duration
644 }
645
646 pub fn set_duration(&mut self, duration: Duration) {
648 self.duration = duration;
649 }
650
651 pub fn with_duration(mut self, duration: Duration) -> Self {
653 self.duration = duration;
654 self
655 }
656
657 pub fn numeral(&self) -> Option<&NumeralFigure> {
659 self.numeral.as_deref()
660 }
661
662 pub fn from_numeral(
683 chord: &Chord,
684 numeral: &crate::roman::RomanNumeral,
685 key: KeyDisplay,
686 ) -> Result<Option<Self>> {
687 let Some(mut symbol) = chord_symbol_from_chord(chord)? else {
688 return Ok(None);
689 };
690 let Some(root) = chord.root() else {
691 return Ok(None);
692 };
693 symbol.numeral = Some(Box::new(NumeralFigure::of(numeral, root, key)));
694 if let Some(duration) = chord.duration() {
695 symbol.duration = duration.clone();
696 }
697 Ok(Some(symbol))
698 }
699
700 pub fn kind(&self) -> Option<&str> {
704 self.kind.as_deref()
705 }
706
707 pub fn figure(&self) -> &str {
709 &self.figure
710 }
711
712 pub fn root(&self) -> &Pitch {
714 &self.root
715 }
716
717 pub fn bass(&self) -> Option<&Pitch> {
719 self.bass.as_ref()
720 }
721
722 pub fn quality(&self) -> ChordQuality {
724 self.quality
725 }
726
727 pub fn extensions(&self) -> &[u8] {
729 &self.extensions
730 }
731
732 pub fn alterations(&self) -> &[ChordAlteration] {
734 &self.alterations
735 }
736
737 pub fn omissions(&self) -> &[u8] {
739 &self.omissions
740 }
741
742 pub fn additions(&self) -> &[ChordAlteration] {
744 &self.additions
745 }
746
747 pub fn find_figure(&self) -> String {
752 let mut figure = self.root.name();
753 figure.push_str(&self.quality_and_extension());
754 for alteration in &self.alterations {
755 if alteration.degree == 5 && self.fifth_is_implied() {
756 continue;
757 }
758 figure.push_str(&alteration_text(alteration));
759 }
760 for addition in &self.additions {
761 figure.push_str(&format!("add({})", alteration_text(addition)));
762 }
763 for omission in &self.omissions {
764 figure.push_str(&format!("no{omission}"));
765 }
766 if let Some(bass) = &self.bass
767 && bass.name() != self.root.name()
768 {
769 figure.push('/');
770 figure.push_str(&bass.name());
771 }
772 figure
773 }
774
775 pub fn transpose(&self, interval: &Interval) -> Result<ChordSymbol> {
779 let mut transposed = self.clone();
780 if !self.is_no_chord() {
783 let moved = self
784 .pitches()?
785 .iter()
786 .map(|pitch| interval.transpose_pitch(pitch))
787 .collect::<Result<Vec<_>>>()?;
788 transposed.transposed = Some(moved);
789 }
790 transposed.root = self.root.transpose(interval)?;
791 transposed.bass = self
792 .bass
793 .as_ref()
794 .map(|bass| bass.transpose(interval))
795 .transpose()?;
796 transposed.figure = transposed.find_figure();
797 Ok(transposed)
798 }
799
800 pub fn inversion_is_valid(&self, inversion: u8) -> bool {
808 if let Some(kind) = &self.kind {
809 return realize::inversion_is_valid_for_kind(kind, inversion);
810 }
811 let highest = self
812 .extensions
813 .iter()
814 .copied()
815 .filter(|degree| matches!(degree, 7 | 9 | 11 | 13))
816 .max()
817 .unwrap_or(5);
818 match inversion {
819 1 | 2 => true,
820 3 => highest >= 7,
821 4 => highest >= 9,
822 5 => highest >= 11,
823 _ => false,
824 }
825 }
826
827 pub fn chord_step_modifications(&self) -> &[ChordStepModification] {
830 &self.modifications
831 }
832
833 pub fn add_chord_step_modification(&mut self, modification: ChordStepModification) {
837 if !self.modifications.contains(&modification) {
838 self.modifications.push(modification);
839 }
840 self.transposed = None;
841 }
842
843 pub fn set_chord_step_modifications(&mut self, modifications: Vec<ChordStepModification>) {
845 self.modifications = modifications;
846 self.transposed = None;
847 }
848
849 pub fn from_kind(root: Pitch, kind: &str, bass: Option<Pitch>) -> Result<Self> {
853 let abbreviation = current_abbreviation_for_kind(kind)
854 .ok_or_else(|| Error::Chord(format!("no such chord kind: {kind}")))?;
855 let mut figure = format!("{}{abbreviation}", root.name());
856 if let Some(bass) = bass.as_ref().filter(|bass| bass.name() != root.name()) {
857 figure.push('/');
858 figure.push_str(&bass.name());
859 }
860 let mut symbol = Self::parse(&figure)?;
861 symbol.kind = Some(kind.to_string());
862 symbol.modifications.clear();
863 symbol.root = root;
864 if bass.is_some() {
865 symbol.bass = bass;
866 }
867 Ok(symbol)
868 }
869
870 pub fn with_kind(mut self, kind: &str) -> Self {
874 self.kind = Some(kind.to_string());
875 self.modifications.clear();
876 self.transposed = None;
877 self
878 }
879
880 pub fn set_root(&mut self, root: Pitch) {
882 self.root = root;
883 self.transposed = None;
884 }
885
886 pub fn set_bass(&mut self, bass: Option<Pitch>) {
888 self.bass = bass;
889 self.transposed = None;
890 }
891
892 fn fifth_is_implied(&self) -> bool {
893 matches!(
894 self.quality,
895 ChordQuality::Diminished | ChordQuality::Augmented | ChordQuality::HalfDiminished
896 )
897 }
898
899 fn quality_and_extension(&self) -> String {
902 let seventh_family = self
903 .extensions
904 .iter()
905 .copied()
906 .filter(|degree| matches!(degree, 7 | 9 | 11 | 13))
907 .filter(|degree| {
908 !self
909 .alterations
910 .iter()
911 .any(|alteration| alteration.degree == *degree)
912 })
913 .max()
914 .or_else(|| {
915 self.extensions
916 .iter()
917 .any(|degree| matches!(degree, 7 | 9 | 11 | 13))
918 .then_some(7)
919 });
920 let sixth = self.extensions.contains(&6);
921 let extension = |written: &str| -> String {
922 match seventh_family {
923 Some(degree) => format!("{written}{degree}"),
924 None if sixth => format!("{written}6"),
925 None => written.to_string(),
926 }
927 };
928 match self.quality {
929 ChordQuality::Major => match seventh_family {
930 Some(degree) => format!("maj{degree}"),
931 None if sixth => "6".to_string(),
932 None => String::new(),
933 },
934 ChordQuality::Minor => extension("m"),
935 ChordQuality::Dominant => seventh_family.unwrap_or(7).to_string(),
936 ChordQuality::Diminished => extension("dim"),
937 ChordQuality::Augmented => extension("aug"),
938 ChordQuality::HalfDiminished => format!("m{}b5", seventh_family.unwrap_or(7)),
939 ChordQuality::Suspended2 => match seventh_family {
940 Some(degree) => format!("{degree}sus2"),
941 None => "sus2".to_string(),
942 },
943 ChordQuality::Suspended4 => match seventh_family {
944 Some(degree) => format!("{degree}sus4"),
945 None => "sus4".to_string(),
946 },
947 ChordQuality::Power => "5".to_string(),
948 ChordQuality::Pedal => "pedal".to_string(),
949 }
950 }
951
952 pub fn to_chord(&self) -> Result<Chord> {
955 Chord::new(self.pitches()?.as_slice())
956 }
957
958 pub fn transposed_pitches(&self) -> Option<&[Pitch]> {
962 self.transposed.as_deref()
963 }
964
965 pub fn pitches(&self) -> Result<Vec<Pitch>> {
980 if self.is_no_chord() {
981 return Ok(Vec::new());
982 }
983 if let Some(moved) = &self.transposed {
984 return Ok(moved.clone());
985 }
986 if self.kind.as_deref() == Some("")
990 || (self.kind.is_some() && self.kind_notation().is_none())
991 {
992 return realize::sound_chord_kind(
993 &self.root,
994 self.kind.as_deref().unwrap_or(""),
995 self.bass.as_ref(),
996 &self.modifications,
997 );
998 }
999 match self.kind_notation() {
1000 Some(notation) => {
1001 let mut realized = realize::realize(
1002 &self.root,
1003 self.bass.as_ref(),
1004 self.kind.as_deref(),
1005 Some(notation),
1006 None,
1007 &self.modifications,
1008 )?;
1009 self.apply_own_reading(&mut realized.pitches, notation)?;
1010 Ok(realized.pitches)
1011 }
1012 None => {
1013 let mut intervals = self.spelled_intervals()?;
1014 intervals.sort_unstable_by_key(|(degree, _)| *degree);
1015 intervals.dedup();
1016 let names = intervals
1017 .into_iter()
1018 .map(|(_, name)| {
1019 Ok(Interval::from_name(&name)?
1020 .transpose_pitch(&self.root)?
1021 .name())
1022 })
1023 .collect::<Result<Vec<_>>>()?;
1024 Ok(
1025 realize::realize(&self.root, self.bass.as_ref(), None, None, Some(names), &[])?
1026 .pitches,
1027 )
1028 }
1029 }
1030 }
1031
1032 fn apply_own_reading(&self, pitches: &mut Vec<Pitch>, notation: &str) -> Result<()> {
1036 if !self.omissions.is_empty() {
1037 for (degree, name) in notation_intervals(notation)? {
1038 if !self.omissions.contains(°ree) {
1039 continue;
1040 }
1041 let omitted = Interval::from_name(&name)?
1042 .transpose_pitch(&self.root)?
1043 .name();
1044 pitches.retain(|pitch| pitch.name() != omitted);
1045 }
1046 }
1047 for addition in &self.additions {
1048 let (_, name) = added_interval(addition)?;
1049 let pitch = Interval::from_name(name)?.transpose_pitch(&self.root)?;
1050 if pitches
1051 .iter()
1052 .any(|existing| existing.name() == pitch.name())
1053 {
1054 continue;
1055 }
1056 let mut placed = pitch;
1058 let top = pitches.last().map_or(0.0, Pitch::ps);
1059 placed.set_octave(pitches.last().and_then(Pitch::octave));
1060 while placed.ps() <= top {
1061 let octave = placed.octave().unwrap_or(3);
1062 placed.set_octave(Some(octave + 1));
1063 }
1064 pitches.push(placed);
1065 }
1066 Ok(())
1067 }
1068
1069 fn kind_notation(&self) -> Option<&'static str> {
1073 notation_for_kind(self.kind.as_deref()?)
1074 }
1075
1076 fn spelled_intervals(&self) -> Result<Vec<(u8, String)>> {
1079 let mut intervals = self.base_intervals();
1080
1081 let highest = self
1082 .extensions
1083 .iter()
1084 .copied()
1085 .filter(|degree| !self.alterations.iter().any(|alt| alt.degree == *degree))
1086 .max()
1087 .unwrap_or(0);
1088 for extension in [6, 9, 11, 13] {
1089 let implied = match extension {
1090 9 => highest >= 11,
1091 11 => highest == 13,
1092 _ => false,
1093 };
1094 if (self.extensions.contains(&extension) || implied)
1095 && !self.alterations.iter().any(|alt| alt.degree == extension)
1096 && !self.omissions.contains(&extension)
1097 {
1098 intervals.push((extension, default_extension_interval(extension)));
1099 }
1100 }
1101
1102 for alteration in &self.alterations {
1103 if alteration.degree == 5 {
1104 continue;
1105 }
1106 let altered = altered_interval(alteration)?;
1107 intervals.retain(|(degree, _)| *degree != altered.0);
1111 intervals.push(altered);
1112 }
1113
1114 for addition in &self.additions {
1115 intervals.push(added_interval(addition)?);
1116 }
1117
1118 Ok(intervals
1119 .into_iter()
1120 .map(|(degree, name)| (degree, name.to_string()))
1121 .collect())
1122 }
1123
1124 fn base_intervals(&self) -> Vec<(u8, &'static str)> {
1125 let altered_fifth = self
1126 .alterations
1127 .iter()
1128 .find(|alteration| alteration.degree == 5)
1129 .and_then(|alteration| match alteration.semitones {
1130 -1 => Some("d5"),
1131 1 => Some("a5"),
1132 _ => None,
1133 });
1134
1135 let fifth = altered_fifth.unwrap_or("P5");
1136 let has_seventh = self
1137 .extensions
1138 .iter()
1139 .any(|degree| matches!(degree, 7 | 9 | 11 | 13));
1140
1141 let intervals = match self.quality {
1142 ChordQuality::Major => {
1143 if has_seventh {
1144 vec![(1, "P1"), (3, "M3"), (5, fifth), (7, "M7")]
1145 } else {
1146 vec![(1, "P1"), (3, "M3"), (5, fifth)]
1147 }
1148 }
1149 ChordQuality::Minor => {
1150 if has_seventh {
1151 vec![(1, "P1"), (3, "m3"), (5, fifth), (7, "m7")]
1152 } else {
1153 vec![(1, "P1"), (3, "m3"), (5, fifth)]
1154 }
1155 }
1156 ChordQuality::Dominant => vec![(1, "P1"), (3, "M3"), (5, fifth), (7, "m7")],
1157 ChordQuality::Diminished => {
1158 if has_seventh {
1159 vec![(1, "P1"), (3, "m3"), (5, "d5"), (7, "d7")]
1160 } else {
1161 vec![(1, "P1"), (3, "m3"), (5, "d5")]
1162 }
1163 }
1164 ChordQuality::Augmented => vec![(1, "P1"), (3, "M3"), (5, "a5")],
1165 ChordQuality::HalfDiminished => vec![(1, "P1"), (3, "m3"), (5, "d5"), (7, "m7")],
1166 ChordQuality::Suspended2 => vec![(1, "P1"), (2, "M2"), (5, fifth)],
1167 ChordQuality::Suspended4 => vec![(1, "P1"), (4, "P4"), (5, fifth)],
1168 ChordQuality::Power => vec![(1, "P1"), (5, fifth)],
1169 ChordQuality::Pedal => vec![(1, "P1")],
1170 };
1171
1172 intervals
1173 .into_iter()
1174 .filter(|(degree, _)| !self.omissions.contains(degree))
1175 .collect()
1176 }
1177}
1178
1179pub fn realize_chord_symbol_durations(stream: &mut Stream) {
1211 let lengths = chord_symbol_durations(stream);
1212 let mut position = 0;
1213 stream.for_each_mut(&mut |_, element| {
1214 if let StreamElement::ChordSymbol(symbol) = element
1215 && let Some((_, length)) = lengths.iter().find(|(at, _)| *at == position)
1216 && let Ok(duration) = Duration::new(*length)
1217 {
1218 symbol.set_duration(duration);
1219 }
1220 position += 1;
1221 });
1222}
1223
1224pub fn chord_symbol_durations(stream: &Stream) -> Vec<(usize, FloatType)> {
1242 let end = stream.end_offset();
1243 let mut symbols: Vec<(FloatType, usize)> = stream
1244 .leaves()
1245 .iter()
1246 .enumerate()
1247 .filter(|(_, (_, element))| matches!(element, StreamElement::ChordSymbol(_)))
1248 .map(|(position, (offset, _))| (*offset, position))
1249 .collect();
1250 symbols.sort_by(|left, right| left.0.total_cmp(&right.0));
1252 symbols
1253 .iter()
1254 .enumerate()
1255 .map(|(index, &(offset, position))| {
1256 let until = symbols.get(index + 1).map_or(end, |next| next.0);
1257 (position, (until - offset).max(0.0))
1258 })
1259 .collect()
1260}
1261
1262impl FromStr for ChordSymbol {
1263 type Err = Error;
1264
1265 fn from_str(value: &str) -> Result<Self> {
1266 Self::parse(value)
1267 }
1268}
1269
1270impl TryFrom<&str> for ChordSymbol {
1271 type Error = Error;
1272
1273 fn try_from(value: &str) -> Result<Self> {
1274 Self::parse(value)
1275 }
1276}
1277
1278impl TryFrom<String> for ChordSymbol {
1279 type Error = Error;
1280
1281 fn try_from(value: String) -> Result<Self> {
1282 Self::parse(value)
1283 }
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288
1289 #[test]
1293 fn a_transposed_symbol_moves_each_pitch() {
1294 let symbol = ChordSymbol::parse_music21("B").unwrap();
1295 let interval = crate::interval::Interval::from_semitones(-12).unwrap();
1296 let moved = symbol.transpose(&interval).unwrap();
1297 let names: Vec<String> = moved
1298 .pitches()
1299 .unwrap()
1300 .iter()
1301 .map(Pitch::name_with_octave)
1302 .collect();
1303 assert_eq!(names, ["B1", "Eb2", "F#2"]);
1304 }
1305
1306 #[test]
1311 fn the_voicing_keeps_music21s_root_and_bass() {
1312 let voiced = |figure: &str| {
1313 let symbol = ChordSymbol::parse_music21(figure).unwrap();
1314 let kind = symbol.kind().unwrap_or_default();
1315 voice_chord_notation(
1316 symbol.root(),
1317 kind,
1318 notation_for_kind(resolve_kind_alias(kind)),
1319 symbol.bass(),
1320 symbol.chord_step_modifications(),
1321 )
1322 .unwrap()
1323 };
1324 let a = voiced("A10/C");
1325 assert_eq!(a.root().name_with_octave(), "A3");
1326 assert_eq!(a.bass().name_with_octave(), "C2");
1327 let names: Vec<String> = a.pitches().iter().map(Pitch::name_with_octave).collect();
1328 assert_eq!(names, ["C2", "A2", "A3"]);
1329 assert_eq!(voiced("Ab10/F#").root().name_with_octave(), "A3");
1330
1331 let flat_one = voiced("Bb10/B-");
1334 assert_eq!(flat_one.bass().name_with_octave(), "Bb1");
1335 assert_eq!(voiced("Ab10/A-").bass().name_with_octave(), "Ab1");
1336 }
1337
1338 #[test]
1339 fn a_slash_bass_is_voiced_as_music21_voices_it() {
1340 let cases: [(&str, &[&str]); 20] = [
1341 ("B-5/E", &["E2", "E2", "Bb3", "F4"]),
1342 ("B-69/E", &["E2", "E2", "Bb3", "G4", "C5"]),
1343 ("C5/G", &["G3", "G3", "C4"]),
1344 ("C5/D", &["D2", "D2", "C3", "G3"]),
1345 ("C69/D", &["D2", "D2", "C3", "A3", "D4"]),
1346 ("C5/C#", &["C#2", "C#2", "C3", "G3"]),
1347 ("F5/E", &["E2", "E2", "F3", "C4"]),
1348 ("A-10/E", &["E3", "Ab3", "Ab3"]),
1349 ("A#10/E", &["E3", "A#3", "A#3"]),
1350 ("C10/G", &["C3", "G3", "C4"]),
1351 ("C35/B", &["B2", "B2", "C3", "E3", "G3"]),
1352 ("C/B-", &["Bb2", "C3", "E3", "G3"]),
1353 ("C7/D", &["D2", "C3", "E3", "G3", "Bb3"]),
1354 ("Cm/E-", &["Eb3", "G3", "C4"]),
1355 ("C9/E", &["E3", "G3", "Bb3", "C4", "D4"]),
1356 ("C13/B-", &["Bb2", "C3", "D3", "E3", "F3", "G3", "A3"]),
1357 ("Cadd9/D", &["D2", "C3", "E3", "G3", "D4"]),
1358 ("C6/D", &["D2", "C3", "E3", "G3", "A3"]),
1359 ("C69/E", &["E3", "A3", "C4", "D4"]),
1360 ("C5/E", &["E3", "G3", "C4"]),
1361 ];
1362 for (figure, voiced) in cases {
1363 let symbol = ChordSymbol::parse_music21(figure).unwrap();
1364 let names: Vec<String> = symbol
1365 .pitches()
1366 .unwrap()
1367 .iter()
1368 .map(Pitch::name_with_octave)
1369 .collect();
1370 assert_eq!(names, voiced, "{figure}");
1371 }
1372 }
1373
1374 #[test]
1378 fn degrees_are_read_as_music21_reads_them() {
1379 type Adds = &'static [(u8, IntegerType)];
1380 let cases: [(&str, &str, Adds); 8] = [
1381 ("Cb-7", "", &[(7, -1)]),
1382 ("Cb+7", "", &[(7, -1)]),
1383 ("C7b-9", "", &[(7, 0), (9, -1)]),
1384 ("C9b-13", "", &[(9, 0), (13, -1)]),
1385 ("C10", "", &[(1, 0)]),
1386 ("C#10", "", &[(1, 0)]),
1387 ("Cb10", "major", &[(1, -1)]),
1388 ("Abb7", "", &[(7, -2)]),
1389 ];
1390 for (figure, kind, adds) in cases {
1391 let symbol = ChordSymbol::parse_music21(figure).unwrap();
1392 assert_eq!(symbol.kind(), Some(kind), "{figure}");
1393 let read: Vec<(u8, IntegerType)> = symbol
1394 .chord_step_modifications()
1395 .iter()
1396 .map(|modification| {
1397 let semitones = modification.interval().semitones() as IntegerType;
1398 (modification.degree(), semitones)
1399 })
1400 .collect();
1401 assert_eq!(read, adds, "{figure}");
1402 }
1403 }
1404
1405 #[test]
1408 fn a_modification_takes_every_accidental_before_its_degree() {
1409 for (figure, semitones) in [("G7addb9", -1), ("G7add-9", -1), ("G7addbb9", -2)] {
1410 let symbol = ChordSymbol::parse_music21(figure).unwrap();
1411 let modification = &symbol.chord_step_modifications()[0];
1412 assert_eq!(modification.degree(), 9, "{figure}");
1413 assert_eq!(
1414 modification.interval().semitones() as IntegerType,
1415 semitones,
1416 "{figure}"
1417 );
1418 }
1419 }
1420
1421 #[test]
1424 fn additions_and_omissions_are_written_as_degrees_that_read_back() {
1425 use super::chord_symbol_figure_from_chord;
1426 for (notes, expected) in [
1427 ("G3 B3 D4 F4 A-4 C5 E-5", "G7addb9add11addb13"),
1428 ("E2 B2 G#3 D4 F##4", "E7add#9"),
1429 ("B-2 F3 A3 D4 E4", "Bbmaj7add#11"),
1430 ("A-2 E-3 G-3 C4 D4 B-4", "Ab9add#11"),
1431 ("A2 E3 A3 B3 C4 E4", "Amadd9"),
1432 ("D4 E4 F#4 A4", "Dadd9"),
1433 ("D3 A3 F#4 E5", "Dadd9"),
1434 ("G B D F A C# E", "C#øb9addb11addb13"),
1435 ("C E G B- D- F#", "C7addb9add#11"),
1436 ("C E G A D", "Am7add11/C"),
1437 ("C# F# B D-", "C#susaddb7addbb9omit5"),
1438 ("D-3 F#3 A-3", "Dbsusadd#3omit4"),
1439 ("F#2 C#3 E-3 A3", "F#m6addbb7omit6"),
1440 ] {
1441 let chord = Chord::new(notes).unwrap();
1442 let figure = chord_symbol_figure_from_chord(&chord).unwrap().unwrap();
1443 assert_eq!(figure, expected, "{notes}");
1444 let respell = |name: &str| {
1447 let mut chars = name.chars();
1448 let Some(first) = chars.next() else {
1449 return String::new();
1450 };
1451 let rest = chars.as_str();
1452 let flats = rest.chars().take_while(|c| *c == 'b').count();
1453 format!("{first}{}{}", "-".repeat(flats), &rest[flats..])
1454 };
1455 let spelled = match figure.split_once('/') {
1456 Some((root, bass)) => format!("{}/{}", respell(root), respell(bass)),
1457 None => respell(&figure),
1458 };
1459 let sounded: BTreeSet<String> = ChordSymbol::parse_music21(spelled)
1460 .unwrap()
1461 .pitches()
1462 .unwrap()
1463 .iter()
1464 .map(Pitch::name)
1465 .collect();
1466 let written: BTreeSet<String> = chord.pitches().iter().map(Pitch::name).collect();
1467 assert_eq!(sounded, written, "{notes}");
1468 }
1469 assert_eq!(super::alter_to_chord_symbol_string(-1), "b");
1470 assert_eq!(super::alter_to_chord_symbol_string(2), "##");
1471 assert_eq!(super::alter_to_chord_symbol_string(0), "");
1472 }
1473
1474 #[test]
1477 fn a_root_with_an_unspellable_accidental_is_an_accidental_error() {
1478 for figure in ["C#-7", "C##-", "F#-7/E"] {
1479 let refused = ChordSymbol::parse_music21(figure).unwrap_err();
1480 assert!(
1481 matches!(refused, Error::Accidental(_)),
1482 "{figure}: {refused:?}"
1483 );
1484 }
1485 assert!(ChordSymbol::parse_music21("H7").is_err());
1486 }
1487 #[test]
1490 fn every_music21_kind_realizes_its_own_notation() {
1491 use super::{ChordSymbol, MUSIC21_CHORD_TYPES};
1492 use crate::pitch::Accidental;
1493 use crate::{Key, Pitch};
1494 use std::collections::BTreeSet;
1495
1496 let major = Key::from_tonic("C").unwrap();
1497 for chord_type in MUSIC21_CHORD_TYPES {
1498 let expected: BTreeSet<String> = chord_type
1499 .notation
1500 .split(',')
1501 .map(|token| {
1502 let degree: usize = token.trim_matches(['#', '-']).parse().unwrap();
1503 let alter =
1504 token.matches('#').count() as f64 - token.matches('-').count() as f64;
1505 let mut pitch = major.pitch_from_degree((degree - 1) % 7 + 1).unwrap();
1506 if alter != 0.0 {
1507 pitch.set_accidental(Accidental::new(alter).unwrap());
1508 }
1509 pitch.name()
1510 })
1511 .collect();
1512 for abbreviation in chord_type.abbreviations {
1513 if music21_kind(abbreviation).is_none_or(|(read, _)| read.kind != chord_type.kind) {
1518 continue;
1519 }
1520 let symbol = ChordSymbol::parse(format!("C{abbreviation}")).unwrap();
1521 assert_eq!(symbol.kind(), Some(chord_type.kind), "C{abbreviation}");
1522 let names: BTreeSet<String> = symbol
1523 .to_chord()
1524 .unwrap()
1525 .pitch_names()
1526 .into_iter()
1527 .collect();
1528 assert_eq!(names, expected, "C{abbreviation} ({})", chord_type.kind);
1529 }
1530 }
1531 assert_eq!(
1534 ChordSymbol::parse("C7#11").unwrap().kind(),
1535 Some("dominant-seventh")
1536 );
1537 assert_eq!(
1538 ChordSymbol::parse("CN6/E")
1539 .unwrap()
1540 .to_chord()
1541 .unwrap()
1542 .pitch_names(),
1543 ["E", "Gb", "C", "Db"]
1544 );
1545 let _ = Pitch::from_name("C").unwrap();
1546 }
1547
1548 #[test]
1551 fn figures_are_written_as_music21_writes_them() {
1552 use super::{
1553 ChordSymbolFigure, chord_symbol_figure_from_chord, chord_symbol_kind_from_chord,
1554 };
1555 use crate::{Chord, Pitch};
1556
1557 let figure =
1558 |notes: &str| chord_symbol_figure_from_chord(&Chord::new(notes).unwrap()).unwrap();
1559 let kind = |notes: &str| chord_symbol_kind_from_chord(&Chord::new(notes).unwrap());
1560 assert_eq!(figure("F3 A3 C#4 E-4 G4 B-4").as_deref(), Some("F+11"));
1561 assert_eq!(kind("F3 A3 C#4 E-4 G4 B-4"), Some("augmented-11th"));
1562 assert_eq!(figure("C3 E3 B3 D4").as_deref(), Some("CM9"));
1563 assert_eq!(figure("C3 D-3 E3 G-3").as_deref(), Some("CN6"));
1564 assert_eq!(kind("C3 D-3 E3 G-3"), Some("Neapolitan"));
1565 assert_eq!(figure("C3 D3 G3").as_deref(), Some("Csus2"));
1566 assert_eq!(figure("C3 E3 G3 D-4").as_deref(), Some("Caddb9"));
1567 assert_eq!(figure("C3").as_deref(), Some("Cpedal"));
1568 assert_eq!(figure("").as_deref(), Some(""));
1569
1570 let inverted = Chord::new("C3 F3 G3").unwrap();
1572 let parts = ChordSymbolFigure::from_chord(&inverted).unwrap();
1573 assert_eq!(parts.root, "C");
1574 assert_eq!(
1575 (parts.kind, parts.abbreviation, parts.bass.as_deref()),
1576 ("suspended-fourth", "sus", None)
1577 );
1578 assert_eq!(parts.to_string(), "Csus");
1579 assert_eq!(parts.written_with("sus4"), "Csus4");
1580
1581 let with_root = |notes: &str, root: &str| {
1583 ChordSymbolFigure::from_chord_with_root(
1584 &Chord::new(notes).unwrap(),
1585 &Pitch::from_name(root).unwrap(),
1586 )
1587 .unwrap()
1588 };
1589 assert_eq!(with_root("C3 F#3 A-3", "C3").to_string(), "CIt+6");
1590 assert_eq!(with_root("C3 D3 F#3 A-3", "C3").to_string(), "CFr+6");
1591 assert_eq!(with_root("C3 E-3 F#3 A-3", "C3").to_string(), "CGr+6");
1592 assert_eq!(with_root("F2 B2 D#3 G#3", "F2").to_string(), "Ftristan");
1593 assert_eq!(with_root("F2 B2 D#3 G#3", "F2").kind, "Tristan");
1594
1595 let parts = ChordSymbolFigure::from_chord(&Chord::new("E3 G3 C4 B-4").unwrap()).unwrap();
1598 assert_eq!(parts.to_string(), "C7/E");
1599 assert_eq!(figure("D3 C4 E-4 G4").as_deref(), Some("Cm/D"));
1601 assert!(ChordSymbolFigure::from_chord(&Chord::new("C4 C~4").unwrap()).is_none());
1602 assert!(ChordSymbolFigure::from_chord(&Chord::new("").unwrap()).is_none());
1603 }
1604
1605 #[test]
1606 fn a_symbol_is_parsed_through_try_from_and_reports_its_alterations() {
1607 use super::{ChordSymbol, chord_symbol_kind_from_chord};
1608 use crate::chord::Chord;
1609
1610 let symbol = ChordSymbol::try_from("C7#11").unwrap();
1611 assert_eq!(symbol.alterations().len(), 1);
1612 assert_eq!(symbol.alterations()[0].degree(), 11);
1613 assert_eq!(symbol.alterations()[0].semitones(), 1);
1614 assert!(symbol.omissions().is_empty());
1615 let omitting = ChordSymbol::try_from("C[no3]".to_string()).unwrap();
1616 assert_eq!(omitting.omissions(), [3]);
1617 assert!(ChordSymbol::try_from("").is_err());
1618
1619 assert_eq!(
1620 chord_symbol_kind_from_chord(&Chord::new("C").unwrap()),
1621 Some("pedal")
1622 );
1623 assert_eq!(
1624 chord_symbol_kind_from_chord(&Chord::new("C G").unwrap()),
1625 Some("power")
1626 );
1627 assert_eq!(
1628 chord_symbol_kind_from_chord(&Chord::new("C E G").unwrap()),
1629 Some("major")
1630 );
1631 assert_eq!(chord_symbol_kind_from_chord(&Chord::new("").unwrap()), None);
1632 }
1633
1634 #[test]
1635 fn chord_symbol_figures_match_music21() {
1636 let cases: [(&str, Option<&str>); 26] = [
1637 ("C4 E4 G4", Some("C")),
1638 ("C4 E-4 G4", Some("Cm")),
1639 ("C4 E4 G#4", Some("C+")),
1640 ("C4 E-4 G-4", Some("Cdim")),
1641 ("C4 E4 G4 B-4", Some("C7")),
1642 ("C4 E4 G4 B4", Some("Cmaj7")),
1643 ("C4 E-4 G4 B-4", Some("Cm7")),
1644 ("C4 E-4 G-4 B--4", Some("Co7")),
1645 ("C4 E-4 G-4 B-4", Some("C\u{00f8}7")),
1646 ("E4 G4 C5", Some("C/E")),
1647 ("G3 C4 E4", Some("C/G")),
1648 ("E4 G4 B-4 C5", Some("C7/E")),
1649 ("C4 E4 G4 B-4 D5", Some("C9")),
1650 ("C4 E4 G4 B4 D5", Some("CM9")),
1651 ("C4 D4 G4", Some("Csus2")),
1652 ("C4 F4 G4", Some("Csus")),
1653 ("C4", Some("Cpedal")),
1654 ("C4 G4", Some("Cpower")),
1655 ("C4 E4 G4 B-4 D5 F5", Some("C11")),
1656 ("C4 E4 G4 B-4 D5 F5 A5", Some("C13")),
1657 ("C4 E4 G4 A4", Some("Am7/C")),
1658 ("C4 E-4 G4 A4", Some("A\u{00f8}7/C")),
1659 ("C4 E4 G4 D5", Some("Cadd9")),
1660 ("F4 A4 C5 D5", Some("Dm7/F")),
1661 ("B3 D4 F4", Some("Bdim")),
1662 ("C4 D-4 E4", None),
1663 ];
1664 for (notes, expected) in cases {
1665 let chord = Chord::new(notes).unwrap();
1666 assert_eq!(
1667 chord_symbol_figure_from_chord(&chord).unwrap().as_deref(),
1668 expected,
1669 "{notes}"
1670 );
1671 }
1672 assert_eq!(
1673 chord_symbol_figure_from_chord(&Chord::empty())
1674 .unwrap()
1675 .as_deref(),
1676 Some("")
1677 );
1678
1679 let symbol = chord_symbol_from_chord(&Chord::new("E4 G4 B-4 C5").unwrap())
1680 .unwrap()
1681 .unwrap();
1682 assert_eq!(symbol.figure(), "C7/E");
1683 assert_eq!(symbol.root().name(), "C");
1684 assert_eq!(symbol.bass().map(Pitch::name).as_deref(), Some("E"));
1685 assert!(
1686 chord_symbol_from_chord(&Chord::new("C4 D-4 E4").unwrap())
1687 .unwrap()
1688 .is_none()
1689 );
1690 assert!(chord_symbol_from_chord(&Chord::empty()).unwrap().is_none());
1691 }
1692
1693 #[test]
1694 fn kind_lookups_match_music21() {
1695 assert_eq!(
1696 abbreviations_for_kind("dominant-seventh"),
1697 Some(&["7", "dom7"][..])
1698 );
1699 assert_eq!(notation_for_kind("dominant-seventh"), Some("1,3,5,-7"));
1700 assert_eq!(current_abbreviation_for_kind("dominant-seventh"), Some("7"));
1701 assert_eq!(abbreviations_for_kind("major"), Some(&["", "M", "maj"][..]));
1702 assert_eq!(current_abbreviation_for_kind("major"), Some(""));
1703 assert_eq!(abbreviations_for_kind("nonsense"), None);
1704 for chord_type in known_chord_symbol_types() {
1705 assert_eq!(
1706 chord_type.abbreviations.first(),
1707 Some(&chord_type.abbreviation)
1708 );
1709 }
1710 }
1711
1712 #[test]
1713 fn find_figure_writes_one_canonical_spelling_that_parses_back() {
1714 let cases = [
1715 ("C", "C", "D"),
1716 ("Cm7", "Cm7", "Dm7"),
1717 ("F#dim", "F#dim", "G#dim"),
1718 ("Bb/D", "Bb/D", "C/E"),
1719 ("G7/B", "G7/B", "A7/C#"),
1720 ("Am/C", "Am/C", "Bm/D"),
1721 ("Cmaj7", "Cmaj7", "Dmaj7"),
1722 ("Dm7b5", "Dm7b5", "Em7b5"),
1723 ("C\u{00f8}7", "Cm7b5", "Dm7b5"),
1724 ("E7#9", "E7#9", "F#7#9"),
1725 ("Csus4", "Csus4", "Dsus4"),
1726 ("G7sus4", "G7sus4", "A7sus4"),
1727 ("Cadd(9)", "Cadd(9)", "Dadd(9)"),
1728 ("C6", "C6", "D6"),
1729 ("Cm6", "Cm6", "Dm6"),
1730 ("Cdim7", "Cdim7", "Ddim7"),
1731 ("Caug", "Caug", "Daug"),
1732 ("C+", "Caug", "Daug"),
1733 ("C9", "C9", "D9"),
1734 ("Cmaj7#11", "Cmaj7#11", "Dmaj7#11"),
1735 ("C5", "C5", "D5"),
1736 ("Cno3", "Cno3", "Dno3"),
1737 ];
1738 let whole_tone = Interval::from_name("M2").unwrap();
1739 for (typed, canonical, transposed) in cases {
1740 let symbol = ChordSymbol::parse(typed).unwrap();
1741 assert_eq!(symbol.find_figure(), canonical, "{typed}");
1742 let reparsed = ChordSymbol::parse(symbol.find_figure()).unwrap();
1743 assert_eq!(reparsed.quality(), symbol.quality(), "{typed}");
1744 assert_eq!(
1745 reparsed.to_chord().unwrap().pitch_names(),
1746 symbol.to_chord().unwrap().pitch_names(),
1747 "{typed}"
1748 );
1749 let up = symbol.transpose(&whole_tone).unwrap();
1750 assert_eq!(up.figure(), transposed, "{typed}");
1751 assert_eq!(up.find_figure(), transposed, "{typed}");
1752 }
1753 }
1754
1755 #[test]
1756 fn inversion_validity_follows_the_chord_size() {
1757 let valid = |figure: &str| -> Vec<u8> {
1758 let symbol = ChordSymbol::parse(figure).unwrap();
1759 (0..=6).filter(|n| symbol.inversion_is_valid(*n)).collect()
1760 };
1761 assert_eq!(valid("C"), [1, 2]);
1762 assert_eq!(valid("C6"), [1, 2]);
1763 assert_eq!(valid("Cm7"), [1, 2, 3]);
1764 assert_eq!(valid("C9"), [1, 2, 3, 4]);
1765 assert_eq!(valid("C13"), [1, 2, 3, 4, 5]);
1766 assert_eq!(valid("E7#9"), [1, 2, 3]);
1769 assert_eq!(valid("Cmaj11"), [1, 2, 3, 4, 5]);
1772 }
1773 use super::*;
1774
1775 #[test]
1776 fn parses_major_seventh_symbol() {
1777 let symbol: ChordSymbol = "Cmaj7".parse().unwrap();
1778 assert_eq!(symbol.root().name(), "C");
1779 assert_eq!(symbol.quality(), ChordQuality::Major);
1780 assert_eq!(symbol.extensions(), &[7]);
1781 assert_eq!(
1782 symbol.to_chord().unwrap().pitched_common_name(),
1783 "C-major seventh chord"
1784 );
1785 }
1786
1787 #[test]
1788 fn parses_half_diminished_symbol() {
1789 let symbol = ChordSymbol::parse("F#m7b5").unwrap();
1790 assert_eq!(symbol.root().name(), "F#");
1791 assert_eq!(symbol.quality(), ChordQuality::HalfDiminished);
1792 assert_eq!(
1793 symbol.to_chord().unwrap().pitched_common_name(),
1794 "F#-half-diminished seventh chord"
1795 );
1796 }
1797
1798 #[test]
1799 fn parses_dominant_altered_symbol() {
1800 let symbol = ChordSymbol::parse("Bb7#11").unwrap();
1801 assert_eq!(symbol.root().name(), "Bb");
1802 assert_eq!(symbol.quality(), ChordQuality::Dominant);
1803 assert_eq!(symbol.extensions(), &[7, 11]);
1804 assert_eq!(symbol.alterations()[0], ChordAlteration::new(11, 1));
1805 let names = symbol
1806 .to_chord()
1807 .unwrap()
1808 .pitches()
1809 .iter()
1810 .map(Pitch::name)
1811 .collect::<Vec<_>>();
1812 assert_eq!(names, vec!["Bb", "D", "F", "Ab", "E"]);
1813 }
1814
1815 #[test]
1816 fn parses_added_tones_without_changing_the_base_chord() {
1817 let symbol = ChordSymbol::parse("Cdim9 add(#5)").unwrap();
1818 assert_eq!(symbol.extensions(), &[9]);
1819 assert_eq!(symbol.additions(), &[ChordAlteration::new(5, 1)]);
1820 assert_eq!(
1821 symbol.to_chord().unwrap().pitch_classes(),
1822 vec![0, 2, 3, 6, 8, 9]
1823 );
1824 }
1825
1826 #[test]
1827 fn parses_altered_dominant_with_slash_bass() {
1828 let symbol = ChordSymbol::parse("D7b9#11/C").unwrap();
1829 assert_eq!(symbol.root().name(), "D");
1830 assert_eq!(symbol.bass().map(Pitch::name).as_deref(), Some("C"));
1831 assert_eq!(symbol.quality(), ChordQuality::Dominant);
1832 assert_eq!(symbol.extensions(), &[7, 9, 11]);
1833 assert_eq!(
1834 symbol.alterations(),
1835 &[ChordAlteration::new(9, -1), ChordAlteration::new(11, 1)]
1836 );
1837 assert_eq!(
1838 symbol.to_chord().unwrap().pitch_classes(),
1839 vec![0, 2, 3, 6, 8, 9]
1840 );
1841 }
1842
1843 #[test]
1844 fn parses_music21_pitch_name_additions() {
1845 let symbol = ChordSymbol::parse("Ddom7dim5/CaddA,E-").unwrap();
1846
1847 assert_eq!(symbol.root().name(), "D");
1848 assert_eq!(symbol.bass().map(Pitch::name).as_deref(), Some("C"));
1849 assert_eq!(symbol.quality(), ChordQuality::Dominant);
1850 assert_eq!(symbol.alterations(), &[ChordAlteration::new(5, -1)]);
1851 assert_eq!(
1852 symbol.additions(),
1853 &[ChordAlteration::new(5, 0), ChordAlteration::new(9, -1)]
1854 );
1855 assert_eq!(
1856 symbol.to_chord().unwrap().pitch_classes(),
1857 vec![0, 2, 3, 6, 8, 9]
1858 );
1859 }
1860
1861 #[test]
1862 fn generates_petrushka_chord_symbol_name() {
1863 let chord = Chord::new("C4 D4 Eb4 F#4 Ab4 A4").unwrap();
1864 let names = chord_symbol_spellings(&chord);
1865
1866 assert_eq!(
1867 names.first().map(String::as_str),
1868 Some("Ddom7dim5add5addb9/C")
1869 );
1870 }
1871
1872 #[test]
1873 fn generates_common_chord_symbols() {
1874 let major_seventh = Chord::new("C E G B").unwrap();
1875 let dominant_ninth = Chord::new("C E G B- D").unwrap();
1876
1877 assert_eq!(
1878 chord_symbol_spellings(&major_seventh)
1879 .first()
1880 .map(String::as_str),
1881 Some("Cmaj7")
1882 );
1883 assert_eq!(
1884 chord_symbol_spellings(&dominant_ninth)
1885 .first()
1886 .map(String::as_str),
1887 Some("C9")
1888 );
1889 }
1890
1891 #[test]
1892 fn split_third_triads_do_not_spell_lower_third_as_sharp_nine() {
1893 let split_third = Chord::new("D4 A4 F#4 F4").unwrap();
1894 let names = chord_symbol_spellings(&split_third);
1895
1896 assert_eq!(names.first().map(String::as_str), Some("Daddb3"));
1897 assert!(!names.iter().any(|name| name == "D add(#9)"));
1898 }
1899
1900 #[test]
1901 fn altered_dominants_write_additions_as_degrees() {
1902 let altered_dominant = Chord::new("C4 E4 G4 Bb4 Eb5").unwrap();
1903 let names = chord_symbol_spellings(&altered_dominant);
1904
1905 assert_eq!(names.first().map(String::as_str), Some("C7addb3"));
1906 }
1907
1908 #[test]
1909 fn unrecognized_music21_figures_return_no_symbol() {
1910 let chord = Chord::new("F4 C5 D5 E-5").unwrap();
1911 let names = chord_symbol_spellings(&chord);
1912
1913 assert!(names.is_empty());
1914 }
1915
1916 #[test]
1917 fn generates_music21_figures_with_explicit_root() {
1918 let major_triad = Chord::new("G3 C4 E4").unwrap();
1919 let dominant_seventh = Chord::new("G3 B-3 C4 E4").unwrap();
1920 let power_chord = Chord::new("C4 G4").unwrap();
1921 let unsupported_dyad = Chord::new("C4 A4").unwrap();
1922
1923 assert_eq!(
1924 chord_symbol_spellings_with_root(&major_triad, 0)
1925 .first()
1926 .map(String::as_str),
1927 Some("C/G")
1928 );
1929 assert_eq!(
1930 chord_symbol_spellings_with_root(&dominant_seventh, 0)
1931 .first()
1932 .map(String::as_str),
1933 Some("C7/G")
1934 );
1935 assert_eq!(
1936 chord_symbol_spellings_with_root(&power_chord, 0)
1937 .first()
1938 .map(String::as_str),
1939 Some("Cpower")
1940 );
1941 assert!(chord_symbol_spellings_with_root(&unsupported_dyad, 0).is_empty());
1942 }
1943
1944 #[test]
1945 fn dense_sets_follow_music21_fallback_matching() {
1946 let chord = Chord::new("C4 D-4 E-4 E4 F#4 G4 A-4 A4").unwrap();
1947
1948 assert_eq!(
1949 chord_symbol_spellings(&chord).first().map(String::as_str),
1950 Some("Csusaddb3add3add#4addb9addb13add13omit4")
1951 );
1952 }
1953
1954 #[test]
1957 fn chord_symbols_hold_until_the_next_one_across_bars() {
1958 use crate::{Note, Stream, StreamElement, StreamKind};
1959
1960 let bar = |figure: &str, at: FloatType| {
1961 let mut measure = Stream::with_kind(StreamKind::Measure);
1962 measure.insert(at, ChordSymbol::parse(figure).unwrap());
1963 for _ in 0..4 {
1966 measure.push(Note::from_name("C4").unwrap());
1967 }
1968 measure
1969 };
1970 let held = |stream: &Stream| -> Vec<FloatType> {
1971 stream
1972 .flatten()
1973 .events()
1974 .iter()
1975 .filter(|event| matches!(event.element(), StreamElement::ChordSymbol(_)))
1976 .map(|event| event.element().quarter_length())
1977 .collect()
1978 };
1979
1980 let mut part = Stream::with_kind(StreamKind::Part);
1981 part.insert(0.0, bar("C", 0.0));
1982 part.insert(4.0, bar("G7", 1.5));
1983 part.insert(8.0, bar("Am", 2.0));
1984 assert_eq!(held(&part), [0.0, 0.0, 0.0]);
1985 realize_chord_symbol_durations(&mut part);
1986 assert_eq!(held(&part), [5.5, 4.5, 4.0]);
1987
1988 let mut stream = Stream::new();
1990 stream.insert(1.0, ChordSymbol::parse("C").unwrap());
1991 for beat in 1..7 {
1992 stream.insert(FloatType::from(beat), Note::from_name("C4").unwrap());
1993 }
1994 realize_chord_symbol_durations(&mut stream);
1995 assert_eq!(held(&stream), [6.0]);
1996
1997 let mut bare = Stream::new();
1999 bare.push(Note::from_name("C4").unwrap());
2000 realize_chord_symbol_durations(&mut bare);
2001 assert_eq!(bare.len(), 1);
2002 }
2003}