Skip to main content

music21/noteworthy/
mod.rs

1//! NoteWorthy Composer's text format, `.nwctxt`: music21's
2//! `noteworthy.translate`.
3//!
4//! A file is a line per object, each `|Command|Name:value|Name:value`, and
5//! [`from_noteworthy`] reads it into a score of a part per staff. The binary
6//! `.nwc` format is read by [`from_nwc`], which writes it out as those lines
7//! first, as music21 does.
8
9mod binary;
10pub mod placement;
11
12pub use binary::{
13    ALTERATION_TEXTS, BAR_STYLES, CLEF_NAMES, DURATION_VALUES, FLAT_MASK, MIDI_INSTRUMENTS, Member,
14    NwcFont, NwcHeader, NwcObject, NwcReader, NwcStaff, OCTAVE_SHIFT_NAMES, Object, SHARP_MASK,
15    dump_lines, from_nwc, nwc_lines,
16};
17
18use crate::bar::{Barline, BarlineType, BracketPlace, Ending, RepeatDirection};
19use crate::chord::Chord;
20use crate::clef::{Clef, ClefKind};
21use crate::defaults::{FloatType, IntegerType};
22use crate::duration::{Duration, DurationType, Tuplet};
23use crate::dynamics::Dynamic;
24use crate::error::{Error, Position, Result};
25use crate::expressions::TextExpression;
26use crate::instrument::Instrument;
27use crate::interval::Interval;
28use crate::key::KeySignature;
29use crate::metadata::{Metadata, MetadataValue};
30use crate::notation::{Placement as Side, Tie, TieType};
31use crate::note::Note;
32use crate::percussion::Unpitched;
33use crate::pitch::Pitch;
34use crate::pitch::accidental::Accidental;
35use crate::repeat::{RepeatExpression, RepeatExpressionKind};
36use crate::rest::Rest;
37use crate::spanner::Spanner;
38use crate::stream::{Stream, StreamElement, StreamKind};
39use crate::tempo::MetronomeMark;
40
41use placement::{Placement, Placing};
42
43fn error(message: impl Into<String>) -> Error {
44    Error::noteworthy(message.into())
45}
46
47/// Reads the text of a NoteWorthy Composer `.nwctxt` file into a score, as
48/// music21's `converter.parse` reads one.
49///
50/// Each staff is a part, every one standing at the start of the score. Its
51/// notes, chords and rests are spelled from their places on the staff under
52/// the clef in force, with the key signature's accidentals and any written
53/// earlier in the measure; slurs, ties, triplets, grace notes and the
54/// staff's first verse of lyrics are read, as are barlines and repeats,
55/// endings, clefs, keys, meters, tempos, dynamics, words, *Coda*, *Segno*,
56/// *Fine* and the jumps to them, each staff's instrument by its MIDI program,
57/// and the song's title. A percussion clef's notes are unpitched strokes.
58///
59/// music21's own habits are kept: its first two measures are both numbered
60/// nought, a staff's name keeps the quotation marks the file writes round
61/// it, words are placed above the staff where the file puts them below, and
62/// a chord with a rest beside it puts what the measure holds so far into a
63/// voice. What music21 passes over -- fonts, page setup, crescendo and
64/// diminuendo marks, performance styles, a second verse -- is passed over.
65///
66/// ```
67/// use music21::noteworthy::from_noteworthy;
68///
69/// let score = from_noteworthy(
70///     "!NoteWorthyComposer(2.0)\n|AddStaff|\n|Clef|Type:Bass\n|TimeSig|Signature:4/4\n|Note|Dur:Whole|Pos:1\n",
71/// )?;
72/// let pitches = score.pitches();
73/// assert_eq!(pitches[0].name_with_octave(), "E3");
74/// # Ok::<(), music21::Error>(())
75/// ```
76///
77/// # Errors
78///
79/// A file with no staff, a line music21 cannot read -- an attribute with no
80/// value, a clef, barline style, flow mark or note length it does not know,
81/// an octave shift on an alto or tenor clef -- or a number that is not one.
82pub fn from_noteworthy(text: &str) -> Result<Stream> {
83    from_lines(text.lines(), true)
84}
85
86/// [`from_noteworthy`] over lines already split, as music21's `parseList`
87/// takes them. What goes wrong on a line says which where the lines are
88/// `numbered`, the lines of a file rather than ones made from a binary one.
89fn from_lines<'a>(lines: impl IntoIterator<Item = &'a str>, numbered: bool) -> Result<Stream> {
90    let mut reader = Reader::new();
91    for (index, line) in lines.into_iter().enumerate() {
92        let here = |error: Error| {
93            if numbered {
94                return error.placed(|| Position::line(index + 1));
95            }
96            error
97        };
98        let line = line.trim_end();
99        if !line.starts_with('|') {
100            continue;
101        }
102        let sections: Vec<&str> = line.split('|').collect();
103        let command = sections.get(1).copied().unwrap_or("");
104        let mut attributes = Attributes::default();
105        for attribute in sections.iter().skip(2) {
106            match attribute.split_once(':') {
107                Some((name, value)) => attributes.add(
108                    name,
109                    value,
110                    command == "Chord" && matches!(name, "Dur" | "Pos"),
111                ),
112                None if attribute.trim().is_empty() => {}
113                None => {
114                    return Err(here(error(format!(
115                        "Cannot unpack value from {attribute} in {line}"
116                    ))));
117                }
118            }
119        }
120        reader.command(command, &attributes).map_err(here)?;
121    }
122    reader.finish()
123}
124
125/// A line's attributes, in the order written; `Dur` and `Pos` of a chord
126/// keep every value given.
127#[derive(Default)]
128struct Attributes {
129    values: Vec<(String, Vec<String>)>,
130}
131
132impl Attributes {
133    fn add(&mut self, name: &str, value: &str, listed: bool) {
134        match self.values.iter_mut().find(|(known, _)| known == name) {
135            Some((_, values)) if listed => values.push(value.to_string()),
136            Some((_, values)) => *values = vec![value.to_string()],
137            None => self
138                .values
139                .push((name.to_string(), vec![value.to_string()])),
140        }
141    }
142
143    fn get(&self, name: &str) -> Option<&str> {
144        self.values
145            .iter()
146            .find(|(known, _)| known == name)
147            .and_then(|(_, values)| values.last())
148            .map(String::as_str)
149    }
150
151    fn list(&self, name: &str) -> Vec<String> {
152        self.values
153            .iter()
154            .find(|(known, _)| known == name)
155            .map(|(_, values)| values.clone())
156            .unwrap_or_default()
157    }
158
159    fn required(&self, name: &str) -> Result<&str> {
160        self.get(name)
161            .ok_or_else(|| error(format!("a line with no {name}")))
162    }
163}
164
165/// The clef notes are read under, as music21's reader names it.
166#[derive(Clone, Copy, PartialEq, Eq)]
167enum ClefState {
168    Treble,
169    TrebleDown,
170    TrebleUp,
171    Bass,
172    BassDown,
173    BassUp,
174    Alto,
175    Tenor,
176    Percussion,
177}
178
179impl ClefState {
180    /// The clef music21's reader keeps as `currentClef`: `TREBLE`,
181    /// `TREBLE8dw`, `TREBLE8up`, `BASS`, `BASS8dw`, `BASS8up`, `ALTO`,
182    /// `TENOR` or `PERCUSSION`; anything else is read as treble.
183    fn named(name: &str) -> Self {
184        match name {
185            "TREBLE8dw" => Self::TrebleDown,
186            "TREBLE8up" => Self::TrebleUp,
187            "BASS" => Self::Bass,
188            "PERCUSSION" => Self::Percussion,
189            "BASS8dw" => Self::BassDown,
190            "BASS8up" => Self::BassUp,
191            "ALTO" => Self::Alto,
192            "TENOR" => Self::Tenor,
193            _ => Self::Treble,
194        }
195    }
196
197    /// The name music21's reader keeps for this clef as `currentClef`.
198    fn music21_name(self) -> &'static str {
199        match self {
200            Self::Treble => "TREBLE",
201            Self::TrebleDown => "TREBLE8dw",
202            Self::TrebleUp => "TREBLE8up",
203            Self::Bass => "BASS",
204            Self::BassDown => "BASS8dw",
205            Self::BassUp => "BASS8up",
206            Self::Alto => "ALTO",
207            Self::Tenor => "TENOR",
208            Self::Percussion => "PERCUSSION",
209        }
210    }
211
212    /// The step and octave of a staff position under this clef.
213    fn step_and_octave(self, position: IntegerType) -> (char, IntegerType) {
214        let (octave, lowest, steps) = self.table();
215        // Wider than the position, so one as far off the staff as an
216        // integer goes neither overflows nor panics.
217        let from_lowest = i64::from(position) - i64::from(lowest);
218        let step = steps[usize::try_from(from_lowest.rem_euclid(7)).unwrap_or(0)];
219        let octave = i64::from(octave) + from_lowest.div_euclid(7);
220        let octave = IntegerType::try_from(octave).unwrap_or(if octave < 0 {
221            IntegerType::MIN
222        } else {
223            IntegerType::MAX
224        });
225        (step, octave)
226    }
227
228    /// music21's `getStepAndOctaveFromPosition` tables: the octave of the
229    /// lowest of seven positions, that position, and the steps from it.
230    fn table(self) -> (IntegerType, IntegerType, [char; 7]) {
231        const TREBLE: [char; 7] = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
232        match self {
233            Self::TrebleDown => (4, 1, TREBLE),
234            Self::TrebleUp => (6, 1, TREBLE),
235            Self::Bass | Self::Percussion => (3, -1, TREBLE),
236            Self::BassDown => (2, -1, TREBLE),
237            Self::BassUp => (4, -1, TREBLE),
238            Self::Alto => (4, 0, TREBLE),
239            Self::Tenor => (3, -5, TREBLE),
240            Self::Treble => (5, 1, TREBLE),
241        }
242    }
243}
244
245/// The positions of a staff under a clef, as music21's
246/// `noteworthy.dictionaries` lays them out: the octave of the lowest of
247/// seven positions, that position, and the steps from it. The clef is
248/// named as music21's reader keeps it (`TREBLE`, `BASS8dw`, `ALTO`, ...).
249#[must_use]
250pub fn staff_positions(clef: &str) -> (IntegerType, IntegerType, [char; 7]) {
251    ClefState::named(clef).table()
252}
253
254/// The step and octave of a staff position under a clef: music21's
255/// `getStepAndOctaveFromPosition`. Position 1 under the treble clef is
256/// C5, and each position up or down is a step.
257#[must_use]
258pub fn step_and_octave(clef: &str, position: IntegerType) -> (char, IntegerType) {
259    ClefState::named(clef).step_and_octave(position)
260}
261
262/// Something standing in a measure or a voice while the file is read.
263struct Item {
264    offset: FloatType,
265    content: Content,
266    /// The order it was put where it stands.
267    inserted: usize,
268}
269
270enum Content {
271    /// An element, with its number among the notes, chords and rests read
272    /// where it is one.
273    Element(Box<StreamElement>, Option<usize>),
274    Voice(VoiceBuilt),
275}
276
277struct VoiceBuilt {
278    id: usize,
279    items: Vec<Item>,
280}
281
282fn is_general_note(element: &StreamElement) -> bool {
283    matches!(
284        element,
285        StreamElement::Note(_)
286            | StreamElement::Chord(_)
287            | StreamElement::Rest(_)
288            | StreamElement::Unpitched(_)
289    )
290}
291
292/// The end of the last thing in a list: music21's `highestTime`.
293fn highest_time(items: &[Item]) -> FloatType {
294    items
295        .iter()
296        .map(|item| {
297            item.offset
298                + match &item.content {
299                    Content::Element(element, _) => element.quarter_length(),
300                    Content::Voice(voice) => highest_time(&voice.items),
301                }
302        })
303        .fold(0.0, FloatType::max)
304}
305
306struct MeasureBuilt {
307    /// Which measure of the file this is, for the slurs and ties that
308    /// remember where they were left open.
309    id: usize,
310    number: IntegerType,
311    left: Option<Barline>,
312    right: Option<Barline>,
313    items: Vec<Item>,
314    inserted: usize,
315}
316
317impl MeasureBuilt {
318    fn new(number: IntegerType, id: usize) -> Self {
319        Self {
320            id,
321            number,
322            left: None,
323            right: None,
324            items: Vec::new(),
325            inserted: 0,
326        }
327    }
328
329    fn insert(&mut self, offset: FloatType, content: Content) {
330        self.items.push(Item {
331            offset,
332            content,
333            inserted: self.inserted,
334        });
335        self.inserted += 1;
336    }
337
338    /// music21's truth of a stream: whether it holds anything, barlines
339    /// included.
340    fn holds_anything(&self) -> bool {
341        !self.items.is_empty() || self.left.is_some() || self.right.is_some()
342    }
343
344    /// The places of the voices, in music21's order.
345    fn voices(&self) -> Vec<usize> {
346        sorted_places(&self.items)
347            .into_iter()
348            .filter(|place| matches!(self.items[*place].content, Content::Voice(_)))
349            .collect()
350    }
351}
352
353/// An element being placed, with its number among the notes, chords and
354/// rests read.
355type Placed = (StreamElement, Option<usize>);
356
357/// The measure being read and the part's slurs, as the placing
358/// algorithm sees them: a measure is its number, a voice its place among
359/// the measure's items, a note its number.
360struct Built<'a> {
361    measure: &'a mut MeasureBuilt,
362    slurs: Option<&'a mut Vec<(usize, usize)>>,
363}
364
365impl Placing for Built<'_> {
366    type Measure = usize;
367    type Voice = usize;
368    type Element = Placed;
369    type Handle = usize;
370    type Error = Error;
371
372    fn copy_measure(&self, measure: &usize) -> usize {
373        *measure
374    }
375
376    fn copy_handle(&self, handle: &usize) -> usize {
377        *handle
378    }
379
380    fn same_measure(&self, first: &usize, second: &usize) -> bool {
381        first == second
382    }
383
384    fn same_handle(&self, first: &usize, second: &usize) -> bool {
385        first == second
386    }
387
388    fn handle(&self, element: &Placed) -> Result<usize> {
389        element
390            .1
391            .ok_or_else(|| error("a note placed with no number"))
392    }
393
394    fn highest_time(&self, _measure: &usize) -> Result<FloatType> {
395        Ok(highest_time(&self.measure.items))
396    }
397
398    fn length(&self, element: &Placed) -> Result<FloatType> {
399        Ok(element.0.quarter_length())
400    }
401
402    fn voices(&self, _measure: &usize) -> Result<Vec<usize>> {
403        Ok(self.measure.voices())
404    }
405
406    fn voice_end(&self, voice: &usize) -> Result<FloatType> {
407        Ok(voice_length(&self.measure.items[*voice]))
408    }
409
410    fn gather_voice(&mut self, _measure: &usize) -> Result<usize> {
411        let measure = &mut *self.measure;
412        let notes: Vec<usize> = sorted_places(&measure.items)
413            .into_iter()
414            .filter(|place| {
415                matches!(&measure.items[*place].content,
416                    Content::Element(element, _) if is_general_note(element))
417            })
418            .collect();
419        let mut voice = VoiceBuilt {
420            id: 0,
421            items: Vec::new(),
422        };
423        for place in &notes {
424            let item = &measure.items[*place];
425            if let Content::Element(element, serial) = &item.content {
426                let inserted = voice.items.len();
427                voice.items.push(Item {
428                    offset: item.offset,
429                    content: Content::Element(element.clone(), *serial),
430                    inserted,
431                });
432            }
433        }
434        let mut index = 0;
435        measure.items.retain(|_| {
436            let keep = !notes.contains(&index);
437            index += 1;
438            keep
439        });
440        measure.insert(0.0, Content::Voice(voice));
441        Ok(measure.items.len() - 1)
442    }
443
444    fn new_voice(&mut self, _measure: &usize, id: usize) -> Result<usize> {
445        self.measure.insert(
446            0.0,
447            Content::Voice(VoiceBuilt {
448                id,
449                items: Vec::new(),
450            }),
451        );
452        Ok(self.measure.items.len() - 1)
453    }
454
455    fn insert(&mut self, _measure: &usize, offset: FloatType, element: Placed) -> Result<()> {
456        let (element, serial) = element;
457        self.measure
458            .insert(offset, Content::Element(Box::new(element), serial));
459        Ok(())
460    }
461
462    fn insert_in(&mut self, voice: &usize, offset: FloatType, element: Placed) -> Result<()> {
463        let (element, serial) = element;
464        if let Content::Voice(voice) = &mut self.measure.items[*voice].content {
465            let inserted = voice.items.len();
466            voice.items.push(Item {
467                offset,
468                content: Content::Element(Box::new(element), serial),
469                inserted,
470            });
471        }
472        Ok(())
473    }
474
475    fn set_ties(&mut self, element: &mut Placed, ties: &[Option<TieType>]) -> Result<()> {
476        let notes: Vec<&mut Note> = match &mut element.0 {
477            StreamElement::Note(note) => vec![note],
478            StreamElement::Unpitched(stroke) => vec![stroke.written_mut()],
479            StreamElement::Chord(chord) => chord.notes_mut().iter_mut().collect(),
480            _ => Vec::new(),
481        };
482        for (note, tie) in notes.into_iter().zip(ties) {
483            if let Some(kind) = tie {
484                note.set_tie(Some(Tie::new(*kind)));
485            }
486        }
487        Ok(())
488    }
489
490    fn slur(&mut self, _measure: &usize, start: &usize, end: &usize) -> Result<()> {
491        let slurs = self
492            .slurs
493            .as_mut()
494            .ok_or_else(|| error("a slur before the first staff"))?;
495        slurs.push((*start, *end));
496        Ok(())
497    }
498}
499
500fn voice_length(item: &Item) -> FloatType {
501    match &item.content {
502        Content::Voice(voice) => highest_time(&voice.items),
503        Content::Element(element, _) => element.quarter_length(),
504    }
505}
506
507/// The places of a list's items in music21's order: offset, then class,
508/// grace notes ahead of the rest, then the order they were put there.
509fn sorted_places(items: &[Item]) -> Vec<usize> {
510    let mut places: Vec<usize> = (0..items.len()).collect();
511    places.sort_by(|left, right| {
512        let key = |item: &Item| {
513            let (order, grace) = match &item.content {
514                Content::Element(element, _) => (
515                    element.class_sort_order(),
516                    element.duration().is_some_and(Duration::is_grace),
517                ),
518                Content::Voice(_) => (5, false),
519            };
520            (item.offset, order, !grace, item.inserted)
521        };
522        let (left, right) = (key(&items[*left]), key(&items[*right]));
523        left.0
524            .total_cmp(&right.0)
525            .then(left.1.cmp(&right.1))
526            .then(left.2.cmp(&right.2))
527            .then(left.3.cmp(&right.3))
528    });
529    places
530}
531
532/// What a part holds while it is read: its measures and instruments in the
533/// order they were appended, each where the part ended at the time.
534enum PartItem {
535    Measure(MeasureBuilt),
536    Instrument(Box<Instrument>),
537}
538
539struct PartBuilt {
540    name: Option<String>,
541    items: Vec<(FloatType, PartItem)>,
542    /// Slurs, by the numbers of the notes they join.
543    slurs: Vec<(usize, usize)>,
544}
545
546impl PartBuilt {
547    fn measures(&self) -> usize {
548        self.items
549            .iter()
550            .filter(|(_, item)| matches!(item, PartItem::Measure(_)))
551            .count()
552    }
553
554    fn end(&self) -> FloatType {
555        self.items
556            .iter()
557            .map(|(offset, item)| {
558                offset
559                    + match item {
560                        PartItem::Measure(measure) => highest_time(&measure.items),
561                        PartItem::Instrument(_) => 0.0,
562                    }
563            })
564            .fold(0.0, FloatType::max)
565    }
566
567    fn append(&mut self, item: PartItem) {
568        let at = self.end();
569        self.items.push((at, item));
570    }
571}
572
573struct Reader {
574    parts: Vec<PartBuilt>,
575    part: Option<PartBuilt>,
576    measure: MeasureBuilt,
577    measure_number: IntegerType,
578    ending: u32,
579    /// The measures an ending spans so far, the one being read included.
580    /// music21 keeps the list from one staff to the next, so an ending left
581    /// open at the end of a staff goes on into the next.
582    repeated: Vec<Place>,
583    /// Endings, as the measures they span and the ending's number.
584    endings: Vec<(Vec<Place>, u32)>,
585    metadata: Option<Metadata>,
586    clef: ClefState,
587    key: KeySignature,
588    /// How many measures have been begun, which numbers each.
589    measures_begun: usize,
590    /// Where the next object goes, and the slurs and ties left open, by
591    /// measure number and note number.
592    placement: Placement<usize, usize>,
593    lyric_position: usize,
594    lyrics: Vec<String>,
595    /// Accidentals written so far in the measure, by the step and octave
596    /// they were written on.
597    accidentals: Vec<(String, &'static str)>,
598    /// How many notes, chords and rests have been read.
599    serials: usize,
600}
601
602impl Reader {
603    fn new() -> Self {
604        Self {
605            parts: Vec::new(),
606            part: None,
607            measure: MeasureBuilt::new(0, 0),
608            measure_number: 0,
609            ending: 1,
610            repeated: Vec::new(),
611            endings: Vec::new(),
612            metadata: None,
613            clef: ClefState::Treble,
614            key: KeySignature::new(0),
615            measures_begun: 1,
616            placement: Placement::default(),
617            lyric_position: 0,
618            lyrics: Vec::new(),
619            accidentals: Vec::new(),
620            serials: 0,
621        }
622    }
623
624    fn part(&mut self) -> Result<&mut PartBuilt> {
625        self.part
626            .as_mut()
627            .ok_or_else(|| error("an object before the first staff"))
628    }
629
630    fn command(&mut self, command: &str, attributes: &Attributes) -> Result<()> {
631        match command {
632            "AddStaff" => self.add_staff(attributes),
633            "Bar" => self.bar(attributes)?,
634            "Chord" => {
635                self.chord(attributes)?;
636                self.lyric_position += 1;
637            }
638            "Clef" => self.clef(attributes)?,
639            "Dynamic" => {
640                if let Some(style) = attributes.get("Style") {
641                    self.at_position(StreamElement::Dynamic(Dynamic::new(style)))?;
642                }
643            }
644            "Ending" => self.ending(attributes)?,
645            "Flow" => self.flow(attributes)?,
646            "Key" => self.key(attributes)?,
647            "Lyric1" => self.lyrics = lyrics(attributes.required("Text")?),
648            "Note" => {
649                self.note(attributes)?;
650                self.lyric_position += 1;
651            }
652            "RestChord" => {
653                self.rest_chord(attributes)?;
654                self.lyric_position += 1;
655            }
656            "Rest" => {
657                let written = attributes.required("Dur")?;
658                let mut rest = Rest::new(Duration::quarter());
659                rest.set_duration(duration_of(written)?);
660                let serial = self.serial();
661                self.simultaneous(vec![(
662                    (StreamElement::Rest(rest), Some(serial)),
663                    slurred(written),
664                )])?;
665            }
666            "SongInfo" => {
667                let mut metadata = Metadata::new();
668                if let Some(title) = attributes.get("Title") {
669                    metadata.set("title", vec![MetadataValue::new(title)]);
670                }
671                self.metadata = Some(metadata);
672            }
673            "StaffInstrument" => self.staff_instrument(attributes)?,
674            "Tempo" => {
675                let tempo: IntegerType = number(attributes.required("Tempo")?)?;
676                self.measure.insert(
677                    0.0,
678                    Content::Element(
679                        Box::new(StreamElement::MetronomeMark(MetronomeMark::new(
680                            FloatType::from(tempo),
681                        ))),
682                        None,
683                    ),
684                );
685            }
686            "Text" => {
687                let mut words = TextExpression::new(attributes.required("Text")?);
688                let position: IntegerType = number(attributes.required("Pos")?)?;
689                words.set_placement(Some(if position < 0 {
690                    Side::Above
691                } else {
692                    Side::Below
693                }));
694                self.at_position(StreamElement::TextExpression(words))?;
695            }
696            "TimeSig" => {
697                let signature = meter_ratio(attributes.required("Signature")?);
698                let meter = crate::meter::TimeSignature::from_ratio_string(signature)?;
699                self.at_position(StreamElement::TimeSignature(meter))?;
700            }
701            _ => {}
702        }
703        Ok(())
704    }
705
706    /// Where the measure being read will stand once it is closed.
707    fn place(&self) -> Result<Place> {
708        let part = self
709            .part
710            .as_ref()
711            .ok_or_else(|| error("an object before the first staff"))?;
712        Ok(Place {
713            part: self.parts.len(),
714            measure: part.measures(),
715        })
716    }
717
718    fn serial(&mut self) -> usize {
719        self.serials += 1;
720        self.serials - 1
721    }
722
723    /// A measure to read into next, numbered `number`.
724    fn begun(&mut self, number: IntegerType) -> MeasureBuilt {
725        self.measures_begun += 1;
726        MeasureBuilt::new(number, self.measures_begun - 1)
727    }
728
729    /// The measure being read and the part's slurs, as [`Placing`] asks
730    /// for them.
731    fn built(&mut self) -> (Built<'_>, &mut Placement<usize, usize>) {
732        let slurs = self.part.as_mut().map(|part| &mut part.slurs);
733        (
734            Built {
735                measure: &mut self.measure,
736                slurs,
737            },
738            &mut self.placement,
739        )
740    }
741
742    /// music21's `insertAtPosition`: a clef, key, dynamic or other mark
743    /// where the next note goes.
744    fn at_position(&mut self, element: StreamElement) -> Result<()> {
745        let id = self.measure.id;
746        let (mut built, placement) = self.built();
747        placement.mark(&mut built, &id, (element, None))
748    }
749
750    fn add_staff(&mut self, attributes: &Attributes) {
751        self.new_part();
752        self.placement.new_staff();
753        self.key = KeySignature::new(0);
754        self.accidentals.clear();
755        self.lyrics.clear();
756        self.lyric_position = 0;
757        if let Some(part) = &mut self.part {
758            part.name = attributes.get("Name").map(str::to_string);
759        }
760    }
761
762    /// music21's `createPart`: the part being read is closed with the
763    /// measure it is in, however empty, and a new one begun.
764    fn new_part(&mut self) {
765        let fresh = self.begun(0);
766        let measure = std::mem::replace(&mut self.measure, fresh);
767        if let Some(mut part) = self.part.take() {
768            part.append(PartItem::Measure(measure));
769            self.parts.push(part);
770        }
771        self.part = Some(PartBuilt {
772            name: None,
773            items: Vec::new(),
774            slurs: Vec::new(),
775        });
776        self.measure_number = 0;
777    }
778
779    /// Closes the measure being read and begins another numbered `number`.
780    fn close_measure(&mut self, number: IntegerType) -> Result<()> {
781        let fresh = self.begun(number);
782        let measure = std::mem::replace(&mut self.measure, fresh);
783        self.part()?.append(PartItem::Measure(measure));
784        Ok(())
785    }
786
787    fn bar(&mut self, attributes: &Attributes) -> Result<()> {
788        self.accidentals.clear();
789        // A tie running to the barline goes on into the next measure; any
790        // other open tie is dropped.
791        let id = self.measure.id;
792        let (built, placement) = self.built();
793        placement.barline(&built, &id)?;
794        let Some(style) = attributes.get("Style") else {
795            self.close_measure(self.measure_number)?;
796            if !self.repeated.is_empty() {
797                let next = self.place()?;
798                self.repeated.push(next);
799            }
800            self.measure_number += 1;
801            return Ok(());
802        };
803        if !self.repeated.is_empty() {
804            let spanned = std::mem::take(&mut self.repeated);
805            self.endings.push((spanned, self.ending));
806        }
807        match bar_style(style)? {
808            BarStyle::RepeatOpen => {
809                self.close_measure(0)?;
810                self.measure.left = Some(Barline::repeat(RepeatDirection::Start, None));
811            }
812            BarStyle::RepeatClose => {
813                self.measure.right = Some(Barline::repeat(RepeatDirection::End, None));
814                self.close_measure(0)?;
815            }
816            BarStyle::Closing(kind) => {
817                self.measure.right = Some(Barline::new(kind));
818                self.close_measure(0)?;
819            }
820        }
821        self.measure.number = self.measure_number;
822        self.measure_number += 1;
823        Ok(())
824    }
825
826    fn ending(&mut self, attributes: &Attributes) -> Result<()> {
827        let endings = attributes.required("Endings")?;
828        if self.measure.left.is_none() {
829            self.measure.left = Some(Barline::new(BarlineType::Regular));
830        }
831        self.repeated = vec![self.place()?];
832        let first = endings.split(',').next().unwrap_or("");
833        self.ending = number(first)?;
834        Ok(())
835    }
836
837    fn flow(&mut self, attributes: &Attributes) -> Result<()> {
838        let kind = flow_kind(attributes.required("Style")?)?;
839        self.at_position(StreamElement::RepeatExpression(RepeatExpression::new(kind)))?;
840        Ok(())
841    }
842
843    fn clef(&mut self, attributes: &Attributes) -> Result<()> {
844        let (clef, state) = clef_of(attributes.required("Type")?, attributes.get("OctaveShift"))?;
845        self.at_position(StreamElement::Clef(clef))?;
846        self.clef = state;
847        Ok(())
848    }
849
850    fn key(&mut self, attributes: &Attributes) -> Result<()> {
851        self.key = KeySignature::new(key_sharps(attributes.required("Signature")?));
852        self.at_position(StreamElement::KeySignature(self.key.clone()))?;
853        Ok(())
854    }
855
856    fn staff_instrument(&mut self, attributes: &Attributes) -> Result<()> {
857        let patch: IntegerType = attributes.get("Patch").map_or(Ok(0), number)?;
858        let program = u8::try_from(patch).map_err(|_| error(format!("no MIDI program {patch}")))?;
859        let mut instrument = Instrument::from_midi_program(program)?;
860        let transposition: IntegerType = attributes.get("Trans").map_or(Ok(0), number)?;
861        instrument.set_transposition(Some(Interval::from_semitones(transposition)?));
862        self.part()?
863            .append(PartItem::Instrument(Box::new(instrument)));
864        Ok(())
865    }
866
867    /// music21's `setTieFromPitchInfo`: the ties of an element about to go
868    /// at the current position, from its `Pos` value, each note's staff
869    /// step under the clef in force and whether it ends `^`.
870    fn tied(&mut self, element: &mut Placed, positions: &str) -> Result<()> {
871        let steps: Vec<((char, IntegerType), bool)> = positions
872            .split(',')
873            .filter_map(|position| {
874                let place = first_number(position)?;
875                Some((self.clef.step_and_octave(place), position.ends_with('^')))
876            })
877            .collect();
878        let id = self.measure.id;
879        let (mut built, placement) = self.built();
880        placement.tie(&mut built, &id, element, &steps)
881    }
882
883    /// music21's `getPitchFromPositionInfo`: a pitch from one `Pos` value,
884    /// its tie and stem marks dropped.
885    fn pitch(&mut self, position: &str) -> Result<Pitch> {
886        let position = position
887            .trim_end_matches('^')
888            .trim_end_matches('x')
889            .trim_end_matches('X')
890            .trim_end_matches('z');
891        let (accidental, place) = match position.chars().next() {
892            Some('n') => (Some("natural"), &position[1..]),
893            Some('b') => (Some("flat"), &position[1..]),
894            Some('#') => (Some("sharp"), &position[1..]),
895            Some('x') => (Some("double-sharp"), &position[1..]),
896            Some('v') => (Some("double-flat"), &position[1..]),
897            _ => (None, position),
898        };
899        let place: IntegerType = number(place)?;
900        let (mut octave, lowest, steps) = self.clef.table();
901        let mut place = place;
902        while place < lowest || place > lowest + 6 {
903            if place < lowest {
904                place += 7;
905                octave -= 1;
906            }
907            if place > lowest + 6 {
908                place -= 7;
909                octave += 1;
910            }
911        }
912        let step = steps[usize::try_from(place - lowest).unwrap_or(0)];
913        let name = format!("{step}{octave}");
914        let mut pitch = Pitch::from_name(&name)?;
915        if let Some(accidental) = accidental {
916            pitch.set_accidental(Accidental::new(accidental)?);
917            self.accidentals.retain(|(written, _)| written != &name);
918            self.accidentals.push((name, accidental));
919        } else if let Some((_, accidental)) = self
920            .accidentals
921            .iter()
922            .find(|(written, _)| written == &name)
923        {
924            pitch.set_accidental(Accidental::new(*accidental)?);
925        } else if let Some(accidental) = self.key.accidental_by_step(step)? {
926            pitch.set_accidental(accidental);
927        }
928        Ok(pitch)
929    }
930
931    fn lyric(&self) -> Option<&str> {
932        self.lyrics.get(self.lyric_position).map(String::as_str)
933    }
934
935    fn note(&mut self, attributes: &Attributes) -> Result<()> {
936        let written = attributes.required("Dur")?;
937        let position = attributes.required("Pos")?;
938        let pitch = self.pitch(position)?;
939        let duration = duration_of(written)?;
940        let serial = self.serial();
941        let lyric = self.lyric().map(str::to_string);
942        let mut note = Note::from_pitch(pitch.clone()).with_duration(duration.clone());
943        if let Some(lyric) = lyric {
944            note.add_lyric(&lyric, None, false)?;
945        }
946        let element = if self.clef == ClefState::Percussion {
947            let octave = pitch.octave().unwrap_or(4);
948            let step = pitch.step().as_char();
949            let mut stroke = Unpitched::displayed_at(step, octave)?;
950            let written_note = stroke.written_mut();
951            written_note.set_duration(duration);
952            *written_note.lyrics_mut() = note.lyrics().to_vec();
953            StreamElement::Unpitched(stroke)
954        } else {
955            StreamElement::Note(note)
956        };
957        let mut element = (element, Some(serial));
958        self.tied(&mut element, position)?;
959        self.simultaneous(vec![(element, slurred(written))])
960    }
961
962    /// music21's `translateChord`: a chord for each `Dur` and the `Pos`
963    /// beside it, and one more for `Dur2` and `Pos2`, all starting together.
964    fn chord(&mut self, attributes: &Attributes) -> Result<()> {
965        attributes.required("Dur")?;
966        attributes.required("Pos")?;
967        let mut groups: Vec<(String, String)> = attributes
968            .list("Dur")
969            .into_iter()
970            .zip(attributes.list("Pos"))
971            .collect();
972        if let Some(written) = attributes.get("Dur2") {
973            groups.push((
974                written.to_string(),
975                attributes.required("Pos2")?.to_string(),
976            ));
977        }
978        let mut chords = Vec::new();
979        for (written, position) in &groups {
980            chords.push(self.chord_of(written, position)?);
981        }
982        self.with_lyric(&mut chords[0].0.0)?;
983        self.simultaneous(chords)
984    }
985
986    /// music21's `translateRestChord`: the chord of `Dur2` and `Pos2`, and a
987    /// rest of `Dur` sounding with it.
988    fn rest_chord(&mut self, attributes: &Attributes) -> Result<()> {
989        let mut chord =
990            self.chord_of(attributes.required("Dur2")?, attributes.required("Pos2")?)?;
991        let written = attributes.required("Dur")?;
992        let mut rest = Rest::new(Duration::quarter());
993        rest.set_duration(duration_of(written)?);
994        let serial = self.serial();
995        self.with_lyric(&mut chord.0.0)?;
996        self.simultaneous(vec![
997            chord,
998            ((StreamElement::Rest(rest), Some(serial)), slurred(written)),
999        ])
1000    }
1001
1002    /// music21's `createChord`: one group of a chord's notes.
1003    fn chord_of(&mut self, written: &str, position: &str) -> Result<(Placed, bool)> {
1004        let duration = duration_of(written)?;
1005        let serial = self.serial();
1006        let mut pitches = Vec::new();
1007        for one in position.split(',') {
1008            pitches.push(self.pitch(one)?);
1009        }
1010        let notes: Vec<Note> = pitches.into_iter().map(Note::from_pitch).collect();
1011        let chord = Chord::new(notes)?.with_duration(duration);
1012        let mut element = (StreamElement::Chord(chord), Some(serial));
1013        self.tied(&mut element, position)?;
1014        Ok((element, slurred(written)))
1015    }
1016
1017    /// music21's `addCurrentLyric`: the syllable sung now, on a chord.
1018    fn with_lyric(&self, element: &mut StreamElement) -> Result<()> {
1019        if let (Some(lyric), StreamElement::Chord(chord)) = (self.lyric(), element) {
1020            chord.add_lyric(lyric, None, false)?;
1021        }
1022        Ok(())
1023    }
1024
1025    /// music21's `appendSimultaneous`: notes, chords or rests starting
1026    /// together at the current position, each with whether it is slurred.
1027    fn simultaneous(&mut self, elements: Vec<(Placed, bool)>) -> Result<()> {
1028        let id = self.measure.id;
1029        let (mut built, placement) = self.built();
1030        placement.place(&mut built, &id, elements)
1031    }
1032
1033    fn finish(mut self) -> Result<Stream> {
1034        let fresh = self.begun(0);
1035        let measure = std::mem::replace(&mut self.measure, fresh);
1036        let mut part = self
1037            .part
1038            .take()
1039            .ok_or_else(|| error("a file with no staff"))?;
1040        if measure.holds_anything() {
1041            part.append(PartItem::Measure(measure));
1042        }
1043        self.parts.push(part);
1044
1045        let mut score = Stream::with_kind(StreamKind::Score);
1046        if let Some(metadata) = self.metadata {
1047            score.set_metadata(Some(metadata));
1048        }
1049        for (index, part) in self.parts.into_iter().enumerate() {
1050            score.insert(0.0, assemble(part, index, &self.endings));
1051        }
1052        Ok(score)
1053    }
1054}
1055
1056/// A value rebuilt with dots, as music21's `dots` setter rebuilds its one
1057/// component: the grace and tuplets it had kept.
1058fn with_dots(duration: &Duration, dots: u32) -> Duration {
1059    let Some((value, _)) = duration.type_and_dots() else {
1060        return duration.clone();
1061    };
1062    let mut dotted = Duration::from_type_with_dots(value, dots);
1063    dotted.set_tuplets(duration.tuplets());
1064    dotted.set_grace(duration.grace().cloned());
1065    dotted.set_expression_is_inferred(duration.expression_is_inferred());
1066    dotted
1067}
1068
1069/// music21's `createClef`: the clef a `Type` and `OctaveShift` name, and
1070/// the name music21's reader keeps for it as `currentClef`.
1071///
1072/// # Errors
1073///
1074/// An octave shift or clef music21 does not know, or a shifted alto or
1075/// tenor clef.
1076pub fn clef_named(kind: &str, shift: Option<&str>) -> Result<(Clef, &'static str)> {
1077    let (clef, state) = clef_of(kind, shift)?;
1078    Ok((clef, state.music21_name()))
1079}
1080
1081fn clef_of(kind: &str, shift: Option<&str>) -> Result<(Clef, ClefState)> {
1082    let shift = match shift {
1083        None => 0,
1084        Some("Octave Down") => -1,
1085        Some("Octave Up") => 1,
1086        Some(other) => {
1087            return Err(error(format!(
1088                "Did not get a proper octave shift from {other}"
1089            )));
1090        }
1091    };
1092    let (clef, state) = match (kind, shift) {
1093        ("Treble", 0) => (ClefKind::TrebleClef, ClefState::Treble),
1094        ("Treble", -1) => (ClefKind::Treble8vbClef, ClefState::TrebleDown),
1095        ("Treble", _) => (ClefKind::Treble8vaClef, ClefState::TrebleUp),
1096        ("Bass", 0) => (ClefKind::BassClef, ClefState::Bass),
1097        ("Bass", -1) => (ClefKind::Bass8vbClef, ClefState::BassDown),
1098        ("Bass", _) => (ClefKind::Bass8vaClef, ClefState::BassUp),
1099        ("Alto", 0) => (ClefKind::AltoClef, ClefState::Alto),
1100        ("Alto", _) => return Err(error("cannot shift octaves on an alto clef")),
1101        ("Tenor", 0) => (ClefKind::TenorClef, ClefState::Tenor),
1102        ("Tenor", _) => return Err(error("cannot shift octaves on a tenor clef")),
1103        ("Percussion", _) => (ClefKind::PercussionClef, ClefState::Percussion),
1104        (other, _) => {
1105            return Err(error(format!(
1106                "Did not find a proper clef in type, {other}"
1107            )));
1108        }
1109    };
1110    let mut clef = Clef::of_kind(clef);
1111    if state == ClefState::Percussion {
1112        clef.set_line(Some(2));
1113    }
1114    Ok((clef, state))
1115}
1116
1117/// music21's `createKey`: sharps less flats in a `Signature` value.
1118#[must_use]
1119pub fn key_sharps(signature: &str) -> IntegerType {
1120    signature.chars().fold(0, |sharps, mark| match mark {
1121        '#' => sharps + 1,
1122        'b' => sharps - 1,
1123        _ => sharps,
1124    })
1125}
1126
1127/// music21's `createTimeSignature`: a `Signature` value as a ratio.
1128#[must_use]
1129pub fn meter_ratio(signature: &str) -> &str {
1130    match signature {
1131        "AllaBreve" => "2/2",
1132        "Common" => "4/4",
1133        other => other,
1134    }
1135}
1136
1137/// music21's `createOtherRepetitions`: the mark a flow `Style` names.
1138///
1139/// # Errors
1140///
1141/// A style music21 does not know.
1142pub fn flow_kind(style: &str) -> Result<RepeatExpressionKind> {
1143    match style {
1144        "DCalFine" => Ok(RepeatExpressionKind::DaCapoAlFine),
1145        "Coda" | "ToCoda" => Ok(RepeatExpressionKind::Coda),
1146        "Segno" => Ok(RepeatExpressionKind::Segno),
1147        "DSalCoda" => Ok(RepeatExpressionKind::DalSegnoAlCoda),
1148        "Fine" => Ok(RepeatExpressionKind::Fine),
1149        _ => Err(error(format!("Cannot get style from {style}"))),
1150    }
1151}
1152
1153/// What a barline `Style` does to the measure: music21's
1154/// `createBarlines`.
1155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1156pub enum BarStyle {
1157    /// The next measure opens with a start repeat.
1158    RepeatOpen,
1159    /// The measure closes with an end repeat.
1160    RepeatClose,
1161    /// The measure closes with a barline of this kind.
1162    Closing(BarlineType),
1163}
1164
1165/// The barline a `Style` names.
1166///
1167/// # Errors
1168///
1169/// A style music21 does not know.
1170pub fn bar_style(style: &str) -> Result<BarStyle> {
1171    match style {
1172        "MasterRepeatOpen" | "LocalRepeatOpen" => Ok(BarStyle::RepeatOpen),
1173        "MasterRepeatClose" | "LocalRepeatClose" => Ok(BarStyle::RepeatClose),
1174        "Double" => Ok(BarStyle::Closing(BarlineType::Double)),
1175        "SectionOpen" => Ok(BarStyle::Closing(BarlineType::HeavyLight)),
1176        "SectionClose" => Ok(BarStyle::Closing(BarlineType::Final)),
1177        other => Err(error(format!("cannot find a style {other} in our list"))),
1178    }
1179}
1180
1181/// music21's `setDurationForObject`: the length a `Dur` value gives, with
1182/// its dots, grace and triplet.
1183///
1184/// # Errors
1185///
1186/// A length music21 does not know.
1187pub fn duration_of(written: &str) -> Result<Duration> {
1188    let mut parts = written.split(',');
1189    let length = match parts.next().unwrap_or("") {
1190        "Whole" => 4.0,
1191        "Half" => 2.0,
1192        "4th" => 1.0,
1193        "8th" => 0.5,
1194        "16th" => 0.25,
1195        "32nd" => 0.125,
1196        "64th" => 0.0625,
1197        other => return Err(error(format!("no note length {other}"))),
1198    };
1199    let mut duration = Duration::new(length)?;
1200    for part in written.split(',') {
1201        match part {
1202            "Grace" => duration = duration.grace_duration(),
1203            "Dotted" => duration = with_dots(&duration, 1),
1204            "DblDotted" => duration = with_dots(&duration, 2),
1205            "Triplet" | "Triplet=First" | "Triplet=End" => {
1206                let value = duration
1207                    .type_and_dots()
1208                    .map_or(DurationType::Quarter, |(value, _)| value);
1209                duration.append_tuplet(Tuplet::new(3, 2, value, 0));
1210            }
1211            _ => {}
1212        }
1213    }
1214    Ok(duration)
1215}
1216
1217/// Whether a `Dur` value slurs the note to the next.
1218fn slurred(written: &str) -> bool {
1219    written.split(',').any(|part| part == "Slur")
1220}
1221
1222/// The staff position in a `Pos` value: its first whole number, as
1223/// music21 finds it with `-?\d+`.
1224#[must_use]
1225pub fn first_number(position: &str) -> Option<IntegerType> {
1226    let start = position.find(|c: char| c.is_ascii_digit())?;
1227    let negative = position[..start].ends_with('-');
1228    let digits: String = position[start..]
1229        .chars()
1230        .take_while(char::is_ascii_digit)
1231        .collect();
1232    let value: IntegerType = digits.parse().ok()?;
1233    Some(if negative { -value } else { value })
1234}
1235
1236/// The parts of `Dur` and `Pos` that are numbers, read as Python's `int`.
1237fn number<T: std::str::FromStr>(text: &str) -> Result<T> {
1238    text.trim()
1239        .parse()
1240        .map_err(|_| error(format!("{text} is not a number")))
1241}
1242
1243/// music21's `createLyrics`: a verse split into the syllables sung to each
1244/// note, a syllable after a hyphen written with one before it.
1245#[must_use]
1246pub fn lyrics(text: &str) -> Vec<String> {
1247    let text = text
1248        .trim_matches('"')
1249        .replace("\r\n", " ")
1250        .replace(['\r', '\n'], " ");
1251    let mut syllables = Vec::new();
1252    for word in text.split(' ') {
1253        let mut first = true;
1254        for part in word.split('-') {
1255            for piece in part.split('\n') {
1256                let syllable = if piece.is_empty() {
1257                    " - ".to_string()
1258                } else if first {
1259                    piece.to_string()
1260                } else {
1261                    format!(" -{piece}")
1262                };
1263                first = false;
1264                syllables.push(syllable);
1265            }
1266        }
1267    }
1268    syllables
1269}
1270
1271/// A measure by the part it is in and its number among that part's
1272/// measures, both counted from nought.
1273#[derive(Clone, Copy, PartialEq, Eq)]
1274struct Place {
1275    part: usize,
1276    measure: usize,
1277}
1278
1279/// A part read, put together as a stream: its measures and instruments where
1280/// they stood, each measure's elements in music21's order, the endings
1281/// opening or closing on its measures, and its slurs.
1282fn assemble(part: PartBuilt, index: usize, endings: &[(Vec<Place>, u32)]) -> Stream {
1283    let mut stream = Stream::with_kind(StreamKind::Part);
1284    stream.set_name(part.name.clone());
1285    stream.set_abbreviation(part.name.clone());
1286    // Each note read, by its number, at its place among the part's leaves.
1287    let mut places: Vec<(usize, usize)> = Vec::new();
1288    let mut leaves = 0;
1289    let mut measures = 0;
1290    for (offset, item) in part.items {
1291        match item {
1292            PartItem::Instrument(instrument) => {
1293                stream.insert(offset, StreamElement::Instrument(instrument));
1294                leaves += 1;
1295            }
1296            PartItem::Measure(built) => {
1297                let mut measure = Stream::with_kind(StreamKind::Measure);
1298                measure.set_number(built.number);
1299                measure.set_left_barline(built.left);
1300                measure.set_right_barline(built.right);
1301                // A bracket is marked where it opens and where it closes.
1302                let here = Place {
1303                    part: index,
1304                    measure: measures,
1305                };
1306                if let Some((spanned, number)) = endings.iter().find(|(spanned, _)| {
1307                    spanned.first() == Some(&here) || spanned.last() == Some(&here)
1308                }) {
1309                    let ending = Ending::new(
1310                        vec![*number],
1311                        spanned.first() == Some(&here),
1312                        spanned.last() == Some(&here),
1313                    );
1314                    measure.set_ending(Some(ending.placed(BracketPlace::LastMeasure)));
1315                }
1316                for place in sorted_places(&built.items) {
1317                    let item = &built.items[place];
1318                    match &item.content {
1319                        Content::Element(element, serial) => {
1320                            if let Some(serial) = serial {
1321                                places.push((*serial, leaves));
1322                            }
1323                            leaves += 1;
1324                            measure.insert(item.offset, (**element).clone());
1325                        }
1326                        Content::Voice(voice) => {
1327                            let mut inner = Stream::with_kind(StreamKind::Voice);
1328                            inner.set_id(Some(voice.id.to_string()));
1329                            for place in sorted_places(&voice.items) {
1330                                let held = &voice.items[place];
1331                                if let Content::Element(element, serial) = &held.content {
1332                                    if let Some(serial) = serial {
1333                                        places.push((*serial, leaves));
1334                                    }
1335                                    leaves += 1;
1336                                    inner.insert(held.offset, (**element).clone());
1337                                }
1338                            }
1339                            measure.insert(item.offset, inner);
1340                        }
1341                    }
1342                }
1343                stream.insert(offset, measure);
1344                measures += 1;
1345            }
1346        }
1347    }
1348    let place_of = |serial: usize| {
1349        places
1350            .iter()
1351            .find(|(read, _)| *read == serial)
1352            .map(|(_, place)| *place)
1353    };
1354    for (start, end) in part.slurs {
1355        stream.add_spanner(Spanner::with_unplaced(
1356            crate::spanner::SpannerKind::Slur,
1357            vec![place_of(start), place_of(end)],
1358        ));
1359    }
1360    stream
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365    use super::*;
1366
1367    /// A position as far from the staff as an integer goes gives some
1368    /// step and octave rather than overflowing: the fuzzer found one.
1369    #[test]
1370    fn an_extreme_position_does_not_overflow() {
1371        for clef in ["TREBLE", "BASS", "TREBLE8dw", "ALTO"] {
1372            let _ = step_and_octave(clef, IntegerType::MIN);
1373            let _ = step_and_octave(clef, IntegerType::MAX);
1374        }
1375    }
1376
1377    #[test]
1378    fn a_position_is_a_step_and_octave_under_its_clef() {
1379        assert_eq!(step_and_octave("BASS", 3), ('G', 3));
1380        assert_eq!(step_and_octave("TREBLE", 1), ('C', 5));
1381        assert_eq!(step_and_octave("TREBLE", 0), ('B', 4));
1382        assert_eq!(step_and_octave("TREBLE", -6), ('C', 4));
1383        assert_eq!(step_and_octave("TENOR", 2), ('C', 4));
1384    }
1385
1386    #[test]
1387    fn a_refusal_says_its_line() {
1388        let text = "!NoteWorthyComposer(2.0)\n|AddStaff|\n|Clef|Type:Bass\n\
1389                    |Note|Dur:Whole|Pos:1\n|Note|Dur:Eon|Pos:2\n";
1390        let error = from_noteworthy(text).unwrap_err();
1391        assert_eq!(error.to_string(), "NoteWorthy error: no note length Eon");
1392        assert_eq!(error.position(), Some(&Position::line(5)));
1393
1394        let error = from_noteworthy("|AddStaff|\n|Note|Dur:4th|Pos:x\n").unwrap_err();
1395        assert_eq!(error.position(), Some(&Position::line(2)));
1396    }
1397
1398    fn names(score: &Stream) -> Vec<String> {
1399        score
1400            .pitches()
1401            .iter()
1402            .map(|pitch| pitch.name_with_octave())
1403            .collect()
1404    }
1405
1406    #[test]
1407    fn a_note_is_spelled_from_its_place_under_the_clef() {
1408        let score = from_noteworthy(
1409            "|AddStaff|\n|Clef|Type:Bass\n|Note|Dur:4th|Pos:b3\n|Note|Dur:4th|Pos:3\n|Bar\n|Note|Dur:4th|Pos:3\n",
1410        )
1411        .unwrap();
1412        // An accidental lasts to the barline.
1413        assert_eq!(names(&score), ["Gb3", "Gb3", "G3"]);
1414    }
1415
1416    #[test]
1417    fn a_key_signature_spells_the_notes_after_it() {
1418        let score = from_noteworthy(
1419            "|AddStaff|\n|Key|Signature:F#,C#,G#,D#\n|Chord|Dur:Half|Pos:1,3,#5\n|Chord|Dur:Half|Pos:1,3,5\n",
1420        )
1421        .unwrap();
1422        assert_eq!(names(&score), ["C#5", "E5", "G#5", "C#5", "E5", "G#5"]);
1423    }
1424
1425    #[test]
1426    fn the_first_two_measures_are_both_numbered_nought() {
1427        let score =
1428            from_noteworthy("|AddStaff|\n|Note|Dur:Whole|Pos:1\n|Bar\n|Note|Dur:Whole|Pos:1\n|Bar\n|Note|Dur:Whole|Pos:1\n")
1429                .unwrap();
1430        let numbers: Vec<IntegerType> = score.parts()[0]
1431            .measures()
1432            .iter()
1433            .map(|measure| measure.number())
1434            .collect();
1435        assert_eq!(numbers, [0, 0, 1]);
1436    }
1437
1438    #[test]
1439    fn a_verse_is_split_into_syllables() {
1440        assert_eq!(lyrics("\"Hello world\""), ["Hello", "world"]);
1441        assert_eq!(
1442            lyrics("\"A-ve Ma-ri-a\""),
1443            ["A", " -ve", "Ma", " -ri", " -a"]
1444        );
1445    }
1446
1447    #[test]
1448    fn a_line_with_an_attribute_and_no_value_is_refused() {
1449        assert!(from_noteworthy("|AddStaff|\n|Note|Dur\n").is_err());
1450        assert!(from_noteworthy("|Note|Dur:4th|Pos:1\n").is_err());
1451    }
1452
1453    /// The notes, chords and rests of the first measure: where each starts
1454    /// in it, how long it is and what it sounds.
1455    fn first_measure(lines: &str) -> Vec<(FloatType, FloatType, String)> {
1456        let score = from_noteworthy(&format!("|AddStaff|\n|Clef|Type:Treble\n{lines}")).unwrap();
1457        let mut out: Vec<(FloatType, FloatType, String)> = score.parts()[0].measures()[0]
1458            .leaves()
1459            .into_iter()
1460            .filter_map(|(offset, element)| {
1461                let sounds = match element {
1462                    StreamElement::Note(note) => note.pitch().name_with_octave(),
1463                    StreamElement::Chord(chord) => chord
1464                        .notes()
1465                        .iter()
1466                        .map(|note| note.pitch().name_with_octave())
1467                        .collect::<Vec<_>>()
1468                        .join(" "),
1469                    StreamElement::Rest(_) => "rest".to_string(),
1470                    _ => return None,
1471                };
1472                Some((offset, element.quarter_length(), sounds))
1473            })
1474            .collect();
1475        out.sort_by(|left, right| left.partial_cmp(right).unwrap());
1476        out
1477    }
1478
1479    #[test]
1480    fn a_chord_of_two_lengths_is_two_chords_starting_together() {
1481        assert_eq!(
1482            first_measure(
1483                "|Note|Dur:4th|Pos:0\n\
1484                 |Chord|Dur:8th|Pos:-4,n-3,b-2,#-1,x0,v1,2x|Opts:Stem=Down|Dur2:8th,DblDotted|Pos2:3x\n\
1485                 |Note|Dur:4th|Pos:-5\n"
1486            ),
1487            [
1488                (0.0, 1.0, "B4".to_string()),
1489                (1.0, 0.5, "E4 F4 Gb4 A#4 B##4 Cbb5 D5".to_string()),
1490                (1.0, 0.875, "E5".to_string()),
1491                (1.5, 1.0, "D4".to_string()),
1492            ]
1493        );
1494    }
1495
1496    #[test]
1497    fn a_rest_chord_is_a_rest_and_a_chord_starting_together() {
1498        assert_eq!(
1499            first_measure(
1500                "|Note|Dur:4th|Pos:0\n\
1501                 |RestChord|Dur:Half|Opts:Stem=Up|Dur2:4th|Pos2:-1,1\n\
1502                 |RestChord|Dur:4th|Dur2:4th|Pos2:-5\n\
1503                 |Note|Dur:4th|Pos:0\n"
1504            ),
1505            [
1506                (0.0, 1.0, "B4".to_string()),
1507                (1.0, 1.0, "A4 C5".to_string()),
1508                (1.0, 2.0, "rest".to_string()),
1509                (2.0, 1.0, "D4".to_string()),
1510                (2.0, 1.0, "rest".to_string()),
1511                (3.0, 1.0, "B4".to_string()),
1512            ]
1513        );
1514    }
1515
1516    /// A part's notes, chords and rests as music21 writes their reprs.
1517    fn shown(element: &StreamElement) -> String {
1518        match element {
1519            StreamElement::Note(note) => format!("Note {}", note.pitch().name()),
1520            StreamElement::Chord(chord) => format!(
1521                "Chord {}",
1522                chord
1523                    .notes()
1524                    .iter()
1525                    .map(|note| note.pitch().name_with_octave())
1526                    .collect::<Vec<_>>()
1527                    .join(" ")
1528            ),
1529            _ => "other".to_string(),
1530        }
1531    }
1532
1533    fn treble(lines: &[&str]) -> Stream {
1534        let mut text = String::from("|AddStaff|\n|Clef|Type:Treble\n");
1535        for line in lines {
1536            text.push_str(line);
1537            text.push('\n');
1538        }
1539        from_noteworthy(&text).unwrap()
1540    }
1541
1542    /// Every slur of the first part, as what it joins.
1543    fn slurs(lines: &[&str]) -> Vec<Vec<String>> {
1544        let score = treble(lines);
1545        let part = &score.parts()[0];
1546        let leaves = part.leaves();
1547        let mut found: Vec<Vec<String>> = part
1548            .spanners()
1549            .iter()
1550            .map(|slur| {
1551                slur.spanned()
1552                    .iter()
1553                    .map(|place| place.map_or("none".to_string(), |at| shown(leaves[at].1)))
1554                    .collect()
1555            })
1556            .collect();
1557        found.sort();
1558        found
1559    }
1560
1561    /// Every note of the first part, with its offset in the part and its tie.
1562    fn ties(lines: &[&str]) -> Vec<(String, FloatType, Option<TieType>)> {
1563        let score = treble(lines);
1564        let part = &score.parts()[0];
1565        let mut found = Vec::new();
1566        for (offset, element) in part.leaves() {
1567            let notes: Vec<&Note> = match element {
1568                StreamElement::Note(note) => vec![note],
1569                StreamElement::Chord(chord) => chord.notes().iter().collect(),
1570                _ => continue,
1571            };
1572            for note in notes {
1573                found.push((
1574                    note.pitch().name_with_octave(),
1575                    offset,
1576                    note.tie().map(Tie::tie_type),
1577                ));
1578            }
1579        }
1580        found.sort_by(|left, right| left.1.total_cmp(&right.1).then(left.0.cmp(&right.0)));
1581        found
1582    }
1583
1584    fn strings(groups: &[&[&str]]) -> Vec<Vec<String>> {
1585        let mut made: Vec<Vec<String>> = groups
1586            .iter()
1587            .map(|group| group.iter().map(|one| (*one).to_string()).collect())
1588            .collect();
1589        made.sort();
1590        made
1591    }
1592
1593    #[test]
1594    fn notes_after_a_group_follow_the_shortest_of_it() {
1595        assert_eq!(
1596            first_measure(
1597                "|Chord|Dur:8th|Pos:-4|Dur2:8th,DblDotted|Pos2:3\n\
1598                 |Note|Dur:4th|Pos:-5\n\
1599                 |Note|Dur:4th|Pos:-4\n"
1600            ),
1601            [
1602                (0.0, 0.5, "E4".to_string()),
1603                (0.0, 0.875, "E5".to_string()),
1604                (0.5, 1.0, "D4".to_string()),
1605                (1.5, 1.0, "E4".to_string()),
1606            ]
1607        );
1608    }
1609
1610    #[test]
1611    fn a_slur_runs_to_the_next_note_once_it_ends() {
1612        assert_eq!(
1613            slurs(&[
1614                "|RestChord|Dur:Half|Dur2:4th,Slur|Pos2:-1,1",
1615                "|Note|Dur:4th|Pos:0"
1616            ]),
1617            strings(&[&["Chord A4 C5", "Note B"]])
1618        );
1619        assert_eq!(
1620            slurs(&[
1621                "|Chord|Dur:Half|Pos:1|Dur2:4th|Pos2:3",
1622                "|Note|Dur:4th,Slur|Pos:2",
1623                "|Bar|",
1624                "|Note|Dur:4th|Pos:4",
1625            ]),
1626            strings(&[&["Note D", "Note F"]])
1627        );
1628        assert_eq!(
1629            slurs(&[
1630                "|Note|Dur:4th,Slur|Pos:1",
1631                "|AddStaff|",
1632                "|Clef|Type:Treble",
1633                "|Note|Dur:4th|Pos:1",
1634            ]),
1635            Vec::<Vec<String>>::new()
1636        );
1637    }
1638
1639    #[test]
1640    fn a_slur_runs_to_the_same_group() {
1641        assert_eq!(
1642            slurs(&[
1643                "|Chord|Dur:4th,Slur|Pos:1|Dur2:4th,Slur|Pos2:3",
1644                "|Chord|Dur:4th|Pos:2|Dur2:4th|Pos2:4",
1645            ]),
1646            strings(&[&["Chord C5", "Chord D5"], &["Chord E5", "Chord F5"]])
1647        );
1648        assert_eq!(
1649            slurs(&[
1650                "|Chord|Dur:4th,Slur|Pos:1|Dur2:4th,Slur|Pos2:3",
1651                "|Note|Dur:4th|Pos:2",
1652            ]),
1653            strings(&[&["Chord C5", "Note D"], &["Chord E5", "Note D"]])
1654        );
1655    }
1656
1657    #[test]
1658    fn a_tie_follows_its_position_and_pitch() {
1659        let start = Some(TieType::Start);
1660        let stop = Some(TieType::Stop);
1661        let at = |name: &str, offset: FloatType, tie| (name.to_string(), offset, tie);
1662        assert_eq!(
1663            ties(&[
1664                "|Chord|Dur:4th|Pos:1^|Dur2:4th|Pos2:3",
1665                "|Chord|Dur:4th|Pos:1|Dur2:4th|Pos2:3"
1666            ]),
1667            [
1668                at("C5", 0.0, start),
1669                at("E5", 0.0, None),
1670                at("C5", 1.0, stop),
1671                at("E5", 1.0, None)
1672            ]
1673        );
1674        assert_eq!(
1675            ties(&[
1676                "|Note|Dur:4th|Pos:-6^",
1677                "|Clef|Type:Bass",
1678                "|Note|Dur:4th|Pos:6"
1679            ]),
1680            [at("C4", 0.0, start), at("C4", 1.0, stop)]
1681        );
1682        assert_eq!(
1683            ties(&[
1684                "|Note|Dur:4th|Pos:1^",
1685                "|Note|Dur:4th|Pos:2",
1686                "|Note|Dur:4th|Pos:1"
1687            ]),
1688            [
1689                at("C5", 0.0, start),
1690                at("D5", 1.0, None),
1691                at("C5", 2.0, None)
1692            ]
1693        );
1694        assert_eq!(
1695            ties(&["|Note|Dur:Whole|Pos:1^", "|Bar|", "|Note|Dur:Whole|Pos:1"]),
1696            [at("C5", 0.0, start), at("C5", 4.0, stop)]
1697        );
1698        assert_eq!(
1699            ties(&[
1700                "|Chord|Dur:4th|Pos:1^|Dur2:Half|Pos2:3",
1701                "|Bar|",
1702                "|Note|Dur:4th|Pos:1"
1703            ]),
1704            [
1705                at("C5", 0.0, start),
1706                at("E5", 0.0, None),
1707                at("C5", 2.0, None)
1708            ]
1709        );
1710    }
1711
1712    #[test]
1713    fn a_direction_goes_where_the_next_note_will() {
1714        for line in [
1715            "|Dynamic|Style:p|Pos:-8",
1716            "|Clef|Type:Bass",
1717            "|Key|Signature:F#",
1718            "|Text|Text:\"dolce\"|Pos:8",
1719        ] {
1720            let score = treble(&[
1721                "|Chord|Dur:4th|Pos:-1|Dur2:Whole|Pos2:3",
1722                line,
1723                "|Note|Dur:4th|Pos:1",
1724            ]);
1725            let measure = &score.parts()[0].measures()[0];
1726            let placed: Vec<FloatType> = measure
1727                .leaves()
1728                .into_iter()
1729                .filter(|(_, element)| {
1730                    matches!(
1731                        element,
1732                        StreamElement::Dynamic(_)
1733                            | StreamElement::KeySignature(_)
1734                            | StreamElement::TextExpression(_)
1735                            | StreamElement::Note(_)
1736                    ) || matches!(element, StreamElement::Clef(clef) if clef.kind() == ClefKind::BassClef)
1737                })
1738                .map(|(offset, _)| offset)
1739                .collect();
1740            assert_eq!(placed, [1.0, 1.0], "{line}");
1741        }
1742    }
1743}