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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
use crate::{Diagnostic, Span};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tune {
    pub reference: String,
    pub title: String,
    pub meter: String,
    pub key: String,
    pub divisions: u32,
    pub events: Vec<Event>,
    pub voices: Vec<VoiceTimeline>,
    pub score_directives: Vec<ScoreDirectiveModel>,
    pub preserved_directives: Vec<PreservedDirective>,
    pub post_tune_lyrics: Vec<TextLine>,
    pub score: Score,
}

/// Rational duration used by semantic lowering before MusicXML divisions are
/// selected.
pub type Rational = Fraction;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Score {
    pub metadata: ScoreMetadata,
    pub parts: Vec<Part>,
    pub diagnostics: Vec<Diagnostic>,
    pub divisions: u32,
    pub source_span: Span,
    pub accidental_policy: AccidentalPolicy,
}

impl Score {
    /// A score with no parts: what a tune that fails to lower, or an empty
    /// MusicXML document, produces.
    pub(crate) fn empty(span: Span, diagnostics: Vec<Diagnostic>) -> Self {
        Self {
            metadata: ScoreMetadata::empty(span),
            parts: Vec::new(),
            diagnostics,
            divisions: 1,
            source_span: span,
            accidental_policy: AccidentalPolicy::abc_default(span),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScoreMetadata {
    pub reference: TextLine,
    pub title: Option<TextLine>,
    pub composers: Vec<TextLine>,
    pub tempo: Option<TextLine>,
    /// Structured interpretation of [`Self::tempo`] for `<metronome>` export.
    pub tempo_model: Option<TempoModel>,
    pub meter: Option<MeterModel>,
    pub key: Option<KeySignatureModel>,
    pub directives: Vec<ScoreDirectiveModel>,
    pub preserved_directives: Vec<PreservedDirective>,
    pub post_tune_lyrics: Vec<TextLine>,
    pub source_span: Span,
}

impl ScoreMetadata {
    /// No title, tempo, meter, key or directives; a blank `X:` reference.
    pub(crate) fn empty(span: Span) -> Self {
        Self {
            reference: TextLine {
                text: String::new(),
                span,
            },
            title: None,
            composers: Vec::new(),
            tempo: None,
            tempo_model: None,
            meter: None,
            key: None,
            directives: Vec::new(),
            preserved_directives: Vec::new(),
            post_tune_lyrics: Vec::new(),
            source_span: span,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreservedDirective {
    pub name: TextLine,
    pub value: TextLine,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeterModel {
    pub display: String,
    /// MusicXML `<time symbol="...">` spelling when the source carried one.
    /// ABC's `M:C`/`M:C|` can imply the common cases; this field preserves
    /// foreign MusicXML symbols whose beat pair is not the ABC shorthand.
    pub time_symbol: Option<String>,
    pub duration: Option<Rational>,
    pub free_meter: bool,
    /// MusicXML-origin `<time>` restatement that must survive the ABC projection
    /// even when it repeats the already-effective meter.
    pub preserve_restatement: bool,
    pub source_span: Span,
}

impl MeterModel {
    pub(crate) fn structurally_matches(&self, other: &Self) -> bool {
        self.display == other.display && self.time_symbol == other.time_symbol
    }
}

/// A parsed ABC `Q:` tempo field, structured for MusicXML `<metronome>` export.
///
/// The raw field text is preserved in [`ScoreMetadata::tempo`]; this model adds
/// the interpreted beat unit, beats-per-minute and any leading quoted text so
/// the writer can emit a real metronome direction rather than plain words.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TempoModel {
    /// Optional quoted text accompanying the tempo (e.g. `"Allegro"`).
    pub text: Option<String>,
    /// Beat unit and bpm, when the field carries a numeric tempo.
    pub beat: Option<TempoBeat>,
    /// Whether the numeric tempo was a visible metronome or playback-only
    /// MusicXML `<sound tempo>`. ABC `Q:` creates visible metronomes; imported
    /// playback-only tempo uses a croma carrier so the round trip does not print
    /// a metronome that was absent from the source.
    pub beat_role: TempoBeatRole,
    pub source_span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TempoBeatRole {
    PrintedMetronome,
    PlaybackSoundOnly,
}

/// The numeric component of a tempo: a beat-unit fraction and its bpm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TempoBeat {
    /// Beat-unit fraction numerator (e.g. `1` for `1/4`, `3` for `3/8`).
    pub beat_numerator: u32,
    /// Beat-unit fraction denominator (e.g. `4` for `1/4`, `8` for `3/8`).
    pub beat_denominator: u32,
    /// Beats per minute.
    pub bpm: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeySignatureModel {
    pub display: String,
    pub fifths: i8,
    pub explicit_accidentals: Vec<KeyAccidentalModel>,
    /// MusicXML-origin `<key>` restatement that must survive the ABC projection
    /// even when it repeats the already-effective key (mirrors
    /// [`MeterModel::preserve_restatement`]).
    pub preserve_restatement: bool,
    pub source_span: Span,
}

impl KeySignatureModel {
    pub(crate) fn structurally_matches(&self, other: &Self) -> bool {
        self.fifths == other.fifths && self.explicit_accidentals == other.explicit_accidentals
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClefChangeModel {
    pub clef: TextLine,
    pub source_span: Span,
    pub musicxml_cursor_pre_backup: Option<Fraction>,
    pub musicxml_cursor_back: Option<Fraction>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyAccidentalModel {
    pub step: char,
    pub accidental: Accidental,
    pub source_span: Span,
}

/// ABC accidentals are source-significant. Croma records the written accidental
/// exactly when present, applies it to following matching pitches in the same
/// measure, and clears that measure-local state at each barline. When the key
/// signature or syntax leaves behavior ambiguous, diagnostics keep the policy
/// decision source-spanned instead of silently changing notation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccidentalPolicy {
    pub preserve_explicit_accidentals: bool,
    pub reset_at_barlines: bool,
    pub scope: AccidentalScope,
    pub source_span: Span,
}

impl AccidentalPolicy {
    /// ABC's rule: explicit accidentals are kept and last to the end of the
    /// bar, per pitch and octave.
    pub(crate) fn abc_default(span: Span) -> Self {
        Self {
            preserve_explicit_accidentals: true,
            reset_at_barlines: true,
            scope: AccidentalScope::PitchAndOctave,
            source_span: span,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccidentalScope {
    PitchAndOctave,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Part {
    pub id: PartId,
    pub name: Option<TextLine>,
    pub instruments: Vec<MusicXmlPartInstrumentModel>,
    pub staves: Vec<Staff>,
    pub voices: Vec<Voice>,
    pub source_span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartId {
    pub value: String,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Staff {
    pub id: StaffId,
    pub voices: Vec<VoiceId>,
    pub source_span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StaffId {
    pub value: u32,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Voice {
    pub id: VoiceId,
    pub staff: StaffId,
    /// MusicXML-origin part/voice initial key signature when it differs from the
    /// score-level ABC `K:` header. ABC-origin scores keep this empty.
    pub initial_key: Option<KeySignatureModel>,
    /// MusicXML-origin part/voice initial meter spelling when it differs from
    /// the score-level ABC `M:` header. Used for per-part `symbol` differences
    /// such as header `M:C|` but a later part's initial numeric `2/2`.
    pub initial_meter: Option<MeterModel>,
    pub initial_properties: VoicePropertiesModel,
    pub properties: VoicePropertiesModel,
    pub measures: Vec<Measure>,
    pub events: Vec<TimedEvent>,
    /// Score-level MIDI instrument projected from this voice's `%%MIDI program`
    /// / `%%MIDI channel` directives (see [`MidiInstrumentModel`]). `None` when
    /// the voice declared no score-translatable MIDI instrument.
    pub midi_instrument: Option<MidiInstrumentModel>,
    /// Chromatic transposition (semitones) projected from this voice's
    /// `%%MIDI transpose <n>` directive, emitted as MusicXML
    /// `<attributes><transpose><chromatic>`. Distinct from the ABC `transpose=`
    /// voice property (which is carried in [`VoicePropertiesModel`] and takes
    /// precedence when both are present). `None` when no `%%MIDI transpose` was
    /// declared.
    pub midi_transpose: Option<i16>,
    pub source_span: Span,
}

/// A score-level MIDI instrument projected from a voice's `%%MIDI program` /
/// `channel` / `control` / `midi-unpitched` directives.
///
/// `%%MIDI` is an abc2midi convention, not part of ABC 2.1; the score-meaningful
/// fields (instrument identity, channel, CC7 volume, CC10 pan, unpitched
/// percussion key) are
/// forward-translated to MusicXML `<score-instrument>` / `<midi-instrument>`
/// while the raw directive text stays in [`ScoreMetadata::preserved_directives`]
/// for round-trip / formatter use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MidiInstrumentModel {
    /// General MIDI program number exactly as written in the directive
    /// (0-based, abc2midi/GM convention). The MusicXML `<midi-program>` is this
    /// value plus one (1-based). `None` when no program was declared.
    pub program: Option<u8>,
    /// MIDI channel (1-16) from the two-integer `program <chan> <prog>` form or
    /// a sibling `%%MIDI channel` directive in the same voice. `None` when no
    /// channel was declared.
    pub channel: Option<u8>,
    /// MIDI CC7 (channel volume) value 0-127 from `%%MIDI control 7 <n>`,
    /// rendered as `<midi-instrument><volume>` (`n / 1.27`). `None` when unset.
    pub volume_cc: Option<u8>,
    /// MIDI CC10 (pan) value 0-127 from `%%MIDI control 10 <n>`, rendered as
    /// `<midi-instrument><pan>` (`n / 127 * 180 - 90`). `None` when unset.
    pub pan_cc: Option<u8>,
    /// MusicXML `<midi-unpitched>` value for unpitched percussion playback
    /// (1-128). `None` when the instrument is pitched or unspecified.
    pub midi_unpitched: Option<u8>,
    /// Source span of the directive that last set this instrument.
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MusicXmlPartInstrumentModel {
    pub id: String,
    pub name: Option<TextLine>,
    pub midi: Option<MidiInstrumentModel>,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MusicXmlInstrumentRef {
    pub id: String,
    pub span: Span,
}

impl MidiInstrumentModel {
    /// True when this projection carries at least one field worth emitting as a
    /// MusicXML `<score-instrument>` / `<midi-instrument>`.
    pub fn has_content(&self) -> bool {
        self.program.is_some()
            || self.channel.is_some()
            || self.volume_cc.is_some()
            || self.pan_cc.is_some()
            || self.midi_unpitched.is_some()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MeasureId {
    pub index: u32,
    pub number: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Measure {
    pub id: MeasureId,
    /// MusicXML-origin `<measure number>` display label. ABC-origin scores use
    /// the numeric [`MeasureId::number`]; imported MusicXML can use labels such
    /// as `0`, repeated movement-local numbers, or `X1`.
    pub display_number: Option<String>,
    pub source_span: Span,
    pub expected_duration: Option<Rational>,
    pub actual_duration: Rational,
    /// Display hint for the first measure of an expanded ABC `Zn` rest run.
    /// The measures still exist individually; this only requests the compact
    /// MusicXML multi-rest glyph.
    pub multiple_rest: Option<u32>,
    pub pickup: bool,
    pub complete: bool,
    pub barlines: Vec<MeasureBarline>,
    pub repeat_endings: Vec<RepeatEndingModel>,
    /// MusicXML-origin explicit volta closes (`<ending type="stop|discontinue">`)
    /// that cannot be inferred from ABC barline syntax, such as a close on an
    /// implicit regular right barline. ABC-origin scores keep this empty.
    pub repeat_ending_closes: Vec<RepeatEndingCloseModel>,
    pub overlays: Vec<OverlaySegment>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MeasureBarline {
    pub kind: BarlineKind,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepeatEndingModel {
    pub span: Span,
    pub endings: Vec<RepeatEndingPartModel>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepeatEndingCloseModel {
    pub span: Span,
    pub close_type: RepeatEndingCloseType,
    pub location: RepeatEndingCloseLocation,
    pub endings: Vec<RepeatEndingPartModel>,
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RepeatEndingCloseLocation {
    Left,
    Right,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepeatEndingPartModel {
    Single(u32),
    Range { start: u32, end: u32 },
    Text(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimedEvent {
    pub measure: MeasureId,
    pub onset: Rational,
    pub duration: Rational,
    pub source: Span,
    pub kind: TimedEventKind,
    pub attachments: EventAttachments,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimedEventKind {
    Note(NoteEvent),
    Chord(ChordEvent),
    Rest(RestEvent),
    Spacer,
    Barline(MeasureBarline),
    RepeatEnding(RepeatEndingModel),
    RepeatEndingClose(RepeatEndingCloseModel),
    /// A mid-tune key change (`[K:..]` or a body `K:` line). Zero duration;
    /// the new key's alters are already baked into later pitches โ€” the event
    /// records WHERE the change was written so exporters can reproduce it.
    KeyChange(KeySignatureModel),
    /// A mid-tune meter change (`[M:..]` or a body `M:` line). Zero duration.
    MeterChange(MeterModel),
    /// A mid-tune clef change carried by `[K:..]` or a body `K:` line. Zero
    /// duration; following pitches are already lowered with the new voice
    /// octave shift.
    ClefChange(ClefChangeModel),
    /// A mid-tune tempo change (`[Q:..]` or a body `Q:` line). Zero duration.
    TempoChange(TempoModel),
    /// A body/inline `P:` section label (ABC 2.1 ยง4.3), e.g. `P:A` or `[P:B]`.
    /// Zero duration; emitted as a MusicXML `<rehearsal>`. The header `P:ABAB`
    /// play-order macro is a different construct and never produces this.
    SectionLabel(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoteEvent {
    pub pitch: Pitch,
    pub written_accidental: Option<AccidentalMark>,
    pub chord_member: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChordEvent {
    pub members: Vec<ChordMemberEvent>,
    pub source_span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChordMemberEvent {
    pub pitch: Pitch,
    pub duration: Rational,
    pub written_accidental: Option<AccidentalMark>,
    pub source_span: Span,
    pub attachments: EventAttachments,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestEvent {
    pub visibility: RestVisibility,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pitch {
    pub step: char,
    pub alter: i8,
    pub octave: i8,
    pub spelling_source: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccidentalMark {
    pub kind: Accidental,
    pub explicit: bool,
    pub courtesy: bool,
    pub source: Span,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EventAttachments {
    pub grace_groups: Vec<GraceGroupAttachment>,
    pub after_grace_groups: Vec<GraceGroupAttachment>,
    pub chord_symbols: Vec<TextAttachment>,
    pub annotations: Vec<TextAttachment>,
    pub decorations: Vec<DecorationAttachment>,
    pub instrument: Option<MusicXmlInstrumentRef>,
    pub lyrics: Vec<AlignedLyric>,
    pub lyric_same_note_extends: Vec<u32>,
    pub lyric_same_note_duplicates: Vec<AlignedLyric>,
    pub musicxml_forward: bool,
    pub musicxml_sequence_backup: Option<Fraction>,
    pub symbols: Vec<AlignedSymbol>,
    pub ties: Vec<TieAttachment>,
    pub slurs: Vec<SlurAttachment>,
    pub tuplets: Vec<TupletAttachment>,
}

impl EventAttachments {
    pub fn is_empty(&self) -> bool {
        self.grace_groups.is_empty()
            && self.after_grace_groups.is_empty()
            && self.chord_symbols.is_empty()
            && self.annotations.is_empty()
            && self.decorations.is_empty()
            && self.instrument.is_none()
            && self.lyrics.is_empty()
            && self.lyric_same_note_extends.is_empty()
            && self.lyric_same_note_duplicates.is_empty()
            && !self.musicxml_forward
            && self.musicxml_sequence_backup.is_none()
            && self.symbols.is_empty()
            && self.ties.is_empty()
            && self.slurs.is_empty()
            && self.tuplets.is_empty()
    }

    pub(crate) fn extend(&mut self, other: EventAttachments) {
        self.grace_groups.extend(other.grace_groups);
        self.after_grace_groups.extend(other.after_grace_groups);
        self.chord_symbols.extend(other.chord_symbols);
        self.annotations.extend(other.annotations);
        self.decorations.extend(other.decorations);
        if self.instrument.is_none() {
            self.instrument = other.instrument;
        }
        self.lyrics.extend(other.lyrics);
        self.lyric_same_note_extends
            .extend(other.lyric_same_note_extends);
        self.lyric_same_note_duplicates
            .extend(other.lyric_same_note_duplicates);
        self.musicxml_forward |= other.musicxml_forward;
        if self.musicxml_sequence_backup.is_none() {
            self.musicxml_sequence_backup = other.musicxml_sequence_backup;
        }
        self.symbols.extend(other.symbols);
        self.ties.extend(other.ties);
        self.slurs.extend(other.slurs);
        self.tuplets.extend(other.tuplets);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraceGroupAttachment {
    pub span: Span,
    pub slash: Option<Span>,
    pub note_count: u32,
    pub events: Vec<GraceEvent>,
    /// Slurs that bind to the FIRST grace note of this group, e.g. the `(` in
    /// `({grace}note)` opens before the grace group, so the slur starts on the
    /// grace note rather than the following main note (ABC 2.1 ยง4.11 + ยง4.20).
    pub slurs: Vec<SlurAttachment>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraceEvent {
    pub source_span: Span,
    pub kind: GraceEventKind,
    pub slurs: Vec<SlurAttachment>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GraceEventKind {
    Note(GraceNoteEvent),
    Rest(RestEvent),
    Chord(Vec<GraceNoteEvent>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraceNoteEvent {
    pub pitch: Pitch,
    pub written_accidental: Option<AccidentalMark>,
    pub decorations: Vec<DecorationAttachment>,
    /// Written length modifier of the grace note relative to the grace base
    /// unit (`/` -> 1/2, `2` -> 2, etc.; `1` when no modifier is written).
    pub length_multiplier: Fraction,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextAttachment {
    pub text: String,
    pub span: Span,
    pub placement: Option<AnnotationPlacementModel>,
    pub musicxml_harmony_text: HarmonyKindText,
}

/// Provenance of a chord symbol's MusicXML `<kind text="...">` attribute, kept so
/// a foreign `<harmony>` re-exports byte-identically. The three states are
/// distinct in MusicXML and must not be conflated: a textless `<kind>` (no `text=`
/// attribute) is not the same as `<kind text="">` (an explicit empty attribute).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum HarmonyKindText {
    /// An ABC-native chord with no MusicXML provenance. The writer synthesises the
    /// `text=` value from the chord's own ABC string.
    #[default]
    AbcNative,
    /// A foreign `<kind>` with NO `text=` attribute (functional / "textless"). The
    /// writer emits a bare `<kind>`.
    Textless,
    /// A foreign `<kind text="V">`; `V` may be empty. The writer emits it verbatim.
    Text(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnotationPlacementModel {
    Above,
    Below,
    Left,
    Right,
    Free,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecorationAttachment {
    pub name: String,
    pub span: Span,
    pub source_kind: DecorationSourceKind,
    pub placement: Option<AnnotationPlacementModel>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecorationSourceKind {
    Named,
    LegacyNamed,
    Shorthand,
    UserDefined,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TieAttachment {
    pub pair_id: u32,
    pub role: TieRole,
    pub span: Span,
    pub dotted: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TieRole {
    Start,
    Stop,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlurAttachment {
    pub pair_id: u32,
    pub role: SlurRole,
    pub span: Span,
    pub dotted: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlurRole {
    Start,
    Stop,
}

/// Reserved low bound for the `pair_id` of a slur reconstructed from a
/// cross-voice `[I:croma-xvoice-slur]` carrier (a slur whose start and stop live
/// in different voices, which ABC `(`/`)` cannot span). Lowering allocates such
/// `pair_id`s from this range so they never coincide with the small per-voice
/// slur ids; the MusicXML writer relies on that disjointness to give a
/// cross-voice slur's two ends a matching `<slur number>` even though they sit
/// under different voice keys. See `lower` and `docs/carriers.md`.
pub(crate) const XVOICE_SLUR_PAIR_ID_BASE: u32 = 1_000_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TupletAttachment {
    pub pair_id: u32,
    pub actual_notes: u32,
    pub normal_notes: u32,
    pub role: TupletRole,
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TupletRole {
    Start,
    Continue,
    Stop,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    Note {
        step: char,
        octave: i8,
        accidental: Option<Accidental>,
        chord: bool,
        duration: u32,
        span: Span,
    },
    Rest {
        visibility: RestVisibility,
        duration: u32,
        span: Span,
    },
    Spacer {
        span: Span,
    },
    Barline {
        kind: BarlineKind,
        span: Span,
    },
}

impl Event {
    pub fn span(&self) -> Span {
        match self {
            Self::Note { span, .. }
            | Self::Rest { span, .. }
            | Self::Spacer { span }
            | Self::Barline { span, .. } => *span,
        }
    }

    pub(crate) fn is_time_bearing(&self) -> bool {
        matches!(self, Self::Note { .. } | Self::Rest { .. })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoiceTimeline {
    pub id: VoiceId,
    pub initial_key: Option<KeySignatureModel>,
    pub initial_meter: Option<MeterModel>,
    pub initial_properties: VoicePropertiesModel,
    pub properties: VoicePropertiesModel,
    pub measures: Vec<VoiceMeasureTimeline>,
    /// MusicXML-origin part-list instruments carried through ABC as croma
    /// `%%MIDI instrument-def` directives.
    pub musicxml_instruments: Vec<MusicXmlPartInstrumentModel>,
    /// Score-level MIDI instrument projected from this voice's `%%MIDI` program
    /// / channel directives, carried through to the semantic [`Voice`].
    pub midi_instrument: Option<MidiInstrumentModel>,
    /// Chromatic transposition (semitones) projected from this voice's
    /// `%%MIDI transpose` directive, carried through to the semantic [`Voice`].
    pub midi_transpose: Option<i16>,
    pub source_span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoiceId {
    pub value: String,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct VoicePropertiesModel {
    pub name: Option<TextLine>,
    pub nm: Option<TextLine>,
    pub subname: Option<TextLine>,
    pub snm: Option<TextLine>,
    pub clef: Option<TextLine>,
    pub stem: Option<StemDirectionModel>,
    pub octave: Option<TextLine>,
    pub transpose: Option<TextLine>,
    pub middle: Option<TextLine>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StemDirectionModel {
    Up,
    Down,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoiceMeasureTimeline {
    pub index: u32,
    pub display_number: Option<String>,
    pub span: Span,
    pub events: Vec<VoiceTimedEvent>,
    pub overlays: Vec<OverlaySegment>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoiceTimedEvent {
    pub onset: Fraction,
    pub duration: Fraction,
    pub span: Span,
    pub line_index: usize,
    pub source_order: u32,
    pub alignable: bool,
    pub kind: TimelineEventKind,
    pub attachments: EventAttachments,
    pub lyrics: Vec<AlignedLyric>,
    pub symbols: Vec<AlignedSymbol>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimelineEventKind {
    Note {
        step: char,
        octave: i8,
        accidental: Option<Accidental>,
        effective_accidental: Option<Accidental>,
        accidental_source: Option<Span>,
        chord: bool,
    },
    Rest {
        visibility: RestVisibility,
        multiple_rest: Option<u32>,
    },
    Spacer,
    Barline {
        kind: BarlineKind,
    },
    VariantEnding {
        endings: Vec<RepeatEndingPartModel>,
    },
    VariantEndingClose {
        close_type: RepeatEndingCloseType,
        location: RepeatEndingCloseLocation,
        endings: Vec<RepeatEndingPartModel>,
    },
    KeyChange(KeySignatureModel),
    MeterChange(MeterModel),
    ClefChange(ClefChangeModel),
    TempoChange(TempoModel),
    /// A body/inline `P:` section label, mirrored from [`TimedEventKind`] so the
    /// per-voice alignment timeline carries it (zero duration, non-alignable).
    SectionLabel(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OverlaySegment {
    pub id: VoiceId,
    pub span: Span,
    pub measure_index: u32,
    pub expected_duration: Fraction,
    pub actual_duration: Fraction,
    pub events: Vec<VoiceTimedEvent>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlignedLyric {
    pub verse: u32,
    pub text: String,
    pub span: Span,
    pub control: LyricControl,
    /// Foreign MusicXML can put `<text>` and `<extend/>` in the same `<lyric>`
    /// element. ABC `w:` cannot spell that directly, so croma preserves it with
    /// a private inline carrier when projecting MusicXML to ABC.
    pub same_note_extend: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LyricControl {
    Syllable,
    Hyphen,
    Extender,
    Skip,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlignedSymbol {
    pub layer: u32,
    pub text: String,
    pub span: Span,
    pub kind: AlignedSymbolKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignedSymbolKind {
    Decoration,
    ChordSymbol,
    Annotation,
    Raw,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScoreDirectiveModel {
    pub span: Span,
    pub value: TextLine,
    pub tokens: Vec<ScoreDirectiveTokenModel>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScoreDirectiveTokenModel {
    pub span: Span,
    pub kind: ScoreDirectiveTokenKindModel,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScoreDirectiveTokenKindModel {
    Voice(String),
    GroupStart(char),
    GroupEnd(char),
    StaffSeparator,
    MeasureSeparator,
    FloatingVoiceMarker,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextLine {
    pub text: String,
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RestVisibility {
    Visible,
    Invisible,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Accidental {
    DoubleFlat,
    Flat,
    Natural,
    Sharp,
    DoubleSharp,
}

impl Accidental {
    /// The accidental for a semitone alteration in -2..=2, if any.
    pub(crate) fn from_alter(alter: i8) -> Option<Self> {
        match alter {
            -2 => Some(Self::DoubleFlat),
            -1 => Some(Self::Flat),
            0 => Some(Self::Natural),
            1 => Some(Self::Sharp),
            2 => Some(Self::DoubleSharp),
            _ => None,
        }
    }

    /// The ABC sign written before a note or a key step: `__ _ = ^ ^^`.
    pub(crate) fn abc_sign(self) -> &'static str {
        match self {
            Self::DoubleFlat => "__",
            Self::Flat => "_",
            Self::Natural => "=",
            Self::Sharp => "^",
            Self::DoubleSharp => "^^",
        }
    }

    pub(crate) fn alter(self) -> i8 {
        match self {
            Self::DoubleFlat => -2,
            Self::Flat => -1,
            Self::Natural => 0,
            Self::Sharp => 1,
            Self::DoubleSharp => 2,
        }
    }

    pub(crate) fn musicxml_name(self) -> &'static str {
        match self {
            Self::DoubleFlat => "flat-flat",
            Self::Flat => "flat",
            Self::Natural => "natural",
            Self::Sharp => "sharp",
            Self::DoubleSharp => "double-sharp",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BarlineKind {
    Regular,
    Double,
    Final,
    Initial,
    RepeatStart,
    RepeatEnd,
    RepeatBoth,
    Dotted,
    Dashed,
    Invisible,
    Liberal,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LoweredEventAtom {
    pub kind: LoweredEventAtomKind,
    pub duration: Fraction,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LoweredEventAtomKind {
    Note {
        step: char,
        octave: i8,
        accidental: Option<Accidental>,
        effective_accidental: Option<Accidental>,
        accidental_source: Option<Span>,
        chord: bool,
        span: Span,
    },
    Rest {
        visibility: RestVisibility,
        multiple_rest: Option<u32>,
        span: Span,
    },
    Spacer {
        span: Span,
    },
}

impl LoweredEventAtom {
    pub(crate) fn span(&self) -> Span {
        match self.kind {
            LoweredEventAtomKind::Note { span, .. }
            | LoweredEventAtomKind::Rest { span, .. }
            | LoweredEventAtomKind::Spacer { span } => span,
        }
    }

    pub(crate) fn into_event(self, divisions: u32) -> Event {
        let duration = self.duration.to_divisions(divisions);
        match self.kind {
            LoweredEventAtomKind::Note {
                step,
                octave,
                accidental,
                effective_accidental: _,
                accidental_source: _,
                chord,
                span,
            } => Event::Note {
                step,
                octave,
                accidental,
                chord,
                duration,
                span,
            },
            LoweredEventAtomKind::Rest {
                visibility, span, ..
            } => Event::Rest {
                visibility,
                duration,
                span,
            },
            LoweredEventAtomKind::Spacer { span } => Event::Spacer { span },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Fraction {
    pub numerator: u32,
    pub denominator: u32,
}

impl Fraction {
    pub fn zero() -> Self {
        Self {
            numerator: 0,
            denominator: 1,
        }
    }

    pub fn new(numerator: u32, denominator: u32) -> Self {
        let denominator = denominator.max(1);
        let gcd = gcd(numerator, denominator);
        Self {
            numerator: numerator / gcd,
            denominator: denominator / gcd,
        }
    }

    pub fn one() -> Self {
        Self {
            numerator: 1,
            denominator: 1,
        }
    }

    /// The largest representable duration; what the saturating operations clamp to.
    pub(crate) const MAX: Self = Self {
        numerator: u32::MAX,
        denominator: 1,
    };

    /// The exact product, or `None` when the reduced result does not fit u32/u32.
    pub(crate) fn checked_mul(self, other: Self) -> Option<Self> {
        Self::reduced_wide(
            u128::from(self.numerator) * u128::from(other.numerator),
            u128::from(self.denominator) * u128::from(other.denominator),
        )
    }

    /// The exact sum, or `None` when the reduced result does not fit u32/u32.
    pub(crate) fn checked_add(self, other: Self) -> Option<Self> {
        Self::reduced_wide(
            u128::from(self.numerator) * u128::from(other.denominator)
                + u128::from(other.numerator) * u128::from(self.denominator),
            u128::from(self.denominator) * u128::from(other.denominator),
        )
    }

    /// For running totals (onsets, cursors): the exact sum, or [`Fraction::MAX`]
    /// when it does not fit. Lowering diagnoses an unrepresentable duration where
    /// it is formed, so a total that still overflows only clamps.
    pub(crate) fn saturating_add(self, other: Self) -> Self {
        self.checked_add(other).unwrap_or(Self::MAX)
    }

    fn reduced_wide(numerator: u128, denominator: u128) -> Option<Self> {
        let denominator = denominator.max(1);
        let divisor = gcd_u128(numerator, denominator);
        Some(Self {
            numerator: u32::try_from(numerator / divisor).ok()?,
            denominator: u32::try_from(denominator / divisor).ok()?,
        })
    }

    /// This value with `dots` augmentation dots, each adding half the previous
    /// increment.
    pub(crate) fn dotted(self, dots: usize) -> Self {
        let mut duration = self;
        let mut dot = self;
        for _ in 0..dots {
            dot = Self::new(dot.numerator, dot.denominator.saturating_mul(2));
            duration = duration.saturating_add(dot);
        }
        duration
    }

    pub(crate) fn less_than(self, other: Self) -> bool {
        u64::from(self.numerator) * u64::from(other.denominator)
            < u64::from(other.numerator) * u64::from(self.denominator)
    }

    pub(crate) fn divisions_requirement(self) -> u32 {
        let denominator = u64::from(self.denominator);
        let scaled_numerator = u64::from(self.numerator) * 4;
        let gcd = gcd_u64(denominator, scaled_numerator);
        u32::try_from(denominator / gcd).unwrap_or(u32::MAX)
    }

    pub(crate) fn to_divisions(self, divisions: u32) -> u32 {
        // u128: `u32 * 4 * u32` can exceed u64. Results past u32 clamp.
        let numerator = u128::from(self.numerator) * 4 * u128::from(divisions);
        let denominator = u128::from(self.denominator.max(1));
        let value = numerator / denominator;
        u32::try_from(value.max(1)).unwrap_or(u32::MAX)
    }
}

/// Key-signature order of sharps and flats (ABC 2.1 ยง3.1.14).
pub(crate) const SHARP_ORDER: [char; 7] = ['F', 'C', 'G', 'D', 'A', 'E', 'B'];
pub(crate) const FLAT_ORDER: [char; 7] = ['B', 'E', 'A', 'D', 'G', 'C', 'F'];

/// The least common multiple, or `None` when it does not fit u32.
pub(crate) fn checked_lcm(left: u32, right: u32) -> Option<u32> {
    if left == 0 || right == 0 {
        return Some(left.max(right).max(1));
    }
    (left / gcd(left, right)).checked_mul(right)
}

pub(crate) fn gcd(mut left: u32, mut right: u32) -> u32 {
    while right != 0 {
        let remainder = left % right;
        left = right;
        right = remainder;
    }
    left.max(1)
}

pub(crate) fn gcd_u64(mut left: u64, mut right: u64) -> u64 {
    while right != 0 {
        let remainder = left % right;
        left = right;
        right = remainder;
    }
    left.max(1)
}

/// The ratio `actual:normal` scaled by `factor_actual:factor_normal`, kept
/// unreduced when it fits u32 (tuplet ratios are written as given) and reduced
/// only when it must be; `None` when even the reduced ratio does not fit.
pub(crate) fn checked_ratio_product(
    actual: u32,
    normal: u32,
    factor_actual: u32,
    factor_normal: u32,
) -> Option<(u32, u32)> {
    let actual = u64::from(actual) * u64::from(factor_actual);
    let normal = u64::from(normal) * u64::from(factor_normal);
    ratio_to_u32(actual, normal)
}

/// `numerator:denominator` as u32s: unchanged when both fit, else reduced, else
/// `None`.
pub(crate) fn ratio_to_u32(numerator: u64, denominator: u64) -> Option<(u32, u32)> {
    if numerator <= u64::from(u32::MAX) && denominator <= u64::from(u32::MAX) {
        return Some((numerator as u32, denominator as u32));
    }
    let gcd = gcd_u64(numerator, denominator);
    let numerator = numerator / gcd;
    let denominator = denominator / gcd;
    (numerator <= u64::from(u32::MAX) && denominator <= u64::from(u32::MAX))
        .then_some((numerator as u32, denominator as u32))
}

fn gcd_u128(mut left: u128, mut right: u128) -> u128 {
    while right != 0 {
        let remainder = left % right;
        left = right;
        right = remainder;
    }
    left.max(1)
}

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