1use std::convert::Infallible;
2
3use thiserror::Error as ThisError;
4
5pub type Result<T, E = Error> = std::result::Result<T, E>;
7
8#[derive(Clone, Debug, Eq, PartialEq, ThisError)]
10#[non_exhaustive]
11pub enum Error {
12 #[error("Music21Object error: {0}")]
14 Music21Object(String),
15 #[error("Chord error: {0}")]
17 Chord(String),
18 #[error("Pitch error: {0}")]
20 Pitch(String),
21 #[error("Microtone error: {0}")]
23 Microtone(String),
24 #[error("Accidental error: {0}")]
26 Accidental(String),
27 #[error("ChordTables error: {0}")]
29 ChordTables(String),
30 #[error("Interval error: {0}")]
32 Interval(String),
33 #[error("StepName error: {0}")]
35 StepName(String),
36 #[error("PitchClass error: {0}")]
38 PitchClass(String),
39 #[error("Ordinal error: {0}")]
41 Ordinal(String),
42 #[error("Polyrhythm error: {0}")]
44 Polyrhythm(String),
45 #[error("TuningSystem error: {0}")]
47 TuningSystem(String),
48 #[error("Midi error: {0}")]
51 Midi(Box<FormatError>),
52 #[error("Analysis error: {0}")]
54 Analysis(String),
55 #[error("Meter error: {0}")]
57 Meter(String),
58 #[error("Sieve error: {0}")]
60 Sieve(String),
61 #[error("Metadata error: {0}")]
64 Metadata(String),
65 #[error("Duration error: {0}")]
67 Duration(String),
68 #[error("Key error: {0}")]
70 Key(String),
71 #[error("Scale error: {0}")]
73 Scale(String),
74 #[error("Tempo error: {0}")]
76 Tempo(String),
77 #[error("Instrument error: {0}")]
79 Instrument(String),
80 #[error("Figured bass error: {0}")]
82 FiguredBass(String),
83 #[error("ABC error: {0}")]
85 Abc(Box<FormatError>),
86 #[error("Humdrum error: {0}")]
88 Humdrum(Box<FormatError>),
89 #[error("XML error: {0}")]
91 Xml(Box<FormatError>),
92 #[error("MEI error: {0}")]
94 Mei(Box<FormatError>),
95 #[error("RomanText error: {0}")]
97 RomanText(Box<FormatError>),
98 #[error("Capella error: {0}")]
100 Capella(Box<FormatError>),
101 #[error("MuseData error: {0}")]
103 MuseData(Box<FormatError>),
104 #[error("NoteWorthy error: {0}")]
106 Noteworthy(Box<FormatError>),
107 #[error("MuseScore error: {0}")]
110 MuseScore(Box<FormatError>),
111 #[error("Expression error: {0}")]
113 Expression(String),
114 #[error("Clef error: {0}")]
116 Clef(String),
117 #[error("Serial error: {0}")]
119 Serial(String),
120 #[error("Notation error: {0}")]
122 Notation(String),
123 #[error("Volume error: {0}")]
125 Volume(String),
126 #[error("Stream error: {0}")]
129 Stream(String),
130
131 #[error("Feature error: {0}")]
134 Feature(String),
135 #[error("Graph error: {0}")]
138 Graph(String),
139 #[error("Text error: {0}")]
142 Text(String),
143 #[error("Search error: {0}")]
146 Search(String),
147 #[error("Tablature error: {0}")]
150 Tablature(String),
151 #[error("Tree error: {0}")]
154 Tree(String),
155 #[error("OMR error: {0}")]
159 Omr(String),
160 #[error("Variant error: {0}")]
164 Variant(String),
165 #[cfg(feature = "musicxml")]
168 #[error("MusicXML export error: {0}")]
169 MusicXml(Box<FormatError>),
170 #[error("Value error: {0}")]
177 Value(String),
178 #[error("{0}")]
182 Placed(Box<PlacedError>),
183 #[error("Environment error: {0}")]
186 Environment(String),
187}
188
189#[derive(Clone, Debug, Eq, PartialEq)]
202#[non_exhaustive]
203pub struct PlacedError {
204 pub error: Error,
206 pub position: Position,
208}
209
210impl std::fmt::Display for PlacedError {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 self.error.fmt(f)
213 }
214}
215
216#[derive(Clone, Debug, Eq, PartialEq)]
232#[non_exhaustive]
233pub struct FormatError {
234 pub kind: FormatErrorKind,
236 pub position: Option<Position>,
238 pub message: String,
240}
241
242impl FormatError {
243 pub fn new(kind: FormatErrorKind, message: impl Into<String>) -> Self {
245 Self {
246 kind,
247 position: None,
248 message: message.into(),
249 }
250 }
251
252 #[must_use]
254 pub fn with_position(mut self, position: Position) -> Self {
255 self.position = Some(position);
256 self
257 }
258}
259
260impl std::fmt::Display for FormatError {
261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262 f.write_str(&self.message)
263 }
264}
265
266#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
268#[non_exhaustive]
269pub enum FormatErrorKind {
270 Malformed,
274 Invalid,
277 Unsupported,
280 TooLarge,
285 NotFound,
288 External,
290}
291
292#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
296#[non_exhaustive]
297pub struct Position {
298 pub line: Option<usize>,
300 pub column: Option<usize>,
302 pub measure: Option<String>,
305 pub part: Option<String>,
307 pub track: Option<usize>,
309 pub tick: Option<u64>,
311}
312
313impl Position {
314 pub fn line(line: usize) -> Self {
316 Self {
317 line: Some(line),
318 ..Self::default()
319 }
320 }
321
322 pub fn measure(number: impl Into<String>) -> Self {
324 Self {
325 measure: Some(number.into()),
326 ..Self::default()
327 }
328 }
329
330 pub fn track(index: usize) -> Self {
332 Self {
333 track: Some(index),
334 ..Self::default()
335 }
336 }
337
338 pub(crate) fn in_text(text: &str, at: usize) -> Self {
341 let before = &text[..at];
342 let line = before.matches('\n').count() + 1;
343 let line_start = before.rfind('\n').map_or(0, |newline| newline + 1);
344 let column = before[line_start..].chars().count() + 1;
345 Self::line(line).with_column(column)
346 }
347
348 #[must_use]
350 pub fn with_column(mut self, column: usize) -> Self {
351 self.column = Some(column);
352 self
353 }
354
355 #[must_use]
357 pub fn in_part(mut self, part: impl Into<String>) -> Self {
358 self.part = Some(part.into());
359 self
360 }
361
362 #[must_use]
364 pub fn at_tick(mut self, tick: u64) -> Self {
365 self.tick = Some(tick);
366 self
367 }
368
369 fn fill_from(&mut self, outer: Position) {
372 self.line = self.line.or(outer.line);
373 self.column = self.column.or(outer.column);
374 self.measure = self.measure.take().or(outer.measure);
375 self.part = self.part.take().or(outer.part);
376 self.track = self.track.or(outer.track);
377 self.tick = self.tick.or(outer.tick);
378 }
379}
380
381impl std::fmt::Display for Position {
382 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384 let mut said = Vec::new();
385 if let Some(part) = &self.part {
386 said.push(format!("part {part}"));
387 }
388 if let Some(measure) = &self.measure {
389 said.push(format!("measure {measure}"));
390 }
391 if let Some(track) = self.track {
392 said.push(format!("track {track}"));
393 }
394 if let Some(tick) = self.tick {
395 said.push(format!("tick {tick}"));
396 }
397 if let Some(line) = self.line {
398 said.push(format!("line {line}"));
399 }
400 if let Some(column) = self.column {
401 said.push(format!("column {column}"));
402 }
403 f.write_str(&said.join(", "))
404 }
405}
406
407macro_rules! format_constructors {
410 ($($(#[$attribute:meta])* $name:ident => $variant:ident,)*) => {
411 impl Error {
412 $(
413 $(#[$attribute])*
414 pub(crate) fn $name(message: impl Into<String>) -> Self {
415 Self::$variant(Box::new(FormatError::new(FormatErrorKind::Invalid, message)))
416 }
417 )*
418 }
419 };
420}
421
422format_constructors! {
423 midi => Midi,
424 abc => Abc,
425 humdrum => Humdrum,
426 xml => Xml,
427 mei => Mei,
428 roman_text => RomanText,
429 capella => Capella,
430 muse_data => MuseData,
431 noteworthy => Noteworthy,
432 muse_score => MuseScore,
433 #[cfg(feature = "musicxml")]
434 music_xml => MusicXml,
435}
436
437impl Error {
438 pub fn unplaced(&self) -> &Error {
441 match self {
442 Self::Placed(placed) => &placed.error,
443 _ => self,
444 }
445 }
446
447 pub fn format_error(&self) -> Option<&FormatError> {
450 match self.unplaced() {
451 Self::Midi(error)
452 | Self::Abc(error)
453 | Self::Humdrum(error)
454 | Self::Xml(error)
455 | Self::Mei(error)
456 | Self::RomanText(error)
457 | Self::Capella(error)
458 | Self::MuseData(error)
459 | Self::Noteworthy(error)
460 | Self::MuseScore(error) => Some(error.as_ref()),
461 #[cfg(feature = "musicxml")]
462 Self::MusicXml(error) => Some(error.as_ref()),
463 _ => None,
464 }
465 }
466
467 fn format_error_mut(&mut self) -> Option<&mut FormatError> {
468 match self {
469 Self::Midi(error)
470 | Self::Abc(error)
471 | Self::Humdrum(error)
472 | Self::Xml(error)
473 | Self::Mei(error)
474 | Self::RomanText(error)
475 | Self::Capella(error)
476 | Self::MuseData(error)
477 | Self::Noteworthy(error)
478 | Self::MuseScore(error) => Some(error.as_mut()),
479 #[cfg(feature = "musicxml")]
480 Self::MusicXml(error) => Some(error.as_mut()),
481 _ => None,
482 }
483 }
484
485 pub fn position(&self) -> Option<&Position> {
487 if let Self::Placed(placed) = self {
488 return Some(&placed.position);
489 }
490 self.format_error()?.position.as_ref()
491 }
492
493 fn position_mut(&mut self) -> Option<&mut Position> {
495 if let Self::Placed(placed) = self {
496 return Some(&mut placed.position);
497 }
498 self.format_error_mut()?.position.as_mut()
499 }
500
501 #[must_use]
503 pub(crate) fn of_kind(mut self, kind: FormatErrorKind) -> Self {
504 if let Some(error) = self.format_error_mut() {
505 error.kind = kind;
506 }
507 self
508 }
509
510 #[must_use]
514 pub(crate) fn lines_down(mut self, before: usize) -> Self {
515 let line = self
516 .position_mut()
517 .and_then(|position| position.line.as_mut());
518 if let Some(line) = line {
519 *line += before;
520 }
521 self
522 }
523
524 #[must_use]
529 pub(crate) fn placed(mut self, position: impl FnOnce() -> Position) -> Self {
530 if let Some(known) = self.position_mut() {
531 known.fill_from(position());
532 return self;
533 }
534 if let Some(error) = self.format_error_mut() {
535 error.position = Some(position());
536 return self;
537 }
538 Self::Placed(Box::new(PlacedError {
539 error: self,
540 position: position(),
541 }))
542 }
543}
544
545impl From<Infallible> for Error {
546 fn from(value: Infallible) -> Self {
547 match value {}
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use super::*;
554 use std::error::Error as StdError;
555
556 #[test]
557 fn test_display_music21object() {
558 let err = Error::Music21Object("error message".to_string());
559 assert_eq!(format!("{err}"), "Music21Object error: error message");
560 }
561
562 #[test]
563 fn test_display_chord() {
564 let err = Error::Chord("chord error".to_string());
565 assert_eq!(format!("{err}"), "Chord error: chord error");
566 }
567
568 #[test]
569 fn test_display_pitch() {
570 let err = Error::Pitch("pitch error".to_string());
571 assert_eq!(format!("{err}"), "Pitch error: pitch error");
572 }
573
574 #[test]
575 fn test_display_microtone() {
576 let err = Error::Microtone("microtone error".to_string());
577 assert_eq!(format!("{err}"), "Microtone error: microtone error");
578 }
579
580 #[test]
581 fn test_display_accidental() {
582 let err = Error::Accidental("accidental error".to_string());
583 assert_eq!(format!("{err}"), "Accidental error: accidental error");
584 }
585
586 #[test]
587 fn test_display_chordtables() {
588 let err = Error::ChordTables("chordtables error".to_string());
589 assert_eq!(format!("{err}"), "ChordTables error: chordtables error");
590 }
591
592 #[test]
593 fn test_display_interval() {
594 let err = Error::Interval("interval error".to_string());
595 assert_eq!(format!("{err}"), "Interval error: interval error");
596 }
597
598 #[test]
599 fn test_display_stepname() {
600 let err = Error::StepName("step name error".to_string());
601 assert_eq!(format!("{err}"), "StepName error: step name error");
602 }
603
604 #[test]
605 fn test_display_ordinal() {
606 let err = Error::Ordinal("ordinal error".to_string());
607 assert_eq!(format!("{err}"), "Ordinal error: ordinal error");
608 }
609
610 #[test]
611 fn test_display_polyrhythm() {
612 let err = Error::Polyrhythm("polyrhythm error".to_string());
613 assert_eq!(format!("{err}"), "Polyrhythm error: polyrhythm error");
614 }
615
616 #[test]
617 fn test_display_tuningsystem() {
618 let err = Error::TuningSystem("tuning system error".to_string());
619 assert_eq!(format!("{err}"), "TuningSystem error: tuning system error");
620 }
621
622 #[test]
623 fn a_format_error_shows_as_its_message_under_its_format() {
624 let error = Error::abc("cannot read the meter \"x\"").placed(|| Position::line(3));
625 assert_eq!(error.to_string(), "ABC error: cannot read the meter \"x\"");
626 assert_eq!(error.position(), Some(&Position::line(3)));
627 assert_eq!(error.format_error().unwrap().kind, FormatErrorKind::Invalid);
628 assert!(Error::Pitch("pitch".to_string()).format_error().is_none());
629 }
630
631 #[test]
632 fn a_position_said_inside_keeps_what_it_says() {
633 let error = Error::midi("a tempo of no time to the quarter")
634 .placed(|| Position::default().at_tick(96))
635 .placed(|| Position::track(2).at_tick(0))
636 .of_kind(FormatErrorKind::Malformed);
637 let position = error.position().unwrap();
638 assert_eq!(position, &Position::track(2).at_tick(96));
639 assert_eq!(position.to_string(), "track 2, tick 96");
640 assert_eq!(
641 Position::measure("12").in_part("P1").to_string(),
642 "part P1, measure 12"
643 );
644 assert_eq!(
645 Position::line(4).with_column(2).to_string(),
646 "line 4, column 2"
647 );
648 let shifted = Error::humdrum("x")
649 .placed(|| Position::line(2))
650 .lines_down(3);
651 assert_eq!(shifted.position(), Some(&Position::line(5)));
652 }
653
654 #[test]
655 fn an_error_of_no_format_is_placed_around_itself() {
656 let error = Error::Pitch("cannot spell it".to_string())
657 .placed(|| Position::line(4))
658 .placed(|| Position::measure("2").with_column(9))
659 .lines_down(1);
660 assert_eq!(error.to_string(), "Pitch error: cannot spell it");
661 assert_eq!(
662 error.unplaced(),
663 &Error::Pitch("cannot spell it".to_string())
664 );
665 let mut wanted = Position::line(5).with_column(9);
666 wanted.measure = Some("2".to_string());
667 assert_eq!(error.position(), Some(&wanted));
668 assert!(error.format_error().is_none());
669
670 let read = Error::abc("x").placed(|| Position::line(1));
671 assert_eq!(read.unplaced(), &read);
672 }
673
674 #[test]
675 fn test_source_none() {
676 let errors = [
677 Error::Music21Object("music21".to_string()),
678 Error::Chord("chord".to_string()),
679 Error::Pitch("pitch".to_string()),
680 Error::Microtone("microtone".to_string()),
681 Error::Accidental("accidental".to_string()),
682 Error::ChordTables("chordtables".to_string()),
683 Error::Interval("interval".to_string()),
684 Error::StepName("step".to_string()),
685 Error::PitchClass("pitch class".to_string()),
686 Error::Ordinal("ordinal".to_string()),
687 Error::Polyrhythm("polyrhythm".to_string()),
688 Error::TuningSystem("tuning system".to_string()),
689 Error::midi("midi"),
690 Error::Analysis("analysis".to_string()),
691 ];
692
693 for err in errors.iter() {
694 assert!(
696 err.source().is_none(),
697 "Expected None for source() in {err:?}"
698 );
699 }
700 }
701
702 #[test]
703 fn test_all_errors_display() {
704 let cases = [
705 (
706 Error::Music21Object("music21".to_string()),
707 "Music21Object error: music21",
708 ),
709 (Error::Chord("chord".to_string()), "Chord error: chord"),
710 (Error::Pitch("pitch".to_string()), "Pitch error: pitch"),
711 (
712 Error::Microtone("microtone".to_string()),
713 "Microtone error: microtone",
714 ),
715 (
716 Error::Accidental("accidental".to_string()),
717 "Accidental error: accidental",
718 ),
719 (
720 Error::ChordTables("chordtables".to_string()),
721 "ChordTables error: chordtables",
722 ),
723 (
724 Error::Interval("interval".to_string()),
725 "Interval error: interval",
726 ),
727 (Error::StepName("step".to_string()), "StepName error: step"),
728 (
729 Error::PitchClass("pitchclass".to_string()),
730 "PitchClass error: pitchclass",
731 ),
732 (
733 Error::Ordinal("ordinal".to_string()),
734 "Ordinal error: ordinal",
735 ),
736 (
737 Error::Polyrhythm("polyrhythm".to_string()),
738 "Polyrhythm error: polyrhythm",
739 ),
740 (
741 Error::TuningSystem("tuning system".to_string()),
742 "TuningSystem error: tuning system",
743 ),
744 (Error::midi("midi"), "Midi error: midi"),
745 (
746 Error::Analysis("analysis".to_string()),
747 "Analysis error: analysis",
748 ),
749 (Error::Serial("serial".to_string()), "Serial error: serial"),
750 ];
751
752 for (err, expected) in cases.iter() {
753 assert_eq!(format!("{err}"), *expected);
754 assert!(err.source().is_none());
755 }
756 }
757}