croma-core 1.0.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
//! Voice timeline construction: turning a lowered event stream into measure
//! timelines, including measure segmentation and overlay handling.

use crate::diagnostic::{Diagnostic, Span};
use crate::lower::voice::{LoweredEvent, LoweredTimedEvent, LoweringState};
use crate::lower::{
    extend_span, overlay_incomplete_measure_warning, overlay_overfull_measure_warning,
};
use crate::model::{
    BarlineKind, Event, EventAttachments, Fraction, LoweredEventAtom, LoweredEventAtomKind,
    OverlaySegment, RepeatEndingPartModel, TimelineEventKind, VoiceId, VoiceMeasureTimeline,
    VoiceTimedEvent, VoiceTimeline,
};
use crate::syntax::VariantEndingPart;

pub(crate) fn build_voice_timeline(
    voice: LoweringState,
    meter_duration: Option<Fraction>,
    single_voice: bool,
    diagnostics: &mut Vec<Diagnostic>,
) -> VoiceTimeline {
    let mut builder = VoiceTimelineBuilder::new(voice.id.clone(), meter_duration, single_voice);
    for event in voice.lowered {
        builder.push(event, diagnostics);
    }
    let measures = builder.finish(diagnostics);
    VoiceTimeline {
        id: voice.id,
        initial_properties: voice.initial_properties,
        properties: voice.properties,
        measures,
        // Projected after timeline construction, in `lower_tune_music`, once the
        // whole tune's `%%MIDI` directives can be scoped to voices by position.
        midi_instrument: None,
        midi_transpose: None,
        source_span: voice.source_span,
    }
}

struct VoiceTimelineBuilder {
    voice_id: VoiceId,
    meter_duration: Option<Fraction>,
    measures: Vec<VoiceMeasureTimeline>,
    measure_index: u32,
    onset: Fraction,
    last_group_onset: Fraction,
    active_overlay: Option<OverlayBuilder>,
    overlay_count: u32,
    /// True iff the whole tune has exactly one voice. Bar-line-only "phantom"
    /// measures are only coalesced in single-voice music; in multi-voice tunes
    /// a bar-line-only measure is a legitimate tacet bar that must be kept so
    /// voices stay measure-aligned.
    single_voice: bool,
}

impl VoiceTimelineBuilder {
    fn new(voice_id: VoiceId, meter_duration: Option<Fraction>, single_voice: bool) -> Self {
        Self {
            voice_id,
            meter_duration,
            measures: vec![VoiceMeasureTimeline {
                index: 0,
                span: Span::new(0, 0),
                events: Vec::new(),
                overlays: Vec::new(),
            }],
            measure_index: 0,
            onset: Fraction::zero(),
            last_group_onset: Fraction::zero(),
            active_overlay: None,
            overlay_count: 0,
            single_voice,
        }
    }

    /// Bar-line-only measures may be coalesced only when the tune is
    /// single-voice and this voice carries no overlays (`&`): overlays imply a
    /// multi-layer measure that abc2xml preserves.
    fn may_coalesce_barline_only(&self) -> bool {
        self.single_voice && self.overlay_count == 0
    }

