croma-core 1.4.0

Library-first ABC to MusicXML exporter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
use crate::diagnostic::{Diagnostic, RecoveryNote, Severity, Span, SpecReference};
use crate::model::{
    AccidentalMark, ClefChangeModel, DecorationAttachment, EventAttachments, Fraction,
    GraceNoteEvent, Pitch, RestEvent, RestVisibility, Score, SlurRole, StaffId, TimedEvent,
    TimedEventKind, TimelineEventKind, TupletAttachment, VoiceTimedEvent, XVOICE_SLUR_PAIR_ID_BASE,
};
use crate::options::MusicXmlWriteOptions;
use crate::parse::ParseReport;

pub(crate) mod attributes;
mod barline;
mod direction;
mod engrave;
mod grace;
mod harmony;
mod lyric;
pub(crate) mod notation;
mod note;
#[cfg(feature = "musicxml-reader")]
pub mod read;
mod score;

/// Every decoration name (the text between `!…!`, in the spelling the parser
/// stores, aliases included) that the MusicXML writer maps: to a notation, a
/// dynamic or other direction, a hairpin, or a deliberate no-op (`roll`).
/// Croma's private `croma-*`/`musicxml-*` carrier names are not listed. Tools
/// such as the LSP build their hover and completion tables from this list.
pub const DECORATION_NAMES: &[&str] = &[
    // Articulations.
    ".",
    "staccato",
    ">",
    "accent",
    "emphasis",
    "tenuto",
    "wedge",
    "marcato",
    "breath",
    "caesura",
    "detached-legato",
    "falloff",
    "doit",
    "slide",
    // Fermatas.
    "fermata",
    "invertedfermata",
    // Ornaments.
    "trill",
    "mordent",
    "lowermordent",
    "uppermordent",
    "pralltriller",
    "turn",
    "invertedturn",
    "arpeggio",
    "roll",
    // Technical marks and fingerings.
    "upbow",
    "downbow",
    "open",
    "thumb",
    "snap",
    "+",
    "plus",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    // Dynamics.
    "pppppp",
    "ppppp",
    "pppp",
    "ppp",
    "pp",
    "p",
    "mp",
    "mf",
    "f",
    "ff",
    "fff",
    "ffff",
    "fffff",
    "ffffff",
    "sf",
    "sfp",
    "sfpp",
    "fp",
    "rf",
    "rfz",
    "sfz",
    "sffz",
    "fz",
    "n",
    "pf",
    "sfzp",
    // Navigation symbols.
    "coda",
    "segno",
    // Hairpins.
    "crescendo(",
    "<(",
    "crescendo)",
    "<)",
    "diminuendo(",
    ">(",
    "diminuendo)",
    ">)",
];

pub fn write_score_partwise(score: &Score) -> ParseReport<String> {
    write_score_partwise_with_options(score, MusicXmlWriteOptions::default())
}

pub fn write_score_partwise_with_options(
    score: &Score,
    options: MusicXmlWriteOptions,
) -> ParseReport<String> {
    let mut writer = MusicXmlWriter::new(score, options);
    writer.write();
    ParseReport::new(writer.xml.finish(), writer.diagnostics)
}

struct MusicXmlWriter<'score> {
    score: &'score Score,
    options: MusicXmlWriteOptions,
    xml: XmlWriter,
    diagnostics: Vec<Diagnostic>,
    /// The key in effect at the current write position — the header key until
    /// a mid-tune `KeyChange` event passes through `write_event`. Used for
    /// implicit grace-note alters. Reset to the header key at each part start.
    /// (Voices within a part share this; per-voice inline divergence is rare
    /// and only affects implicit grace spelling.)
    active_key: Option<crate::model::KeySignatureModel>,
    /// The meter in effect at the current write position, initialised to the
    /// header meter at each part start and updated by mid-tune `MeterChange`
    /// events. Drives the engraving beam-grouping table (`None` = free meter).
    active_meter: Option<crate::model::MeterModel>,
    slur_numbers: SlurNumbers,
    lyric_hyphen_open: Vec<OpenLyricHyphen>,
    /// Per-tuplet-pair bracket decision (`true` = show bracket) for the sequence
    /// currently being written, under `TupletDisplay::EngravingDefault`. Empty
    /// otherwise. Consulted by `write_notations` when the source carried no explicit
    /// tuplet-display directive.
    tuplet_brackets: std::collections::HashMap<u32, bool>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct OpenLyricHyphen {
    voice_key: String,
    verse: u32,
}

