// ScoreSectionTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth // MARK: - ScoreSectionTests @MainActor @Suite("ScoreSection — section-based score authoring") struct ScoreSectionTests { // MARK: - 1. Back-compat: flat Score(parts:) is unchanged @Test func flatScorePartsUnchanged() { let score: Score = Score(bpm: 120) { Part("lead") { Note(.c, 4, dur: .quarter) Note(.e, 4, dur: .quarter) } Part("bass", channel: 1) { Note(.c, 2, dur: .half) } } #expect(score.parts.count == 2) #expect(score.rehearsalMarks.isEmpty) let leadEvents: [ScoreEvent] = score.parts[0].flatten() #expect(leadEvents.count == 2) #expect(leadEvents[0].beat == 0.0) #expect(leadEvents[1].beat == 1.0) } // MARK: - 2. Two sections concatenate with continuous global measure numbers @Test func twoSectionsContinuousGlobalMeasures() { // Section A: 4/4, 1 bar (measures 1) // Section B: 4/4, 1 bar (measures 2) // Both sections have the same "lead" part. let score: Score = Score(bpm: 120) { Section("A") { Part("lead") { Note(.c, 4, dur: .whole) } } Section("B") { Part("lead") { Note(.g, 4, dur: .whole) } } } #expect(score.parts.count == 1) // Section A lands at measure 1, Section B at measure 2. #expect(score.rehearsalMarks[1] == "A") #expect(score.rehearsalMarks[2] == "B") // The flat part must have 2 beats from section A (4 beats whole) + // 2 beats from section B = 8 beats total (two wholes). let events: [ScoreEvent] = score.parts[0].flatten() #expect(events.count == 2) // First note at beat 0, second at beat 4 (after one 4/4 bar). #expect(abs(events[0].beat - 0.0) < 1e-12) #expect(abs(events[1].beat - 4.0) < 1e-12) } // MARK: - 3. TACET instrument gets rest-filled and stays bar-aligned @Test func tacetInstrumentFillsWithRests() { // Section A (4/4, 1 bar): "lead" plays, "bass" is TACET. // Section B (4/4, 1 bar): "bass" plays, "lead" is TACET. let score: Score = Score(bpm: 120) { Section("A") { Part("lead") { Note(.c, 4, dur: .whole) } } Section("B") { Part("bass") { Note(.c, 2, dur: .whole) } } } #expect(score.parts.count == 2) // "lead" should have: whole-note in section A + rest in section B. // When flattened: 1 sounding event at beat 0, rest is not a sounding event. let leadPart: ScorePart = score.parts[0] #expect(leadPart.id == "lead") let leadEvents: [ScoreEvent] = leadPart.flatten() #expect(leadEvents.count == 1) #expect(abs(leadEvents[0].beat - 0.0) < 1e-12) // "bass" should have: rest in section A + whole-note in section B. // The whole-note in section B starts at beat 4 (after the 4/4 section A). let bassPart: ScorePart = score.parts[1] #expect(bassPart.id == "bass") let bassEvents: [ScoreEvent] = bassPart.flatten() #expect(bassEvents.count == 1) #expect(abs(bassEvents[0].beat - 4.0) < 1e-12) } // MARK: - 3b. A present-but-short part is padded to the section's longest part @Test func presentShortPartPaddedToSectionSpan() { // Section A (4/4): violin plays 1 bar, cello plays 3 bars. The violin must // be rest-padded to the section's full span (3 bars) so every present part // bar-aligns to the last measure expressed across the parts. let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) { Section("A") { Part("violin") { Note(.c, 5, dur: .whole) // 1 bar } Part("cello") { Note(.c, 3, dur: .whole) Note(.d, 3, dur: .whole) Note(.e, 3, dur: .whole) // 3 bars } } } // Both parts span 3 full bars (12 quarter-beats) after padding. #expect(abs(score.parts[0].lastBeat() - 4.0) < 1e-12) // violin sounds 1 bar #expect(abs(score.totalBeats - 12.0) < 1e-12) // section spans 3 bars // The encoded violin part has 3 measures (padded), matching the cello. let xml: String = score.toMusicXMLString() let violinBlock: String = { guard let r: Range = xml.range(of: ""), let e: Range = xml.range(of: "", range: r.upperBound..= 1 local measures; the base bpm is score.bpm). #expect(tc.count == 2) let tc1: TempoChange? = tc.first { $0.measure == 1 } let tc3: TempoChange? = tc.first { $0.measure == 3 } #expect(tc1 != nil) #expect(tc3 != nil) #expect(abs((tc1?.bpm ?? 0) - 80.0) < 1e-10) #expect(abs((tc3?.bpm ?? 0) - 160.0) < 1e-10) } // MARK: - 6. Section's local repeat structure is offset correctly @Test func sectionRepeatsOffsetCorrectly() { // Section A: 1 bar with a forward repeat at local bar 1 and backward at local bar 1. // Section B: 2 bars with backward repeat at local bar 2. let sectionARepeats: RepeatStructure = RepeatStructure( forwardRepeatMeasures: [1], backwardRepeatMeasures: [1] ) let sectionBRepeats: RepeatStructure = RepeatStructure( backwardRepeatMeasures: [2] ) let score: Score = Score(bpm: 120) { Section("A", repeats: sectionARepeats) { Part("lead") { Note(.c, 4, dur: .whole) } } Section("B", repeats: sectionBRepeats) { Part("lead") { Note(.d, 4, dur: .whole) Note(.e, 4, dur: .whole) } } } // Section A occupies global bar 1; its forward + backward repeat are at global bar 1. // Section B occupies global bars 2–3; its backward repeat is at global bar 3. #expect(score.repeats.forwardRepeatMeasures.contains(1)) #expect(score.repeats.backwardRepeatMeasures.contains(1)) #expect(score.repeats.backwardRepeatMeasures.contains(3)) // Global bar 2 has no backward repeat. #expect(!score.repeats.backwardRepeatMeasures.contains(2)) } // MARK: - 7. Section meter changes are reflected in the global meterMap @Test func sectionMeterMapOffsetAndMerged() { // Section A: 4/4, 1 bar. // Section B: 3/4, 1 bar. let section3_4: MeterMap = MeterMap(TimeSignature(3, 4)) let score: Score = Score(bpm: 120) { Section("A") { Part("lead") { Note(.c, 4, dur: .whole) } } Section("B", meterMap: section3_4) { Part("lead") { Note(.g, 4, dur: .quarter) Note(.a, 4, dur: .quarter) Note(.b, 4, dur: .quarter) } } } // Global meter: 4/4 at bar 1, 3/4 at bar 2. #expect(score.meterMap.segments.count == 2) let bar1sig: TimeSignature = score.meterMap.timeSignature(atBar: 1) let bar2sig: TimeSignature = score.meterMap.timeSignature(atBar: 2) #expect(bar1sig.numerator == 4 && bar1sig.denominator == 4) #expect(bar2sig.numerator == 3 && bar2sig.denominator == 4) // Flattened events: 1 whole in section A (beat 0), 3 quarters in section B // (beats 4, 5, 6 — since section A is 4 quarters long). let events: [ScoreEvent] = score.parts[0].flatten() #expect(events.count == 4) #expect(abs(events[0].beat - 0.0) < 1e-12) #expect(abs(events[1].beat - 4.0) < 1e-12) #expect(abs(events[2].beat - 5.0) < 1e-12) #expect(abs(events[3].beat - 6.0) < 1e-12) } // MARK: - 8. Part(id:) defaults to name; matching by id across sections @Test func partIDDefaultsToName() { let part: ScorePart = Part("lead") { Note(.c, 4, dur: .quarter) } #expect(part.id == "lead") #expect(part.name == "lead") } @Test func partIDExplicitOverride() { let part: ScorePart = Part("Lead Guitar", id: "lead") { Note(.c, 4, dur: .quarter) } #expect(part.id == "lead") #expect(part.name == "Lead Guitar") } // MARK: - 9. Cross-section matching by id, even with different display names @Test func matchByIDDifferentNameAcrossSections() { // Section A: instrument with id "lead" named "Solo Lead" // Section B: same instrument id "lead" but named "Rhythm Lead" // They should merge into a single flat part. let score: Score = Score(bpm: 120) { Section("A") { Part("Solo Lead", id: "lead") { Note(.c, 5, dur: .whole) } } Section("B") { Part("Rhythm Lead", id: "lead") { Note(.e, 5, dur: .whole) } } } // One part total, identified by the first-seen name "Solo Lead". #expect(score.parts.count == 1) let p: ScorePart = score.parts[0] #expect(p.id == "lead") #expect(p.name == "Solo Lead") // first-seen name wins // Both notes should appear: C5 at beat 0, E5 at beat 4. let events: [ScoreEvent] = p.flatten() #expect(events.count == 2) #expect(abs(events[0].beat - 0.0) < 1e-12) #expect(abs(events[1].beat - 4.0) < 1e-12) let midiNotes: [Int] = events.compactMap { $0.pitch.midiNote }.sorted() #expect(midiNotes == [72, 76]) // C5=72, E5=76 } // MARK: - 10. Flatten / playback sequences events with correct global beat offsets @Test func flattenedEventsHaveCorrectGlobalBeats() { // Three 4/4 sections, each 1 bar. // Section A: quarter note C4 // Section B: half note E4 // Section C: whole note G4 let score: Score = Score(bpm: 120) { Section("A") { Part("p") { Note(.c, 4, dur: .quarter) } } Section("B") { Part("p") { Note(.e, 4, dur: .half) } } Section("C") { Part("p") { Note(.g, 4, dur: .whole) } } } let events: [ScoreEvent] = score.parts[0].flatten() #expect(events.count == 3) // Section A: beat 0 (bar 1 starts at beat 0) #expect(abs(events[0].beat - 0.0) < 1e-12) // Section B: beat 4 (bar 2 starts at beat 4) #expect(abs(events[1].beat - 4.0) < 1e-12) // Section C: beat 8 (bar 3 starts at beat 8) #expect(abs(events[2].beat - 8.0) < 1e-12) } // MARK: - 11. MusicXML output contains rehearsal marks at correct measures @Test func musicXMLContainsRehearsalMarks() { let score: Score = Score(bpm: 120) { Section("Intro") { Part("p") { Note(.c, 4, dur: .whole) } } Section("A") { Part("p") { Note(.g, 4, dur: .whole) } } } let xml: String = score.toMusicXMLString() // Measure 1 should contain a rehearsal "Intro". #expect(xml.contains("Intro")) // Measure 2 should contain a rehearsal "A". #expect(xml.contains("A")) } @Test func rehearsalMarksAsStaffTextEmitsBoxedWords() { // Multi-part score so the system-object constraint (mark in the first part // only) is exercised for the path too. let score: Score = Score(bpm: 120) { Section("Intro") { Part("lead") { Note(.c, 4, dur: .whole) } Part("bass") { Note(.c, 2, dur: .whole) } } Section("A") { Part("lead") { Note(.g, 4, dur: .whole) } Part("bass") { Note(.g, 2, dur: .whole) } } } // Default: standard elements, no . let standard: String = score.toMusicXMLString() #expect(standard.contains("Intro")) #expect(!standard.contains(", verbatim labels, no . let introBox: String = "Intro" let aBox: String = "A" let asWords: String = score.toMusicXMLString(rehearsalMarksAsStaffText: true) #expect(asWords.contains(introBox)) #expect(asWords.contains(aBox)) #expect(!asWords.contains("")) // System object: each label appears exactly once (first part only). #expect(asWords.components(separatedBy: introBox).count - 1 == 1) #expect(asWords.components(separatedBy: aBox).count - 1 == 1) // The Data convenience honours the flag too. let dataString: String = String( decoding: score.toMusicXMLData(rehearsalMarksAsStaffText: true), as: UTF8.self ) #expect(dataString.contains(introBox)) } // MARK: - 12. Rehearsal marks only appear in the first part (system objects) @Test func rehearsalMarksOnlyInFirstPart() { let score: Score = Score(bpm: 120) { Section("Verse") { Part("lead") { Note(.c, 4, dur: .whole) } Part("bass") { Note(.c, 2, dur: .whole) } } Section("Chorus") { Part("lead") { Note(.g, 4, dur: .whole) } Part("bass") { Note(.g, 2, dur: .whole) } } } let xml: String = score.toMusicXMLString() // Count rehearsal mark occurrences — should be exactly 2 (one per section, // both in the first part only). let verseCount: Int = xml.components(separatedBy: "Verse").count - 1 let chorusCount: Int = xml.components(separatedBy: "Chorus").count - 1 #expect(verseCount == 1) #expect(chorusCount == 1) } // MARK: - 13. Two consecutive same-meter sections deduplicate segment @Test func consecutiveSameMeterSectionsDeduplicateSegment() { let score: Score = Score(bpm: 120) { Section("A") { Part("p") { Note(.c, 4, dur: .whole) } } Section("B") { Part("p") { Note(.g, 4, dur: .whole) } } } // Both sections are default 4/4. The global meterMap should have exactly // one segment (deduplicated consecutive equal signatures). #expect(score.meterMap.segments.count == 1) #expect(score.meterMap.timeSignature(atBar: 1).numerator == 4) } // MARK: - 14. Section DSL builder produces correct ScoreSection @Test func sectionDSLBuilderProducesCorrectSection() { let section: ScoreSection = Section("MySection", tempoChanges: [TempoChange(measure: 1, bpm: 90)]) { Part("p") { Note(.c, 4, dur: .whole) } } #expect(section.name == "MySection") #expect(section.parts.count == 1) #expect(section.tempoChanges.count == 1) #expect(abs(section.tempoChanges[0].bpm - 90.0) < 1e-10) #expect(section.tempoChanges[0].measure == 1) } // MARK: - 15. ScoreSectionBuilder array initializer @Test func scoreArraySectionInit() { let sections: [ScoreSection] = [ ScoreSection(name: "X", parts: [ ScorePart(name: "p", elements: [Note(.c, 4, dur: .whole)]) ]), ScoreSection(name: "Y", parts: [ ScorePart(name: "p", elements: [Note(.g, 4, dur: .whole)]) ]) ] let score: Score = Score(sections: sections, bpm: 100) #expect(score.parts.count == 1) #expect(score.rehearsalMarks[1] == "X") #expect(score.rehearsalMarks[2] == "Y") } // MARK: - First-section anacrusis keeps TACET parts aligned @Test func firstSectionAnacrusisKeepsTacetAligned() { // Section A: 4/4 with a 1-beat pickup. "lead" plays the pickup quarter + // a full bar (1 + 4 = 5 beats); "bass" is TACET. Section B: "bass" plays. // The bass's section-B onset must be at global beat 5 (pickup 1 + bar 4), // not 4 — i.e. the TACET fill must include the anacrusis. let pickup: Fraction = Fraction(num: 1, den: 1) // one quarter let score: Score = Score(bpm: 120) { Section("A", meterMap: MeterMap(TimeSignature(4, 4), anacrusis: pickup)) { Part("lead") { Note(.c, 5, dur: .quarter) // pickup Note(.d, 5, dur: .whole) // bar 1 } } Section("B") { Part("bass") { Note(.c, 2, dur: .whole) } } } let bassPart: ScorePart = score.parts.first { $0.id == "bass" } ?? score.parts[1] let bassEvents: [ScoreEvent] = bassPart.flatten() #expect(bassEvents.count == 1) #expect(abs(bassEvents[0].beat - 5.0) < 1e-12, "TACET bass must be padded by pickup(1) + bar(4) = 5 beats before section B") } // MARK: - Key signature: first section wins (rendered in measure 1) @Test func firstSectionKeySignatureWins() { // Section A declares G major, section B declares D major. The assembled // score's global key is G major (measure 1 belongs to the first section). let score: Score = Score(bpm: 120) { Section("A", keySignature: .gMajor) { Part("lead") { Note(.g, 4, dur: .whole) } } Section("B", keySignature: .dMajor) { Part("lead") { Note(.d, 4, dur: .whole) } } } #expect(score.keySignature == .gMajor) } @Test func pickupOnlySectionFloorsToOneMeasureNoCollision() { // A first section whose entire content fits within its pickup would make // _measureSpan return 0; flooring to 1 measure must keep measure offsets // distinct so the next section (with a DIFFERENT meter) does not collide a // meter segment / rehearsal mark at the same global bar (which previously // tripped MeterMap's duplicate-startBar precondition). let pickup: Fraction = Fraction(num: 1, den: 1) // one quarter == content below let score: Score = Score(bpm: 120) { Section("P", meterMap: MeterMap(TimeSignature(4, 4), anacrusis: pickup)) { Part("lead") { Note(.c, 5, dur: .quarter) } // fits within the pickup } Section("Q", meterMap: MeterMap(TimeSignature(3, 4))) { Part("lead") { Note(.d, 5, dur: .dotted(.half)) } } } // Distinct rehearsal marks at distinct global measures (no clobber). #expect(score.rehearsalMarks[1] == "P") #expect(score.rehearsalMarks[2] == "Q") // Encoding must not trap (the meter segments land at distinct bars). let xml: String = score.toMusicXMLString() #expect(xml.contains("P")) #expect(xml.contains("Q")) } @Test func firstSectionNilKeyFallsBackToCallerKey() { // First section has no key override → the caller-supplied score key wins. let score: Score = Score(bpm: 120, keySignature: .fMajor) { Section("A") { Part("lead") { Note(.f, 4, dur: .whole) } } Section("B", keySignature: .dMajor) { Part("lead") { Note(.d, 4, dur: .whole) } } } #expect(score.keySignature == .fMajor) } // MARK: - Score-level timeSignature applies to sections @Test func scoreTimeSignatureAppliesToSectionsWithoutMeterMap() { // Score-level 3/4 governs section A (no meterMap); section B overrides to 2/4. let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) { Section("A") { Part("p") { Note(.c, 5, dur: .quarter) Note(.d, 5, dur: .quarter) Note(.e, 5, dur: .quarter) // 3 quarters = one bar of 3/4 } } Section("B", meterMap: MeterMap(TimeSignature(2, 4))) { Part("p") { Note(.c, 5, dur: .quarter) Note(.d, 5, dur: .quarter) // 2 quarters = one bar of 2/4 } } } #expect(score.meterMap.timeSignature(atBar: 1).tuple == (3, 4)) // inherited #expect(score.meterMap.timeSignature(atBar: 2).tuple == (2, 4)) // override wins } @Test func sectionsDefaultTo4_4WhenNoScoreTimeSignature() { let score: Score = Score(bpm: 120) { Section("A") { Part("p") { Note(.c, 5, dur: .whole) } } } #expect(score.meterMap.timeSignature(atBar: 1).tuple == (4, 4)) } @Test func scoreSectionsAcceptTimeSignatureAndKeySignatureTogether() { // The previously-impossible combination: timeSignature + keySignature + sections. let score: Score = Score( bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .dMinor ) { Section("A") { Part("p") { Note(.c, 5, dur: .whole) } } } #expect(score.keySignature == .dMinor) #expect(score.meterMap.timeSignature(atBar: 1).tuple == (4, 4)) #expect(score.rehearsalMarks[1] == "A") } // MARK: - Section end barlines @Test func sectionEndBarlineRecordedAtLastGlobalMeasure() { // Section A: 2 bars of 4/4 → last bar is global measure 2. // Section B: 1 bar → last bar is global measure 3. let score: Score = Score { Section("A", endBarline: .double) { Part("p") { Note(.c, 5, dur: .whole) Note(.d, 5, dur: .whole) } } Section("B", endBarline: .final) { Part("p") { Note(.e, 5, dur: .whole) } } } #expect(score.measureBarlines[2] == .double) #expect(score.measureBarlines[3] == .final) // Sections without endBarline contribute nothing. #expect(score.measureBarlines.count == 2) } @Test func sectionEndBarlineEmitsBarStyle() { let score: Score = Score { Section("A", endBarline: .double) { Part("p") { Note(.c, 5, dur: .whole) } } Section("B", endBarline: .final) { Part("p") { Note(.e, 5, dur: .whole) } } } let xml: String = score.toMusicXMLString() #expect(xml.contains("light-light")) #expect(xml.contains("light-heavy")) } @Test func backwardRepeatSuppressesSectionBarStyle() { // A backward repeat on the same (last) measure must win — the section's // .final style is suppressed so only one light-heavy bar-style emits, and // a backward is present. let score: Score = Score { Section("A", repeats: RepeatStructure(backwardRepeatMeasures: [1]), endBarline: .final) { Part("p") { Note(.c, 5, dur: .whole) } } } let xml: String = score.toMusicXMLString() #expect(xml.contains("")) // Exactly one light-heavy bar-style (the repeat's), not two stacked. let occurrences: Int = xml.components(separatedBy: "light-heavy").count - 1 #expect(occurrences == 1) } @Test func allBarlineStylesMapToMusicXMLTokens() { let expected: [(BarlineStyle, String)] = [ (.regular, "regular"), (.double, "light-light"), (.final, "light-heavy"), (.heavy, "heavy"), (.dashed, "dashed"), (.dotted, "dotted"), (.tick, "tick"), (.short, "short"), (.invisible, "none") ] // Exhaustive: every case must be exercised (count guards against a new // case slipping through untested). #expect(expected.count == BarlineStyle.allCases.count) for (style, token): (BarlineStyle, String) in expected { #expect(style.musicXMLBarStyle == token) } } @Test func sectionBarStyleCoexistsWithEndingStopInDTDOrder() { // An endBarline landing on a measure that is also an ending-stop (hook // ending, no backward repeat) must emit both, with the bar-style BEFORE // the ending per the MusicXML child order. let score: Score = Score { Section("A", repeats: RepeatStructure(endings: [Ending(number: 1, startMeasure: 1, stopMeasure: 1)]), endBarline: .double) { Part("p") { Note(.c, 5, dur: .whole) } } } let xml: String = score.toMusicXMLString() // The right barline carries the bar-style and the ending STOP; assert the // bar-style precedes the ending-stop (the ending START sits in the left // barline earlier in the document and is not what we compare against). guard let barStyleIdx: Range = xml.range(of: "light-light"), let endingStopIdx: Range = xml.range(of: "type=\"stop\"") else { Issue.record("expected both bar-style and ending-stop in output") return } #expect(barStyleIdx.lowerBound < endingStopIdx.lowerBound) } @Test func noEndBarlineProducesNoExtraBarStyle() { let score: Score = Score { Section("A") { Part("p") { Note(.c, 5, dur: .whole) } } } let xml: String = score.toMusicXMLString() #expect(!xml.contains("")) #expect(score.measureBarlines.isEmpty) } }