    fn push(&mut self, event: LoweredEvent, diagnostics: &mut Vec<Diagnostic>) {
        match event {
            LoweredEvent::Timed(timed) => self.push_timed(timed),
            LoweredEvent::Untimed(Event::Barline { kind, span }) => {
                self.finish_overlay(diagnostics);
                if self.repeat_end_closes_previous_measure(kind) {
                    self.push_barline_to_previous_measure(kind, span);
                    return;
                }
                // A redundant plain `|` in a spaced bar-run seam (`| |`, `: |`):
                // the prior glyph already closed the previous measure and opened
                // this empty one, so a further plain bar adds no boundary.
                // Absorbing it โ€” rather than recording it as this measure's
                // leading bar โ€” keeps the seam as ONE boundary, so a following
                // `|:`/`[N` leads the measure instead of being displaced one bar
                // late (tune_010091). Contiguous `||`/`:|`/`]|` are single tokens
                // that never reach here; only `Regular` is dropped, so a styled
                // closer keeps emitting. Single-voice only โ€” multi-voice empty
                // measures are preserved for alignment.
                if kind == BarlineKind::Regular
                    && self.measure_index > 0
                    && self.may_coalesce_barline_only()
                    && self.is_empty_measure_start()
                {
                    return;
                }
                let starts_current_measure = self.is_empty_measure_start()
                    && (starts_measure_barline(kind)
                        || (self.is_first_measure_start()
                            && starts_first_body_measure_barline(kind)))
                    || self.is_first_measure_combined_repeat_start(kind, span);
                self.push_barline(kind, span);
                if starts_current_measure {
                    return;
                }
                self.start_measure_after_barline(span);
            }
            LoweredEvent::KeyChange(key) => {
                let onset = self.onset;
                let span = key.source_span;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::KeyChange(key),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::MeterChange(meter) => {
                let onset = self.onset;
                let span = meter.source_span;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::MeterChange(meter),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::ClefChange(clef) => {
                let onset = self.onset;
                let span = clef.source_span;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::ClefChange(clef),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::TempoChange(tempo) => {
                let onset = self.onset;
                let span = tempo.source_span;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::TempoChange(tempo),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::SectionLabel { label, span } => {
                let onset = self.onset;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::SectionLabel(label),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::Untimed(Event::Spacer { span }) => {
                let onset = self.onset;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::Spacer,
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                    attachments: EventAttachments::default(),
                });
            }
            LoweredEvent::Untimed(Event::Note { .. } | Event::Rest { .. }) => {}
            LoweredEvent::Overlay(overlay) => {
                self.finish_overlay(diagnostics);
                let expected_duration = if self.onset == Fraction::zero() {
                    self.meter_duration.unwrap_or_else(Fraction::zero)
                } else {
                    self.onset
                };
                let overlay_id = VoiceId {
                    value: format!("{}.overlay{}", self.voice_id.value, self.overlay_count + 1),
                    span: overlay.span,
                };
                self.overlay_count = self.overlay_count.saturating_add(1);
                self.active_overlay = Some(OverlayBuilder {
                    id: overlay_id,
                    start_span: overlay.span,
                    span: overlay.span,
                    measure_index: self.measure_index,
                    expected_duration,
                    actual_duration: Fraction::zero(),
                    last_group_onset: Fraction::zero(),
                    events: Vec::new(),
                });
            }
            LoweredEvent::VariantEnding(ending) => {
                let onset = self.onset;
                let span = ending.span;
                self.current_measure_mut().events.push(VoiceTimedEvent {
                    onset,
                    duration: Fraction::zero(),
                    span,
                    line_index: 0,
                    source_order: 0,
                    alignable: false,
                    kind: TimelineEventKind::VariantEnding {
                        endings: repeat_ending_parts_model(&ending.endings),
                    },
                    attachments: EventAttachments::default(),
                    lyrics: Vec::new(),
                    symbols: Vec::new(),
                });
                self.current_measure_mut().span =
                    extend_span(self.current_measure_mut().span, span);
            }
        }
    }

    fn push_barline(&mut self, kind: BarlineKind, span: Span) {
        let onset = self.onset;
        let measure_index = self.measure_index;
        let measure = self.current_measure_mut();
        let measure_span = measure.span;
        measure.events.push(VoiceTimedEvent {
            onset,
            duration: Fraction::zero(),
            span,
            line_index: 0,
            source_order: 0,
            alignable: false,
            kind: TimelineEventKind::Barline { kind },
            lyrics: Vec::new(),
            symbols: Vec::new(),
            attachments: EventAttachments::default(),
        });
        measure.span =
            if measure_index > 0 && measure_span.is_empty() && closes_empty_measure_barline(kind) {
                Span::new(measure_span.start, span.end)
            } else {
                extend_span(measure_span, span)
            };
    }

    fn repeat_end_closes_previous_measure(&self, kind: BarlineKind) -> bool {
        matches!(kind, BarlineKind::RepeatEnd | BarlineKind::RepeatBoth)
            && self.onset == Fraction::zero()
            && self.active_overlay.is_none()
            && self.measures.len() > 1
            // The current (seam) measure carries no timed notes โ€” it is either
            // brand-new or note-less (a key/meter/clef change on its own line, as
            // in tune_011411's `K:D` seam). Such a measure cannot host the
            // backward repeat, so the `:|` retro-closes the previous real measure.
            && self.measures.last().is_some_and(is_empty_measure)
            && self.previous_measure_has_timed_content()
    }

    fn push_barline_to_previous_measure(&mut self, kind: BarlineKind, span: Span) {
        let previous_index = self.measures.len().saturating_sub(2);
        let Some(previous) = self.measures.get_mut(previous_index) else {
            return;
        };
        let onset = timeline_measure_actual_duration(previous);
        previous.events.push(VoiceTimedEvent {
            onset,
            duration: Fraction::zero(),
            span,
            line_index: 0,
            source_order: 0,
            alignable: false,
            kind: TimelineEventKind::Barline { kind },
            lyrics: Vec::new(),
            symbols: Vec::new(),
            attachments: EventAttachments::default(),
        });
        previous.span = extend_span(previous.span, span);
    }

    /// True when the measure before the current (empty) one carries real timed
    /// content โ€” a closed measure that a *leading* `:|`/`::` at a line seam must
    /// retro-close with a backward repeat, instead of dropping the repeat on the
    /// empty seam measure (a leading `RepeatEnd` matches neither barline filter
    /// in `unique_barlines`). Generalizes the earlier invisible-barline-only
    /// gate: the prior measure may be closed by any bar (`|`, `[|]`, ...), as in
    /// tune_000205 (`...^f|` then `:|2 ...`). The invisible `[|]:|` case still
    /// qualifies โ€” its prior measure also holds notes.
    fn previous_measure_has_timed_content(&self) -> bool {
        self.measures.iter().rev().nth(1).is_some_and(|measure| {
            measure.events.iter().any(|event| {
                matches!(
                    event.kind,
                    TimelineEventKind::Note { .. } | TimelineEventKind::Rest { .. }
                )
            })
        })
    }

    fn is_empty_measure_start(&self) -> bool {
        self.onset == Fraction::zero()
            && self.active_overlay.is_none()
            && self.measures.last().is_some_and(|measure| {
                // A brand-new measure (no events at all) always accepts a leading
                // bar line without opening a phantom. A measure that already holds
                // *only bar-line tokens* is a phantom produced by a run of bar
                // lines (`| |`, `|]|`, `]|`): a further bar line merges into the
                // same boundary (ABC 2.1 ยง4.8) instead of opening a new measure โ€”
                // but only past the first measure, since abc2xml preserves a single
                // leading empty (pickup) measure. Spacers (`y`, annotation-only
                // bars) and overlays are *not* treated as collapsible: abc2xml
                // keeps those measures, so they must not be coalesced here.
                if is_empty_measure(measure) {
                    return true;
                }
                self.may_coalesce_barline_only()
                    && self.measure_index > 0
                    && is_barline_only_measure(measure)
            })
    }

    fn is_first_measure_start(&self) -> bool {
        self.measure_index == 0 && self.measures.len() == 1
    }

    fn is_first_measure_combined_repeat_start(&self, kind: BarlineKind, span: Span) -> bool {
        kind == BarlineKind::RepeatStart
            && self.onset == Fraction::zero()
            && self.active_overlay.is_none()
            && self.is_first_measure_start()
            && self.measures.last().is_some_and(|measure| {
                !measure.events.is_empty()
                    && measure.overlays.is_empty()
                    && measure.events.iter().all(|event| {
                        event.duration == Fraction::zero()
                            && event.span == span
                            && matches!(
                                event.kind,
                                TimelineEventKind::Barline {
                                    kind: BarlineKind::Double | BarlineKind::Initial
                                }
                            )
                    })
            })
    }

    fn start_measure_after_barline(&mut self, span: Span) {
        self.measure_index = self.measure_index.saturating_add(1);
        self.onset = Fraction::zero();
        self.last_group_onset = Fraction::zero();
        self.measures.push(VoiceMeasureTimeline {
            index: self.measure_index,
            span: Span::new(span.end, span.end),
            events: Vec::new(),
            overlays: Vec::new(),
        });
    }

    fn push_timed(&mut self, timed: LoweredTimedEvent) {
        let span = timed_span(timed.event);
        let chord_member = matches!(
            timed.event.kind,
            LoweredEventAtomKind::Note { chord: true, .. }
        );
        let onset = if let Some(overlay) = &self.active_overlay {
            if chord_member {
                overlay.last_group_onset
            } else {
                overlay.actual_duration
            }
        } else if chord_member {
            self.last_group_onset
        } else {
            self.onset
        };
        let event = VoiceTimedEvent {
            onset,
            duration: timed.event.duration,
            span,
            line_index: timed.line_index,
            source_order: timed.source_order,
            alignable: timed.alignable
                && matches!(timed.event.kind, LoweredEventAtomKind::Note { .. }),
            kind: timeline_event_kind(timed.event.kind),
            attachments: timed.attachments,
            lyrics: Vec::new(),
            symbols: Vec::new(),
        };
        if let Some(overlay) = &mut self.active_overlay {
            if !chord_member {
                overlay.last_group_onset = event.onset;
                overlay.actual_duration = overlay.actual_duration.checked_add(timed.event.duration);
            }
            overlay.span = extend_span(overlay.span, span);
            overlay.events.push(event);
        } else {
            if !chord_member {
                self.last_group_onset = event.onset;
                self.onset = self.onset.checked_add(timed.event.duration);
            }
            self.current_measure_mut().span = extend_span(self.current_measure_mut().span, span);
            self.current_measure_mut().events.push(event);
        }
    }

    fn finish(mut self, diagnostics: &mut Vec<Diagnostic>) -> Vec<VoiceMeasureTimeline> {
        self.finish_overlay(diagnostics);
        // Pop a trailing measure that carries only bar-line tokens. Per ABC 2.1
        // ยง4.8 a run of adjacent or split bar lines (`| |`, `|]|`, `]|`) is a
        // single boundary, not a measure of music, so a trailing bar-line-only
        // measure is a phantom and must not survive. The first bar line of the
        // run already sits on the preceding real measure, so its right bar line
        // is not lost when the phantom is popped. Spacer-only or overlay-bearing
        // trailing measures are kept (abc2xml keeps them). Never pop the only
        // measure.
        let may_coalesce_barline_only = self.may_coalesce_barline_only();
        while self.measures.last().is_some_and(|measure| {
            is_empty_measure(measure)
                || (may_coalesce_barline_only && is_barline_only_measure(measure))
        }) && self.measures.len() > 1
        {
            let trailing = self
                .measures
                .pop()
                .expect("checked that a trailing measure exists");
            if let Some(previous) = self.measures.last_mut() {
                merge_visible_trailing_barlines(previous, trailing);
            }
        }
        self.measures
    }

    fn finish_overlay(&mut self, diagnostics: &mut Vec<Diagnostic>) {
        let Some(overlay) = self.active_overlay.take() else {
            return;
        };
        if overlay.actual_duration.less_than(overlay.expected_duration) {
            diagnostics.push(overlay_incomplete_measure_warning(
                overlay.start_span,
                overlay.actual_duration,
                overlay.expected_duration,
            ));
        } else if overlay.expected_duration.less_than(overlay.actual_duration) {
            diagnostics.push(overlay_overfull_measure_warning(
                overlay.start_span,
                overlay.actual_duration,
                overlay.expected_duration,
            ));
        }
        self.current_measure_mut().overlays.push(OverlaySegment {
            id: overlay.id,
            span: overlay.span,
            measure_index: overlay.measure_index,
            expected_duration: overlay.expected_duration,
            actual_duration: overlay.actual_duration,
            events: overlay.events,
        });
    }

    fn current_measure_mut(&mut self) -> &mut VoiceMeasureTimeline {
        self.measures
            .last_mut()
            .expect("timeline builder always has a current measure")
    }
}

/// A measure with no events and no overlays at all (the original phantom case:
/// a fresh measure opened after a trailing bar line with nothing following).
fn is_empty_measure(measure: &VoiceMeasureTimeline) -> bool {
    // Zero-duration key/meter/tempo change AND section-label events do not make a
    // measure real: in `...| [K:C] |: ...` (or a leading `P:A` before a pickup's
    // `|:`) the change/label belongs to the measure the `|:` opens, and the
    // pending one must keep accepting that leading barline. Without including
    // `SectionLabel`, a leading body `P:` would split off a spurious standalone
    // measure and shift every downstream measure number.
    measure.overlays.is_empty()
        && measure.events.iter().all(|event| {
            matches!(
                event.kind,
                TimelineEventKind::KeyChange(_)
                    | TimelineEventKind::MeterChange(_)
                    | TimelineEventKind::ClefChange(_)
                    | TimelineEventKind::TempoChange(_)
                    | TimelineEventKind::SectionLabel(_)
            )
        })
}

/// A measure is *bar-line-only* when it carries no overlay and every event it
/// holds is a bar line โ€” i.e. it has at least one `Barline` and nothing else.
/// Such a measure is a phantom produced by a run of bar lines (e.g. a trailing
/// `| |` / `|]|` / `]|`, or consecutive interior bar lines) and is not a measure
/// of music. A real rest (`z`/`x`/`Z`) is a `Rest` event, a `y` is a `Spacer`,
/// and an annotation/overlay carries its own events, so none of those count as
/// bar-line-only โ€” abc2xml preserves those measures.
fn is_barline_only_measure(measure: &VoiceMeasureTimeline) -> bool {
    measure.overlays.is_empty()
        && !measure.events.is_empty()
        && measure.events.iter().all(|event| {
            // Zero-duration key/meter change events do not make a measure
            // real: `| [K:C] |:` must still merge into one boundary rather
            // than opening a phantom empty measure the reference lacks.
            matches!(
                event.kind,
                TimelineEventKind::Barline { .. }
                    | TimelineEventKind::KeyChange(_)
                    | TimelineEventKind::MeterChange(_)
                    | TimelineEventKind::ClefChange(_)
            )
        })
}

fn merge_visible_trailing_barlines(
    previous: &mut VoiceMeasureTimeline,
    trailing: VoiceMeasureTimeline,
) {
    for event in trailing.events {
        let TimelineEventKind::Barline { kind } = event.kind else {
            continue;
        };
        if matches!(kind, BarlineKind::Regular | BarlineKind::Liberal) {
            continue;
        }
        if kind == BarlineKind::Final && has_repeat_end_barline(previous) {
            continue;
        }
        if previous.events.iter().any(|existing| {
            matches!(
                existing.kind,
                TimelineEventKind::Barline {
                    kind: existing_kind
                } if existing_kind == kind && existing.span == event.span
            )
        }) {
            continue;
        }
        previous.events.push(event);
    }
}

fn has_repeat_end_barline(measure: &VoiceMeasureTimeline) -> bool {
    measure.events.iter().any(|event| {
        matches!(
            event.kind,
            TimelineEventKind::Barline {
                kind: BarlineKind::RepeatEnd | BarlineKind::RepeatBoth
            }
        )
    })
}

fn timeline_measure_actual_duration(measure: &VoiceMeasureTimeline) -> Fraction {
    let mut actual = Fraction::zero();
    for event in &measure.events {
        if matches!(
            event.kind,
            TimelineEventKind::Note { .. } | TimelineEventKind::Rest { .. }
        ) {
            let end = event.onset.checked_add(event.duration);
            if actual.less_than(end) {
                actual = end;
            }
        }
    }
    actual
}

fn starts_measure_barline(kind: BarlineKind) -> bool {
    matches!(
        kind,
        BarlineKind::Regular | BarlineKind::Initial | BarlineKind::RepeatStart
    )
}

fn starts_first_body_measure_barline(kind: BarlineKind) -> bool {
    matches!(
        kind,
        BarlineKind::Double | BarlineKind::Final | BarlineKind::Liberal
    )
}

/// A visible closing-style bar line that terminates an otherwise empty (note-
/// less) measure keeps that measure's existing span start rather than collapsing
/// the span onto the bar line itself. This keeps the bar line *non-leading* so it
/// is emitted as the measure's right bar line instead of being filtered out โ€” a
/// note-less `|]`/`[|]` measure must still notate its boundary (ยง4.8; the `[|]`
/// invisible bar exports `bar-style none`, line 999). `Double` is excluded: a
/// section-leading `||` on an empty measure is absorbed, not emitted (see
/// `continued_section_leading_double_barline_does_not_close_empty_measure`), so
/// the orphan-`||` case needs separate handling. Repeat boundaries (`:|`) are
/// excluded too โ€” they attach to the preceding measure, not this one.
fn closes_empty_measure_barline(kind: BarlineKind) -> bool {
    matches!(kind, BarlineKind::Final | BarlineKind::Invisible)
}

struct OverlayBuilder {
    id: VoiceId,
    start_span: Span,
    span: Span,
    measure_index: u32,
    expected_duration: Fraction,
    actual_duration: Fraction,
    last_group_onset: Fraction,
    events: Vec<VoiceTimedEvent>,
}

fn timed_span(event: LoweredEventAtom) -> Span {
    match event.kind {
        LoweredEventAtomKind::Note { span, .. }
        | LoweredEventAtomKind::Rest { span, .. }
        | LoweredEventAtomKind::Spacer { span } => span,
    }
}

fn timeline_event_kind(kind: LoweredEventAtomKind) -> TimelineEventKind {
    match kind {
        LoweredEventAtomKind::Note {
            step,
            octave,
            accidental,
            effective_accidental,
            accidental_source,
            chord,
            ..
        } => TimelineEventKind::Note {
            step,
            octave,
            accidental,
            effective_accidental,
            accidental_source,
            chord,
        },
        LoweredEventAtomKind::Rest {
            visibility,
            multiple_rest,
            ..
        } => TimelineEventKind::Rest {
            visibility,
            multiple_rest,
        },
        LoweredEventAtomKind::Spacer { .. } => TimelineEventKind::Spacer,
    }
}

fn repeat_ending_parts_model(parts: &[VariantEndingPart]) -> Vec<RepeatEndingPartModel> {
    parts
        .iter()
        .map(|part| match part {
            VariantEndingPart::Single(number) => RepeatEndingPartModel::Single(number.value),
            VariantEndingPart::Range { start, end, .. } => RepeatEndingPartModel::Range {
                start: start.value,
                end: end.value,
            },
            VariantEndingPart::Text { text, .. } => RepeatEndingPartModel::Text(text.clone()),
        })
        .collect()
}