impl<'score> MusicXmlWriter<'score> {
    fn new(score: &'score Score, options: MusicXmlWriteOptions) -> Self {
        Self {
            score,
            options,
            xml: XmlWriter::new(),
            active_key: score.metadata.key.clone(),
            active_meter: score.metadata.meter.clone(),
            slur_numbers: SlurNumbers::default(),
            lyric_hyphen_open: Vec::new(),
            tuplet_brackets: std::collections::HashMap::new(),
            diagnostics: Vec::new(),
        }
    }

    fn write(&mut self) {
        self.xml.declaration();
        self.xml.start("score-partwise", &[("version", "4.0")]);
        self.write_metadata();
        self.write_credits();
        self.write_part_list();
        for (part_index, part) in self.score.parts.iter().enumerate() {
            self.write_part(part, part_index);
        }
        self.xml.end("score-partwise");
    }

    fn write_forward(&mut self, duration: Fraction) {
        if duration == Fraction::zero() {
            return;
        }
        let duration = self.duration_to_divisions(duration, self.score.source_span);
        self.xml.start("forward", &[]);
        self.xml.text_element("duration", &duration.to_string());
        self.xml.end("forward");
    }

    fn write_backup(&mut self, duration: Fraction) {
        if duration == Fraction::zero() {
            return;
        }
        let duration = self.duration_to_divisions(duration, self.score.source_span);
        self.xml.start("backup", &[]);
        self.xml.text_element("duration", &duration.to_string());
        self.xml.end("backup");
    }

    fn duration_to_divisions(&mut self, duration: Fraction, span: Span) -> u32 {
        let divisions = self.score.divisions.max(1);
        // u128: `u32 * 4 * u32` can exceed u64. Results past u32 clamp.
        let numerator = u128::from(duration.numerator) * 4 * u128::from(divisions);
        let denominator = u128::from(duration.denominator.max(1));
        if numerator % denominator != 0 {
            self.diagnostics.push(non_integral_duration_warning(span));
        }
        u32::try_from((numerator / denominator).max(1)).unwrap_or(u32::MAX)
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct NoteWrite<'a> {
    pitch: Option<&'a Pitch>,
    rest: Option<&'a RestEvent>,
    duration: Fraction,
    source: Span,
    written_accidental: Option<&'a AccidentalMark>,
    attachments: &'a EventAttachments,
    chord_member: bool,
    measure_rest: bool,
    unpitched: bool,
    grace: bool,
    grace_slash: bool,
    /// Time-modification a chord MEMBER inherits from the chord's tuplet. A member
    /// carries no `tuplets` of its own (the bracket belongs to the head), so without
    /// this it would emit no `<time-modification>` and lose the ratio on re-export.
    /// `None` for the head and every non-member note — they derive it from their own
    /// `attachments.tuplets`.
    chord_tuplet_time_modification: Option<TimeModification>,
}

#[derive(Debug, Clone, Copy)]
struct GraceNoteWrite<'a> {
    note: &'a GraceNoteEvent,
    source: Span,
    chord_member: bool,
    slash: bool,
    display_duration: Fraction,
}

#[derive(Debug, Clone)]
pub(crate) struct MeasureSequence<'score> {
    voice_number: String,
    slur_voice_key: String,
    staff: StaffId,
    expected_duration: Option<Fraction>,
    actual_duration: Fraction,
    unpitched: bool,
    musicxml_sequence_backup: Option<Fraction>,
    /// 0-based slot of this voice among the voices sharing its staff (plus overlay
    /// index) — drives engraving voice-parity rules (stem/rest/slur direction).
    staff_voice_slot: usize,
    /// Whether this voice's staff carries more than one voice (or this voice has an
    /// overlay) in the measure — the engraving multi-voice trigger.
    staff_multivoice: bool,
    /// The voice's prevailing clef text (e.g. `"treble"`), for the engraving
    /// middle-line reference. `None` → treble default.
    clef_text: Option<String>,
    events: Vec<SequenceEvent<'score>>,
}

#[derive(Debug, Clone)]
enum SequenceEvent<'score> {
    Timed(&'score TimedEvent),
    Overlay(&'score VoiceTimedEvent),
}

impl SequenceEvent<'_> {
    fn onset(&self) -> Fraction {
        match self {
            Self::Timed(event) => event.onset,
            Self::Overlay(event) => event.onset,
        }
    }

    fn duration(&self) -> Fraction {
        match self {
            Self::Timed(event) => event.duration,
            Self::Overlay(event) => event.duration,
        }
    }

    fn clef_cursor_script(&self) -> Option<(&ClefChangeModel, Fraction, Fraction)> {
        match self {
            Self::Timed(event) => match &event.kind {
                TimedEventKind::ClefChange(clef) => Some((
                    clef,
                    clef.musicxml_cursor_pre_backup?,
                    clef.musicxml_cursor_back?,
                )),
                _ => None,
            },
            Self::Overlay(_) => None,
        }
    }

    fn attachments(&self) -> &EventAttachments {
        match self {
            Self::Timed(event) => &event.attachments,
            Self::Overlay(event) => &event.attachments,
        }
    }

    fn advances_time(&self) -> bool {
        match self {
            Self::Timed(event) => matches!(
                event.kind,
                TimedEventKind::Note(_) | TimedEventKind::Chord(_) | TimedEventKind::Rest(_)
            ),
            Self::Overlay(event) => matches!(
                event.kind,
                TimelineEventKind::Note { .. } | TimelineEventKind::Rest { .. }
            ),
        }
    }

    fn emits_musicxml(&self) -> bool {
        match self {
            Self::Timed(event) => {
                matches!(
                    event.kind,
                    TimedEventKind::Note(_)
                        | TimedEventKind::Chord(_)
                        | TimedEventKind::Rest(_)
                        | TimedEventKind::KeyChange(_)
                        | TimedEventKind::MeterChange(_)
                        | TimedEventKind::ClefChange(_)
                        | TimedEventKind::TempoChange(_)
                        | TimedEventKind::SectionLabel(_)
                ) || !event.attachments.is_empty()
            }
            Self::Overlay(event) => {
                matches!(
                    event.kind,
                    TimelineEventKind::Note { .. } | TimelineEventKind::Rest { .. }
                ) || !event.attachments.is_empty()
            }
        }
    }

    fn is_chord_member(&self) -> bool {
        match self {
            Self::Timed(event) => match &event.kind {
                TimedEventKind::Note(note) => note.chord_member,
                _ => false,
            },
            Self::Overlay(event) => match event.kind {
                TimelineEventKind::Note { chord, .. } => chord,
                _ => false,
            },
        }
    }

    fn is_rest(&self) -> bool {
        match self {
            Self::Timed(event) => matches!(event.kind, TimedEventKind::Rest(_)),
            Self::Overlay(event) => matches!(event.kind, TimelineEventKind::Rest { .. }),
        }
    }

    fn source_start(&self) -> usize {
        match self {
            Self::Timed(event) => event.source.start,
            Self::Overlay(event) => event.span.start,
        }
    }
}

impl MeasureSequence<'_> {
    fn is_full_measure_rest(&self, onset: Fraction, duration: Fraction, rest: &RestEvent) -> bool {
        rest.visibility == RestVisibility::Visible
            && onset == Fraction::zero()
            && self
                .expected_duration
                .is_some_and(|expected| expected == duration && self.actual_duration == expected)
    }
}

#[derive(Debug, Default)]
pub(crate) struct TupletNumbers {
    pairs: Vec<(u32, u32)>,
}

impl TupletNumbers {
    pub(crate) fn number_for(&self, pair_id: u32) -> u32 {
        self.pairs
            .iter()
            .find_map(|(pair, number)| (*pair == pair_id).then_some(*number))
            .unwrap_or(1)
    }
}

#[derive(Debug, Default)]
pub(crate) struct SlurNumbers {
    active: Vec<ActiveSlurNumber>,
}

impl SlurNumbers {
    pub(crate) fn number_for(&mut self, slur_voice_key: &str, pair_id: u32, role: SlurRole) -> u32 {
        // A cross-voice slur (reconstructed from `[I:croma-xvoice-slur]`) has its
        // two ends under different voice keys, so the per-voice start/stop
        // bookkeeping cannot pair them. Number them by `pair_id` alone — which is
        // unique in the reserved range — so both ends share one `<slur number>`.
        if pair_id >= XVOICE_SLUR_PAIR_ID_BASE {
            return self.cross_voice_number(pair_id);
        }
        match role {
            SlurRole::Start => self.start(slur_voice_key, pair_id),
            SlurRole::Stop => self.stop(slur_voice_key, pair_id),
        }
    }

    /// Number both ends of a cross-voice slur identically, independent of which
    /// end the writer emits first (voice order can place the stop before the
    /// start). The first end seen reserves the lowest free number; the second
    /// end reuses and releases it.
    fn cross_voice_number(&mut self, pair_id: u32) -> u32 {
        if let Some(index) = self
            .active
            .iter()
            .position(|active| active.pair_id == pair_id)
        {
            return self.active.remove(index).number;
        }
        let number = self.lowest_available_number();
        self.active.push(ActiveSlurNumber {
            slur_voice_key: String::new(),
            pair_id,
            number,
        });
        number
    }

    fn start(&mut self, slur_voice_key: &str, pair_id: u32) -> u32 {
        if let Some(active) = self
            .active
            .iter()
            .find(|active| active.slur_voice_key == slur_voice_key && active.pair_id == pair_id)
        {
            return active.number;
        }

        let preferred = pair_id.max(1);
        let number = if self.number_is_active(preferred) {
            self.lowest_available_number()
        } else {
            preferred
        };
        self.active.push(ActiveSlurNumber {
            slur_voice_key: slur_voice_key.to_owned(),
            pair_id,
            number,
        });
        number
    }

    fn stop(&mut self, slur_voice_key: &str, pair_id: u32) -> u32 {
        let Some(index) = self.active.iter().position(|active| {
            active.slur_voice_key == slur_voice_key && active.pair_id == pair_id
        }) else {
            return 1;
        };
        self.active.remove(index).number
    }

    fn lowest_available_number(&self) -> u32 {
        for number in 1..=u32::MAX {
            if !self.number_is_active(number) {
                return number;
            }
        }
        u32::MAX
    }

    fn number_is_active(&self, number: u32) -> bool {
        self.active.iter().any(|active| active.number == number)
    }
}

#[derive(Debug)]
struct ActiveSlurNumber {
    slur_voice_key: String,
    pair_id: u32,
    number: u32,
}

struct XmlWriter {
    output: String,
    indent: usize,
}

impl XmlWriter {
    fn new() -> Self {
        Self {
            output: String::new(),
            indent: 0,
        }
    }

    fn finish(self) -> String {
        self.output
    }

    fn declaration(&mut self) {
        self.output
            .push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    }

    fn start(&mut self, name: &str, attrs: &[(&str, &str)]) {
        self.write_indent();
        self.output.push('<');
        self.output.push_str(name);
        self.write_attrs(attrs);
        self.output.push_str(">\n");
        self.indent += 1;
    }

    fn end(&mut self, name: &str) {
        self.indent = self.indent.saturating_sub(1);
        self.write_indent();
        self.output.push_str("</");
        self.output.push_str(name);
        self.output.push_str(">\n");
    }

    fn empty(&mut self, name: &str, attrs: &[(&str, &str)]) {
        self.write_indent();
        self.output.push('<');
        self.output.push_str(name);
        self.write_attrs(attrs);
        self.output.push_str("/>\n");
    }

    fn text_element(&mut self, name: &str, text: &str) {
        self.text_element_attrs(name, &[], text);
    }

    fn text_element_attrs(&mut self, name: &str, attrs: &[(&str, &str)], text: &str) {
        self.write_indent();
        self.output.push('<');
        self.output.push_str(name);
        self.write_attrs(attrs);
        self.output.push('>');
        self.output.push_str(&escape_xml(text));
        self.output.push_str("</");
        self.output.push_str(name);
        self.output.push_str(">\n");
    }

    fn write_attrs(&mut self, attrs: &[(&str, &str)]) {
        for (name, value) in attrs {
            self.output.push(' ');
            self.output.push_str(name);
            self.output.push_str("=\"");
            self.output.push_str(&escape_xml(value));
            self.output.push('"');
        }
    }

    fn write_indent(&mut self) {
        for _ in 0..self.indent {
            self.output.push_str("  ");
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TimeModification {
    actual_notes: u32,
    normal_notes: u32,
}

impl From<&TupletAttachment> for TimeModification {
    fn from(tuplet: &TupletAttachment) -> Self {
        Self {
            actual_notes: tuplet.actual_notes,
            normal_notes: tuplet.normal_notes,
        }
    }
}

impl TimeModification {
    pub(crate) fn composite(tuplets: &[TupletAttachment]) -> Result<Option<Self>, ()> {
        let mut seen_pairs = Vec::new();
        let mut actual_notes = 1u32;
        let mut normal_notes = 1u32;
        for tuplet in tuplets {
            if seen_pairs.contains(&tuplet.pair_id) {
                continue;
            }
            seen_pairs.push(tuplet.pair_id);
            let Some(product) = crate::model::checked_ratio_product(
                actual_notes,
                normal_notes,
                tuplet.actual_notes,
                tuplet.normal_notes,
            ) else {
                return Err(());
            };
            actual_notes = product.0;
            normal_notes = product.1;
        }
        // A 1:1 composite is an identity ratio (e.g. a foreign display-only
        // `<tuplet>` bracket carrying no `<time-modification>`): it neither
        // compresses the written duration nor warrants a `<time-modification>`
        // element, so report no modification while the bracket still emits.
        Ok(
            (!seen_pairs.is_empty() && (actual_notes, normal_notes) != (1, 1)).then_some(Self {
                actual_notes,
                normal_notes,
            }),
        )
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum BarlineLocation {
    Left,
    Right,
}

impl BarlineLocation {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Left => "left",
            Self::Right => "right",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum EndingType {
    Start,
    Stop,
    Discontinue,
}

trait FractionExt {
    fn subtract(self, other: Self) -> Self;
}

impl FractionExt for Fraction {
    fn subtract(self, other: Self) -> Self {
        let numerator = self
            .numerator
            .saturating_mul(other.denominator)
            .saturating_sub(other.numerator.saturating_mul(self.denominator));
        let denominator = self.denominator.saturating_mul(other.denominator);
        Fraction::new(numerator, denominator)
    }
}

fn escape_xml(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

fn unsupported_decoration_warning(decoration: &DecorationAttachment) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.decoration.unsupported",
        format!(
            "Decoration `{}` has no MusicXML mapping and was ignored",
            decoration.name
        ),
        decoration.span,
    )
    .with_spec_reference(musicxml_reference("direction"))
    .with_recovery_note(RecoveryNote::new(
        "The decorated note was exported and timing was unchanged.",
    ))
}

fn variable_chord_duration_export_warning(span: Span) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.chord.variable_duration",
        "Variable-duration chord members were exported as same-onset MusicXML chord tones",
        span,
    )
    .with_spec_reference(musicxml_reference("chord"))
    .with_recovery_note(RecoveryNote::new(
        "The following note onset follows the semantic base chord duration.",
    ))
}

fn unsupported_grace_warning(span: Span) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.grace.unsupported",
        "Grace group has no semantic grace-note events to export",
        span,
    )
    .with_spec_reference(musicxml_reference("grace"))
    .with_recovery_note(RecoveryNote::new(
        "The following time-bearing note was exported unchanged.",
    ))
}

fn unsupported_transpose_warning(span: Span) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.transpose.unsupported",
        "Voice transpose value is not a numeric chromatic transposition",
        span,
    )
    .with_spec_reference(musicxml_reference("transpose"))
    .with_recovery_note(RecoveryNote::new(
        "The transposition text was preserved in the semantic voice properties.",
    ))
}

fn non_integral_duration_warning(span: Span) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.duration.non_integral",
        "Duration does not map exactly to the selected MusicXML divisions",
        span,
    )
    .with_spec_reference(musicxml_reference("duration"))
    .with_recovery_note(RecoveryNote::new(
        "The duration was truncated to a positive MusicXML duration value.",
    ))
}

fn unsupported_note_type_warning(span: Span, duration: Fraction) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.duration.unsupported_note_type",
        format!(
            "Duration {}/{} does not map cleanly to a supported MusicXML note type",
            duration.numerator, duration.denominator
        ),
        span,
    )
    .with_spec_reference(musicxml_reference("type"))
    .with_recovery_note(RecoveryNote::new(
        "A valid MusicXML duration was exported with a conservative quarter-note type.",
    ))
}

fn unsupported_tuplet_time_modification_warning(span: Span) -> Diagnostic {
    Diagnostic::new(
        Severity::Warning,
        "abc.musicxml.tuplet.time_modification_overflow",
        "Nested tuplet ratio product is too large for a supported MusicXML time-modification",
        span,
    )
    .with_spec_reference(musicxml_reference("time-modification"))
    .with_recovery_note(RecoveryNote::new(
        "Tuplet notation was exported, but the oversized composite time-modification was omitted.",
    ))
}

fn unsupported_duration_diagnostics(_attachments: &EventAttachments) -> Vec<Diagnostic> {
    Vec::new()
}

fn musicxml_reference(element: &str) -> SpecReference {
    SpecReference::new(format!("MusicXML 4.0 `{element}` element"))
        .with_url("https://www.w3.org/2021/06/musicxml40/musicxml-reference/")
}

#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;