Skip to main content

music21/
mei.rs

1//! MEI: music21's `mei.base`, which reads a score encoded by the Music
2//! Encoding Initiative's schema.
3//!
4//! An MEI score is measures, each holding a `<staff>` for every part and in
5//! it a `<layer>` for every voice; `<scoreDef>` and `<staffDef>` say the
6//! meter, key, clef and instrument. Slurs, ties, beams and tuplets may be
7//! written on the notes or apart from them, naming the notes they join by
8//! their `xml:id`.
9
10use std::collections::HashMap;
11
12use crate::articulations::{Articulation, ArticulationKind};
13use crate::bar::{Barline, BarlineType, RepeatDirection};
14use crate::chord::Chord;
15use crate::clef::{Clef, ClefKind};
16use crate::defaults::{FloatType, IntegerType};
17use crate::duration::{Duration, DurationType, Tuplet, TupletType};
18use crate::error::{FormatErrorKind, Result};
19use crate::expressions::{Expression, Ornament, OrnamentKind};
20use crate::instrument::{Instrument, SearchLanguage};
21use crate::interval::Interval;
22use crate::key::{Key, KeySignature};
23use crate::makenotation::op_frac;
24use crate::metadata::Metadata;
25use crate::meter::TimeSignature;
26use crate::notation::{BeamType, Lyric, Tie};
27use crate::note::Note;
28use crate::pitch::{Accidental, Pitch, PitchOptions};
29use crate::rest::Rest;
30use crate::spanner::{Spanner, SpannerKind};
31use crate::stream::{Stream, StreamElement, StreamEvent, StreamKind};
32use crate::xml::Xml;
33
34pub mod step;
35
36use step::{fresh_uuid, mei_error, without_hash};
37
38/// A tag with any namespace prefix taken off.
39fn local(tag: &str) -> &str {
40    tag.rsplit(':').next().unwrap_or(tag)
41}
42
43fn children<'a>(element: &'a Xml, tag: &'a str) -> impl Iterator<Item = &'a Xml> {
44    element
45        .children
46        .iter()
47        .filter(move |child| local(&child.tag) == tag)
48}
49
50fn child<'a>(element: &'a Xml, tag: &str) -> Option<&'a Xml> {
51    element
52        .children
53        .iter()
54        .find(|child| local(&child.tag) == tag)
55}
56
57/// Every element under this one of a tag, in document order.
58fn descendants<'a>(element: &'a Xml, tag: &str, out: &mut Vec<&'a Xml>) {
59    for held in &element.children {
60        if local(&held.tag) == tag {
61            out.push(held);
62        }
63        descendants(held, tag, out);
64    }
65}
66
67/// A tuplet a `<tupletSpan>` runs from one note to another, waiting for
68/// the layer to say which notes lie between.
69#[derive(Clone, Debug)]
70struct Search {
71    end: &'static str,
72    number: u32,
73    base: u32,
74}
75
76/// A thing a layer holds: an element, and what is known of it that the
77/// element itself cannot say.
78#[derive(Clone, Debug)]
79struct Thing {
80    element: StreamElement,
81    /// The number slurs know it by.
82    uid: usize,
83    search: Option<Search>,
84    /// A measure rest with no length of its own.
85    whole_measure: bool,
86}
87
88/// What a `<staffDef>` says: music21's dictionary of instrument, meter, key
89/// and clef, in that order.
90#[derive(Clone, Debug, Default)]
91struct StaffDef {
92    instrument: Option<Instrument>,
93    meter: Option<TimeSignature>,
94    key: Option<Key>,
95    clef: Option<Clef>,
96}
97
98impl StaffDef {
99    fn elements(&self) -> Vec<StreamElement> {
100        let mut out: Vec<StreamElement> = Vec::new();
101        if let Some(instrument) = &self.instrument {
102            out.push(instrument.clone().into());
103        }
104        if let Some(meter) = &self.meter {
105            out.push(meter.clone().into());
106        }
107        if let Some(key) = &self.key {
108            out.push(StreamElement::Key(key.clone()));
109        }
110        if let Some(clef) = &self.clef {
111            out.push(clef.clone().into());
112        }
113        out
114    }
115}
116
117/// A measure of one staff while it is put together.
118#[derive(Clone, Debug)]
119struct Measure {
120    number: IntegerType,
121    /// Each voice with its name and what it holds.
122    voices: Vec<(String, Vec<Thing>)>,
123    /// What stands at the start outside any voice, in the order inserted.
124    own: Vec<StreamElement>,
125    left: Option<Barline>,
126    right: Option<Barline>,
127    /// The length a measure rest fixed it at.
128    length: Option<FloatType>,
129}
130
131/// What a part holds in order: an instrument before its measures, then the
132/// measures.
133#[derive(Clone, Debug)]
134enum Held {
135    Instrument(Box<Instrument>),
136    Measure(Box<Measure>),
137}
138
139/// music21's `MeiToM21Converter`: the document, and what the elements that
140/// stand apart from the notes say of each note by its id.
141struct Reader {
142    /// For each `xml:id`, the attributes to be put on the element.
143    extra: HashMap<String, Vec<(&'static str, String)>>,
144    /// The slurs, each with the name it is known by and the notes it joins.
145    slurs: Vec<(String, Vec<usize>)>,
146    next_uid: usize,
147    next_slur: usize,
148}
149
150/// music21's `makeDuration`: a length, then its dots.
151fn duration_of(base: FloatType, dots: u32) -> Result<Duration> {
152    let plain = Duration::new(base)?;
153    Ok(match plain.type_and_dots() {
154        Some((kind, _)) => Duration::from_type_with_dots(kind, dots),
155        None => plain,
156    })
157}
158
159fn dots_of(element: &Xml) -> Result<u32> {
160    match element.get("dots") {
161        None => Ok(0),
162        Some(dots) => dots
163            .parse()
164            .map_err(|_| mei_error(format!("the dots {dots:?} are no number"))),
165    }
166}
167
168/// music21's `_makeArticList`: the marks an `artic` attribute names.
169fn articulations_of(attribute: &str) -> Result<Vec<Articulation>> {
170    let mut marks = Vec::new();
171    for name in attribute.split(' ') {
172        for class in step::articulation_classes(name)? {
173            let kind = ArticulationKind::from_class_name(class)
174                .ok_or_else(|| mei_error(format!("no articulation called {class}")))?;
175            marks.push(Articulation::of_kind(kind));
176        }
177    }
178    Ok(marks)
179}
180
181/// music21's `_barlineFromAttr`: a barline, or the two a repeat both ways
182/// is, the one closing a measure and the one opening the next.
183fn barline_of(attribute: &str) -> Result<(Barline, Option<Barline>)> {
184    Ok(match attribute {
185        "rptboth" => (
186            Barline::repeat(RepeatDirection::End, Some(2)),
187            Some(Barline::repeat(RepeatDirection::Start, None)),
188        ),
189        "rptend" => (Barline::repeat(RepeatDirection::End, Some(2)), None),
190        other if other.starts_with(step::REPEAT_PREFIX) => {
191            (Barline::repeat(RepeatDirection::Start, None), None)
192        }
193        other => {
194            let style = step::translate(&step::BARLINES, other, "right")?;
195            (Barline::new(BarlineType::from_name(style)?), None)
196        }
197    })
198}
199
200fn tie_of(attribute: &str) -> Tie {
201    Tie::new(step::tie_type(attribute))
202}
203
204fn meter_of(element: &Xml) -> Result<TimeSignature> {
205    TimeSignature::from_ratio_string(&format!(
206        "{}/{}",
207        element.get("meter.count").unwrap_or("None"),
208        element.get("meter.unit").unwrap_or("None")
209    ))
210}
211
212/// music21's `_keySigFromAttrs`: a key named by its tonic, or by how many
213/// sharps or flats it is written with.
214fn key_of(element: &Xml) -> Result<Key> {
215    if let Some(step) = element.get("key.pname") {
216        let tonic = format!(
217            "{step}{}",
218            step::written_accidental(element.get("key.accid"))?.unwrap_or("")
219        );
220        return Key::from_tonic_mode(
221            &tonic,
222            element.get("key.mode").filter(|mode| !mode.is_empty()),
223        );
224    }
225    let sharps = step::sharps_of(element.get("key.sig").unwrap_or("0"))?;
226    Ok(KeySignature::new(sharps).as_key(element.get("key.mode").unwrap_or("major")))
227}
228
229/// music21's `_transpositionFromAttrs`: the interval an instrument sounds
230/// away from where it is written.
231fn transposition_of(element: &Xml) -> Result<Interval> {
232    let read = |name: &str| -> Result<IntegerType> {
233        match element.get(name) {
234            None => Ok(0),
235            Some(text) => text
236                .parse()
237                .map_err(|_| mei_error(format!("{name} is no number: {text:?}"))),
238        }
239    };
240    let (diatonic, semitones) =
241        step::transposition_steps(read("trans.diat")?.into(), read("trans.semi")?.into())?;
242    Interval::from_generic_and_chromatic(diatonic, semitones)
243}
244
245fn clef_of(
246    shape: Option<&str>,
247    line: Option<&str>,
248    displaced: Option<&str>,
249    place: Option<&str>,
250) -> Result<Clef> {
251    match shape {
252        Some("perc") => Ok(Clef::of_kind(ClefKind::PercussionClef)),
253        Some("TAB") => Ok(Clef::of_kind(ClefKind::TabClef)),
254        _ => {
255            let shift = step::octave_shift(displaced, place)?;
256            let (Some(shape), Some(line)) = (shape, line) else {
257                return Err(mei_error("a clef with no shape or no line"));
258            };
259            Clef::from_string(&format!("{shape}{line}"), shift)
260        }
261    }
262}
263
264fn clef_element(element: &Xml) -> Result<Clef> {
265    clef_of(
266        element.get("shape"),
267        element.get("line"),
268        element.get("dis"),
269        element.get("dis.place"),
270    )
271}
272
273/// Whether a length is written with a flag, and so may be beamed.
274fn is_beamable(duration: &Duration) -> Option<DurationType> {
275    match duration.components().as_slice() {
276        [(kind, _)] if kind.quarter_length() < 1.0 => Some(*kind),
277        _ => None,
278    }
279}
280
281fn with_duration(element: &mut StreamElement, change: impl FnOnce(&mut Duration)) {
282    let Some(mut duration) = element.duration().cloned() else {
283        return;
284    };
285    change(&mut duration);
286    match element {
287        StreamElement::Note(note) => note.set_duration(duration),
288        StreamElement::Chord(chord) => chord.set_duration(duration),
289        StreamElement::Rest(rest) => rest.set_duration(duration),
290        _ => {}
291    }
292}
293
294fn is_sounding(element: &StreamElement) -> bool {
295    matches!(
296        element,
297        StreamElement::Note(_) | StreamElement::Chord(_) | StreamElement::Rest(_)
298    )
299}
300
301fn mark_first_tuplet(element: &mut StreamElement, kind: TupletType) {
302    with_duration(element, |duration| {
303        let mut tuplets = duration.tuplets();
304        if let Some(first) = tuplets.first_mut() {
305            first.set_tuplet_type(Some(kind));
306        }
307        duration.set_tuplets(tuplets);
308    });
309}
310
311/// music21's `scaleToTuplet` for a tuplet whose numbers are known: so many
312/// notes in the time of so many, of the value the note is written in.
313fn scale_to_tuplet(element: &mut StreamElement, number: u32, base: u32) {
314    if !is_sounding(element) {
315        return;
316    }
317    with_duration(element, |duration| {
318        let kind = match duration.components().as_slice() {
319            [(kind, _)] => *kind,
320            _ => DurationType::Quarter,
321        };
322        duration.append_tuplet(Tuplet::new(number, base, kind, 0));
323    });
324}
325
326/// music21's `beamTogether`: the first thing that can carry a beam starts
327/// it, those after carry it on, and the last ends it.
328fn beam_together(things: &mut [Thing]) -> Result<()> {
329    let mut last: Option<usize> = None;
330    for (index, thing) in things.iter_mut().enumerate() {
331        let (beams, duration) = match &thing.element {
332            StreamElement::Note(note) => (note.beams().clone(), note.duration().cloned()),
333            StreamElement::Chord(chord) => (chord.beams().clone(), chord.duration().cloned()),
334            _ => continue,
335        };
336        let Some(kind) = duration.as_ref().and_then(is_beamable) else {
337            continue;
338        };
339        if !beams.is_empty() {
340            continue;
341        }
342        let mut filled = beams;
343        filled.fill(
344            kind,
345            Some(if last.is_none() {
346                BeamType::Start
347            } else {
348                BeamType::Continue
349            }),
350        )?;
351        match &mut thing.element {
352            StreamElement::Note(note) => note.set_beams(filled),
353            StreamElement::Chord(chord) => chord.set_beams(filled),
354            _ => {}
355        }
356        last = Some(index);
357    }
358    // Where nothing was beamed music21 reaches for the last thing of all.
359    let closing = last.or(things.len().checked_sub(1));
360    if let Some(thing) = closing.and_then(|index| things.get_mut(index)) {
361        match &mut thing.element {
362            StreamElement::Note(note) => {
363                let mut beams = note.beams().clone();
364                beams.set_all(BeamType::Stop, None);
365                note.set_beams(beams);
366            }
367            StreamElement::Chord(chord) => {
368                let mut beams = chord.beams().clone();
369                beams.set_all(BeamType::Stop, None);
370                chord.set_beams(beams);
371            }
372            _ => {}
373        }
374    }
375    Ok(())
376}
377
378impl Reader {
379    /// An attribute as music21 reads it once the spanning elements have
380    /// written theirs onto the notes: what the element says, then what was
381    /// said of it.
382    fn attribute(&self, element: &Xml, name: &str) -> Option<String> {
383        let added = element
384            .get("xml:id")
385            .and_then(|id| self.extra.get(id))
386            .and_then(|extra| {
387                extra
388                    .iter()
389                    .find(|(held, _)| *held == name)
390                    .map(|(_, value)| value.clone())
391            });
392        match (element.get(name), added) {
393            (Some(own), Some(added)) => Some(format!("{own}{added}")),
394            (Some(own), None) => Some(own.to_string()),
395            (None, added) => added,
396        }
397    }
398
399    fn set(&mut self, id: &str, name: &'static str, value: String) {
400        let extra = self.extra.entry(without_hash(id).to_string()).or_default();
401        match extra.iter_mut().find(|(held, _)| *held == name) {
402            Some((_, held)) => *held = value,
403            None => extra.push((name, value)),
404        }
405    }
406
407    /// music21's `_ppSlurs`, `_ppTies`, `_ppBeams` and `_ppTuplets`: what
408    /// the spanning elements of the score say, written against the ids of
409    /// the notes they name.
410    fn preprocess(&mut self, score: &Xml) {
411        let mut found = Vec::new();
412        descendants(score, "slur", &mut found);
413        for slur in std::mem::take(&mut found) {
414            if let (Some(start), Some(end)) = (slur.get("startid"), slur.get("endid")) {
415                let name = fresh_uuid(self.next_slur);
416                self.next_slur += 1;
417                self.slurs.push((name.clone(), Vec::new()));
418                self.set(start, "m21SlurStart", name.clone());
419                self.set(end, "m21SlurEnd", name);
420            }
421        }
422        descendants(score, "tie", &mut found);
423        for tie in std::mem::take(&mut found) {
424            if let (Some(start), Some(end)) = (tie.get("startid"), tie.get("endid")) {
425                self.set(start, "tie", "i".to_string());
426                self.set(end, "tie", "t".to_string());
427            }
428        }
429        descendants(score, "beamSpan", &mut found);
430        for beam in std::mem::take(&mut found) {
431            let (Some(start), Some(end)) = (beam.get("startid"), beam.get("endid")) else {
432                continue;
433            };
434            self.set(start, "m21Beam", "start".to_string());
435            self.set(end, "m21Beam", "stop".to_string());
436            for id in beam.get("plist").unwrap_or("").split(' ') {
437                let id = without_hash(id);
438                let has = self
439                    .extra
440                    .get(id)
441                    .is_some_and(|extra| extra.iter().any(|(name, _)| *name == "m21Beam"));
442                if !has {
443                    self.set(id, "m21Beam", "continue".to_string());
444                }
445            }
446        }
447        descendants(score, "tupletSpan", &mut found);
448        for tuplet in found {
449            let number = tuplet.get("num").unwrap_or("None").to_string();
450            let base = tuplet.get("numbase").unwrap_or("None").to_string();
451            if let Some(list) = tuplet.get("plist") {
452                for id in list.split(' ') {
453                    if !without_hash(id).is_empty() {
454                        self.set(id, "m21TupletNum", number.clone());
455                        self.set(id, "m21TupletNumbase", base.clone());
456                    }
457                }
458            } else if let (Some(start), Some(end)) = (tuplet.get("startid"), tuplet.get("endid")) {
459                for (id, which) in [(start, "start"), (end, "end")] {
460                    self.set(id, "m21TupletSearch", which.to_string());
461                    self.set(id, "m21TupletNum", number.clone());
462                    self.set(id, "m21TupletNumbase", base.clone());
463                }
464            }
465        }
466    }
467
468    fn uid(&mut self) -> usize {
469        self.next_uid += 1;
470        self.next_uid - 1
471    }
472
473    /// music21's `addSlurs`: the slurs an element starts or ends.
474    fn add_slurs(&mut self, element: &Xml, uid: usize) -> Result<()> {
475        let join = |slurs: &mut Vec<(String, Vec<usize>)>, name: &str| {
476            if let Some((_, held)) = slurs.iter_mut().find(|(held, _)| held == name) {
477                held.push(uid);
478            }
479        };
480        if let Some(name) = self.attribute(element, "m21SlurStart") {
481            join(&mut self.slurs, &name);
482        }
483        if let Some(name) = self.attribute(element, "m21SlurEnd") {
484            join(&mut self.slurs, &name);
485        }
486        if let Some(slurs) = element.get("slur") {
487            for slur in slurs.split(' ') {
488                let chars: Vec<char> = slur.chars().collect();
489                let [number, kind] = chars.as_slice() else {
490                    return Err(mei_error(format!("cannot read the slur {slur:?}")));
491                };
492                let name = number.to_string();
493                match kind {
494                    'i' => self.slurs.push((name, vec![uid])),
495                    't' => join(&mut self.slurs, &name),
496                    _ => {}
497                }
498            }
499        }
500        Ok(())
501    }
502
503    /// What the tuplet numbers written against an element do to it:
504    /// music21's `scaleToTuplet`.
505    fn tuplet(&self, element: &Xml, thing: &mut Thing) -> Result<()> {
506        let Some(number) = self.attribute(element, "m21TupletNum") else {
507            return Ok(());
508        };
509        let base = self
510            .attribute(element, "m21TupletNumbase")
511            .unwrap_or_default();
512        let read = |text: &str| -> Result<u32> {
513            text.parse()
514                .map_err(|_| mei_error(format!("a tuplet of {text:?} notes")))
515        };
516        let (number, base) = (read(&number)?, read(&base)?);
517        match self.attribute(element, "m21TupletSearch").as_deref() {
518            Some(end) => {
519                thing.search = Some(Search {
520                    end: if end.contains("start") {
521                        "start"
522                    } else {
523                        "end"
524                    },
525                    number,
526                    base,
527                });
528            }
529            None => {
530                scale_to_tuplet(&mut thing.element, number, base);
531                if let Some(written) = element.get("tuplet") {
532                    if written.starts_with('i') {
533                        mark_first_tuplet(&mut thing.element, TupletType::Start);
534                    } else if written.starts_with('t') {
535                        mark_first_tuplet(&mut thing.element, TupletType::Stop);
536                    }
537                }
538            }
539        }
540        Ok(())
541    }
542
543    /// music21's `noteFromElement`. The second answer is the number slurs
544    /// know the note by.
545    fn note(&mut self, element: &Xml) -> Result<(Note, usize)> {
546        let name = element.get("pname").unwrap_or("");
547        let mut pitch = if name.is_empty() {
548            Pitch::from_name("C4")?
549        } else {
550            let step = name
551                .chars()
552                .next()
553                .map(|c| c.to_ascii_uppercase())
554                .ok_or_else(|| mei_error("a note with no name"))?;
555            let mut options = PitchOptions::new().step(step);
556            if let Some(octave) = element.get("oct").filter(|octave| !octave.is_empty()) {
557                options = options.octave(
558                    octave
559                        .parse()
560                        .map_err(|_| mei_error(format!("the octave {octave:?} is no number")))?,
561                );
562            }
563            options.build()?
564        };
565        if let Some(accidental) = step::written_accidental(element.get("accid"))? {
566            pitch.set_written_accidental(Some(Accidental::new(accidental)?));
567        }
568        let length = step::quarter_length(element.get("dur"))?;
569        let mut note =
570            Note::from_pitch(pitch).with_duration(duration_of(length, dots_of(element)?)?);
571
572        let mut dot_elements = 0;
573        for held in &element.children {
574            match local(&held.tag) {
575                "dot" => dot_elements += 1,
576                "artic" => {
577                    if let Some(marks) = held.get("artic") {
578                        note.articulations_mut().extend(articulations_of(marks)?);
579                    }
580                }
581                "accid" => {
582                    let accidental = match held.get("accid.ges") {
583                        Some(gestural) => Some(step::gestural_accidental(gestural)?),
584                        None => step::written_accidental(held.get("accid"))?,
585                    };
586                    if let Some(accidental) = accidental {
587                        let mut pitch = note.pitch().clone();
588                        pitch.set_written_accidental(Some(Accidental::new(accidental)?));
589                        note.set_pitch(pitch);
590                    }
591                }
592                "syl" => *note.lyrics_mut() = vec![syllable_of(held)?],
593                _ => {}
594            }
595        }
596        if let Some(gestural) = element.get("accid.ges") {
597            let mut pitch = note.pitch().clone();
598            pitch.set_written_accidental(Some(Accidental::new(step::gestural_accidental(
599                gestural,
600            )?)?));
601            note.set_pitch(pitch);
602        }
603        let uid = self.uid();
604        self.add_slurs(element, uid)?;
605        if let Some(id) = element.get("xml:id") {
606            note.set_id(Some(id.to_string()));
607        }
608        if let Some(marks) = element.get("artic") {
609            note.articulations_mut().extend(articulations_of(marks)?);
610        }
611        if let Some(tie) = self.attribute(element, "tie") {
612            note.set_tie(Some(tie_of(&tie)));
613        }
614        if dot_elements > 0 {
615            note.set_duration(duration_of(length, dot_elements)?);
616        }
617        if element.get("grace").is_some() {
618            let mut grace = note
619                .duration()
620                .map(Duration::grace_duration)
621                .unwrap_or_default();
622            // music21's `GraceDuration(quarterLength)`, read off a length.
623            grace.set_expression_is_inferred(true);
624            note.set_duration(grace);
625        }
626        if let Some(beam) = self.attribute(element, "m21Beam")
627            && let Some(kind) = note.duration().and_then(is_beamable)
628        {
629            let mut beams = note.beams().clone();
630            beams.fill(kind, Some(beam_type_of(&beam)?))?;
631            note.set_beams(beams);
632        }
633        let verses: Vec<&Xml> = children(element, "verse").collect();
634        if !verses.is_empty() {
635            let mut lyrics = Vec::new();
636            for (index, verse) in verses.iter().enumerate() {
637                let number = match verse.get("n") {
638                    Some(number) => number.parse::<IntegerType>().ok(),
639                    None => Some(index as IntegerType + 1),
640                };
641                for syllable in children(verse, "syl") {
642                    let mut lyric = syllable_of(syllable)?;
643                    if let Some(number) = number {
644                        lyric.set_number(number);
645                    }
646                    lyrics.push(lyric);
647                }
648            }
649            *note.lyrics_mut() = lyrics;
650        }
651        Ok((note, uid))
652    }
653
654    fn note_thing(&mut self, element: &Xml) -> Result<Thing> {
655        let (note, uid) = self.note(element)?;
656        let mut thing = Thing {
657            element: note.into(),
658            uid,
659            search: None,
660            whole_measure: false,
661        };
662        self.tuplet(element, &mut thing)?;
663        Ok(thing)
664    }
665
666    /// music21's `chordFromElement`.
667    fn chord(&mut self, element: &Xml) -> Result<Thing> {
668        let mut notes = Vec::new();
669        for held in children(element, "note") {
670            // A note of a chord takes its own tuplet, as music21 gives it.
671            let thing = self.note_thing(held)?;
672            if let StreamElement::Note(note) = thing.element {
673                notes.push(note);
674            }
675        }
676        let mut chord = Chord::new(notes)?.with_duration(duration_of(
677            step::quarter_length(element.get("dur"))?,
678            dots_of(element)?,
679        )?);
680        for held in children(element, "artic") {
681            if let Some(marks) = held.get("artic") {
682                chord.articulations_mut().extend(articulations_of(marks)?);
683            }
684        }
685        let uid = self.uid();
686        self.add_slurs(element, uid)?;
687        if let Some(id) = element.get("xml:id") {
688            chord.set_id(Some(id.to_string()));
689        }
690        if let Some(marks) = element.get("artic") {
691            chord.articulations_mut().extend(articulations_of(marks)?);
692        }
693        if let Some(tie) = self.attribute(element, "tie") {
694            chord.set_tie(Some(tie_of(&tie)));
695        }
696        if element.get("grace").is_some() {
697            let mut grace = chord
698                .duration()
699                .map(Duration::grace_duration)
700                .unwrap_or_default();
701            // music21's `GraceDuration(quarterLength)`, read off a length.
702            grace.set_expression_is_inferred(true);
703            chord.set_duration(grace);
704        }
705        if let Some(beam) = self.attribute(element, "m21Beam")
706            && let Some(kind) = chord.duration().and_then(is_beamable)
707        {
708            let mut beams = chord.beams().clone();
709            beams.fill(kind, Some(beam_type_of(&beam)?))?;
710            chord.set_beams(beams);
711        }
712        let mut thing = Thing {
713            element: chord.into(),
714            uid,
715            search: None,
716            whole_measure: false,
717        };
718        self.tuplet(element, &mut thing)?;
719        Ok(thing)
720    }
721
722    /// music21's `restFromElement` and `spaceFromElement`: a rest, hidden
723    /// where it is only space.
724    fn rest(&mut self, element: &Xml, hidden: bool, whole_measure: bool) -> Result<Thing> {
725        let mut rest = Rest::new(duration_of(
726            step::quarter_length(element.get("dur"))?,
727            dots_of(element)?,
728        )?);
729        rest.set_hidden(hidden);
730        if let Some(id) = element.get("xml:id") {
731            rest.set_id(Some(id.to_string()));
732        }
733        let mut thing = Thing {
734            element: rest.into(),
735            uid: self.uid(),
736            search: None,
737            whole_measure: whole_measure && element.get("dur").is_none(),
738        };
739        self.tuplet(element, &mut thing)?;
740        Ok(thing)
741    }
742
743    /// What a layer, a beam or a tuplet holds, in order.
744    fn contents(&mut self, element: &Xml, in_layer: bool) -> Result<Vec<Thing>> {
745        let mut things = Vec::new();
746        for held in &element.children {
747            match local(&held.tag) {
748                "clef" => things.push(Thing {
749                    element: clef_element(held)?.into(),
750                    uid: self.uid(),
751                    search: None,
752                    whole_measure: false,
753                }),
754                "chord" => things.push(self.chord(held)?),
755                "note" => things.push(self.note_thing(held)?),
756                "rest" => things.push(self.rest(held, false, false)?),
757                "mRest" if in_layer => things.push(self.rest(held, false, true)?),
758                "space" => things.push(self.rest(held, true, false)?),
759                "mSpace" if in_layer => things.push(self.rest(held, true, true)?),
760                "beam" => {
761                    let mut beamed = self.contents(held, false)?;
762                    beam_together(&mut beamed)?;
763                    things.extend(beamed);
764                }
765                "tuplet" => things.extend(self.tuplet_element(held)?),
766                "bTrem" => things.extend(self.tremolo(held)?),
767                // A barline inside a layer is checked and then has nowhere
768                // to stand.
769                "barLine" => {
770                    let _ = barline_of(held.get("rend").unwrap_or("single"))?;
771                }
772                _ => {}
773            }
774        }
775        Ok(things)
776    }
777
778    /// music21's `tupletFromElement`.
779    fn tuplet_element(&mut self, element: &Xml) -> Result<Vec<Thing>> {
780        let (Some(number), Some(base)) = (element.get("num"), element.get("numbase")) else {
781            return Err(mei_error(
782                "Both @num and @numbase attributes are required on <tuplet> tags.",
783            ));
784        };
785        let read = |text: &str| -> Result<u32> {
786            text.parse()
787                .map_err(|_| mei_error(format!("a tuplet of {text:?} notes")))
788        };
789        let (number, base) = (read(number)?, read(base)?);
790        let mut members = self.contents(element, false)?;
791        for member in &mut members {
792            scale_to_tuplet(&mut member.element, number, base);
793        }
794        let sounding: Vec<usize> = (0..members.len())
795            .filter(|index| is_sounding(&members[*index].element))
796            .collect();
797        let first = *sounding
798            .first()
799            .ok_or_else(|| mei_error("a tuplet with no notes in it"))?;
800        mark_first_tuplet(&mut members[first].element, TupletType::Start);
801        let last = sounding.last().copied().filter(|last| *last != first);
802        mark_first_tuplet(
803            &mut members[last.unwrap_or(first)].element,
804            TupletType::Stop,
805        );
806        beam_together(&mut members)?;
807        Ok(members)
808    }
809
810    /// music21's `bTremFromElement`: notes played as repeated strokes.
811    fn tremolo(&mut self, element: &Xml) -> Result<Vec<Thing>> {
812        let mut things = Vec::new();
813        for held in &element.children {
814            match local(&held.tag) {
815                "chord" => things.push(self.chord(held)?),
816                "note" => things.push(self.note_thing(held)?),
817                _ => {}
818            }
819        }
820        let marks = match element.get("unitdur") {
821            Some("8") => Some(1),
822            Some("16") => Some(2),
823            Some("32") => Some(3),
824            Some("64") => Some(4),
825            Some("128") => Some(5),
826            Some("256") => Some(6),
827            Some("512") => Some(7),
828            Some("1024") => Some(8),
829            _ => None,
830        };
831        if let Some(marks) = marks {
832            for thing in &mut things {
833                let mut tremolo = Ornament::of_kind(OrnamentKind::Tremolo);
834                tremolo.set_number_of_marks(marks)?;
835                let expression = Expression::from(tremolo);
836                match &mut thing.element {
837                    StreamElement::Note(note) => note.expressions_mut().push(expression),
838                    StreamElement::Chord(chord) => chord.expressions_mut().push(expression),
839                    _ => {}
840                }
841            }
842        }
843        Ok(things)
844    }
845
846    /// music21's `layerFromElement`, with `_guessTuplets`: the notes between
847    /// the two a tuplet span names are in the tuplet too.
848    fn layer(&mut self, element: &Xml) -> Result<Vec<Thing>> {
849        let mut things = self.contents(element, true)?;
850        let mut active: Option<(u32, u32)> = None;
851        for thing in &mut things {
852            if !is_sounding(&thing.element) {
853                continue;
854            }
855            let search = thing.search.take();
856            if let Some(search) = &search
857                && search.end == "start"
858            {
859                active = Some((search.number, search.base));
860            }
861            if let Some((number, base)) = active {
862                scale_to_tuplet(&mut thing.element, number, base);
863                if search.is_some_and(|search| search.end == "end") {
864                    mark_first_tuplet(&mut thing.element, TupletType::Stop);
865                    active = None;
866                }
867            }
868        }
869        Ok(things)
870    }
871
872    /// music21's `staffDefFromElement`.
873    fn staff_def(&mut self, element: &Xml) -> Result<StaffDef> {
874        let instrument = match child(element, "instrDef") {
875            Some(definition) => Some(match definition.get("midi.instrnum") {
876                Some(number) => Instrument::from_midi_program(number.parse().map_err(|_| {
877                    mei_error(format!("the MIDI program {number:?} is no number"))
878                })?)?,
879                None => {
880                    let name = definition.get("midi.instrname");
881                    name.and_then(|name| Instrument::from_name(name, SearchLanguage::All).ok())
882                        .unwrap_or_else(|| {
883                            let mut generic = Instrument::new();
884                            generic.set_part_name(Some(name.unwrap_or("").to_string()));
885                            generic
886                        })
887                }
888            }),
889            None => {
890                Instrument::from_name(element.get("label").unwrap_or(""), SearchLanguage::All).ok()
891            }
892        };
893        let mut found = StaffDef {
894            instrument,
895            ..StaffDef::default()
896        };
897        if let Some(instrument) = &mut found.instrument {
898            instrument.set_part_name(element.get("label").map(str::to_string));
899            instrument.set_part_abbreviation(element.get("label.abbr").map(str::to_string));
900            instrument.set_part_id(element.get("n").map(str::to_string));
901        }
902        if element.get("trans.semi").is_some() {
903            found
904                .instrument
905                .get_or_insert_with(Instrument::new)
906                .set_transposition(Some(transposition_of(element)?));
907        }
908        if element.get("meter.count").is_some() {
909            found.meter = Some(meter_of(element)?);
910        }
911        if element.get("key.pname").is_some() || element.get("key.sig").is_some() {
912            found.key = Some(key_of(element)?);
913        }
914        if element.get("clef.shape").is_some() {
915            found.clef = Some(clef_of(
916                element.get("clef.shape"),
917                element.get("clef.line"),
918                element.get("clef.dis"),
919                element.get("clef.dis.place"),
920            )?);
921        }
922        for held in children(element, "clef") {
923            found.clef = Some(clef_element(held)?);
924        }
925        Ok(found)
926    }
927
928    /// music21's `measureFromElement`: a measure of every part.
929    fn measure(
930        &mut self,
931        element: &Xml,
932        backup: IntegerType,
933        parts: &[String],
934        meter: Option<&TimeSignature>,
935    ) -> Result<(HashMap<String, Measure>, Option<Barline>)> {
936        let number = match element.get("n") {
937            Some(number) => number
938                .parse()
939                .map_err(|_| mei_error(format!("the measure number {number:?} is no number")))?,
940            None => backup,
941        };
942        let mut staves: HashMap<String, Measure> = HashMap::new();
943        let mut waiting: Vec<(String, StaffDef)> = Vec::new();
944        let mut longest: Option<FloatType> = None;
945        for held in &element.children {
946            match local(&held.tag) {
947                "staff" => {
948                    let mut voices = Vec::new();
949                    for (count, layer) in children(held, "layer").enumerate() {
950                        voices.push(((count + 1).to_string(), self.layer(layer)?));
951                    }
952                    let length = voices
953                        .iter()
954                        .map(|(_, things)| {
955                            things
956                                .iter()
957                                .map(|thing| thing.element.quarter_length())
958                                .sum::<FloatType>()
959                        })
960                        .fold(0.0, FloatType::max);
961                    longest = Some(longest.map_or(length, |held| held.max(length)));
962                    staves.insert(
963                        held.get("n").unwrap_or("").to_string(),
964                        Measure {
965                            number,
966                            voices,
967                            own: Vec::new(),
968                            left: None,
969                            right: None,
970                            length: None,
971                        },
972                    );
973                }
974                "staffDef" => {
975                    if let Some(name) = held.get("n") {
976                        waiting.push((name.to_string(), self.staff_def(held)?));
977                    }
978                }
979                _ => {}
980            }
981        }
982        for (name, definition) in waiting {
983            let measure = staves.get_mut(&name).ok_or_else(|| {
984                mei_error(format!("a <staffDef> for staff {name}, which is not here"))
985            })?;
986            measure.own.extend(definition.elements());
987        }
988        // A part with nothing written for this measure rests through it.
989        for name in parts {
990            if !staves.contains_key(name) {
991                let length = longest.ok_or_else(|| mei_error("a measure with no staff in it"))?;
992                staves.insert(
993                    name.clone(),
994                    Measure {
995                        number,
996                        voices: vec![(
997                            "1".to_string(),
998                            vec![Thing {
999                                element: Rest::new(Duration::new(length)?).into(),
1000                                uid: self.uid(),
1001                                search: None,
1002                                whole_measure: true,
1003                            }],
1004                        )],
1005                        own: Vec::new(),
1006                        left: None,
1007                        right: None,
1008                        length: None,
1009                    },
1010                );
1011            }
1012        }
1013        // A measure rest lasts as long as the longest staff, or the bar
1014        // where no staff says.
1015        let target = match (longest, meter) {
1016            (Some(longest), Some(meter))
1017                if longest == step::NO_DURATION && longest != meter.bar_quarter_length() =>
1018            {
1019                Some(meter.bar_quarter_length())
1020            }
1021            (longest, _) => longest,
1022        };
1023        if let Some(target) = target {
1024            for measure in staves.values_mut() {
1025                for (_, things) in &mut measure.voices {
1026                    for thing in things {
1027                        if std::mem::take(&mut thing.whole_measure) {
1028                            let duration = Duration::new(target)?;
1029                            with_duration(&mut thing.element, |held| *held = duration);
1030                            measure.length = Some(target);
1031                        }
1032                    }
1033                }
1034            }
1035        }
1036        let mut next_left = None;
1037        if let Some(left) = element.get("left") {
1038            let (first, second) = barline_of(left)?;
1039            let barline = second.unwrap_or(first);
1040            for measure in staves.values_mut() {
1041                measure.left = Some(barline.clone());
1042            }
1043        }
1044        if let Some(right) = element.get("right") {
1045            let (barline, next) = barline_of(right)?;
1046            next_left = next;
1047            for measure in staves.values_mut() {
1048                measure.right = Some(barline.clone());
1049            }
1050        }
1051        Ok((staves, next_left))
1052    }
1053
1054    /// music21's `sectionScoreCore`: what a `<score>` or a `<section>`
1055    /// holds, part by part.
1056    fn section(
1057        &mut self,
1058        element: &Xml,
1059        parts: &[String],
1060        state: &mut SectionState,
1061    ) -> Result<HashMap<String, Vec<Held>>> {
1062        let in_section = local(&element.tag) == "section";
1063        let mut parsed: HashMap<String, Vec<Held>> = parts
1064            .iter()
1065            .map(|name| (name.clone(), Vec::new()))
1066            .collect();
1067        let mut next: HashMap<String, Vec<StreamElement>> = parts
1068            .iter()
1069            .map(|name| (name.clone(), Vec::new()))
1070            .collect();
1071        for held in &element.children {
1072            match local(&held.tag) {
1073                "measure" if in_section => {
1074                    state.backup += 1;
1075                    let (mut staves, next_left) =
1076                        self.measure(held, state.backup, parts, state.meter.as_ref())?;
1077                    for name in parts {
1078                        let measure = staves
1079                            .get_mut(name)
1080                            .ok_or_else(|| mei_error(format!("no staff {name} in a measure")))?;
1081                        measure
1082                            .own
1083                            .extend(std::mem::take(next.entry(name.clone()).or_default()));
1084                        if let Some(left) = &state.next_left {
1085                            measure.left = Some(left.clone());
1086                        }
1087                        if let Some(measure) = staves.remove(name) {
1088                            parsed
1089                                .entry(name.clone())
1090                                .or_default()
1091                                .push(Held::Measure(Box::new(measure)));
1092                        }
1093                    }
1094                    state.next_left = next_left;
1095                }
1096                "scoreDef" => {
1097                    let mut everywhere: Vec<StreamElement> = Vec::new();
1098                    if held.get("meter.count").is_some() {
1099                        let meter = meter_of(held)?;
1100                        state.meter = Some(meter.clone());
1101                        everywhere.push(meter.into());
1102                    }
1103                    if held.get("key.pname").is_some() || held.get("key.sig").is_some() {
1104                        everywhere.push(StreamElement::Key(key_of(held)?));
1105                    }
1106                    let mut definitions: Vec<&Xml> = Vec::new();
1107                    for group in children(held, "staffGrp") {
1108                        descendants_in_groups(group, &mut definitions);
1109                    }
1110                    let mut own: HashMap<String, StaffDef> = HashMap::new();
1111                    for definition in definitions {
1112                        own.insert(
1113                            definition.get("n").unwrap_or("").to_string(),
1114                            self.staff_def(definition)?,
1115                        );
1116                    }
1117                    for name in parts {
1118                        let waiting = next.entry(name.clone()).or_default();
1119                        waiting.extend(everywhere.iter().cloned());
1120                        if let Some(definition) = own.get(name) {
1121                            waiting.extend(definition.elements());
1122                        }
1123                    }
1124                }
1125                "staffDef" => {
1126                    if let Some(name) = held.get("n") {
1127                        let definition = self.staff_def(held)?;
1128                        if let Some(meter) = &definition.meter {
1129                            state.meter = Some(meter.clone());
1130                        }
1131                        next.get_mut(name)
1132                            .ok_or_else(|| mei_error(format!("a <staffDef> for no part: {name}")))?
1133                            .extend(definition.elements());
1134                    }
1135                }
1136                "section" => {
1137                    let inner = self.section(held, parts, state)?;
1138                    for name in parts {
1139                        let mut list = inner.get(name).cloned().unwrap_or_default();
1140                        let mut waiting = std::mem::take(next.entry(name.clone()).or_default());
1141                        if !waiting.is_empty() {
1142                            // The instrument stands before the measures, and
1143                            // the rest at the start of the first of them.
1144                            if let Some(at) = waiting
1145                                .iter()
1146                                .position(|thing| matches!(thing, StreamElement::Instrument(_)))
1147                                && let StreamElement::Instrument(instrument) = waiting.remove(at)
1148                            {
1149                                list.insert(0, Held::Instrument(instrument));
1150                            }
1151                            if let Some(Held::Measure(first)) = list
1152                                .iter_mut()
1153                                .find(|thing| matches!(thing, Held::Measure(_)))
1154                            {
1155                                first.own.extend(waiting);
1156                            }
1157                        }
1158                        parsed.entry(name.clone()).or_default().extend(list);
1159                    }
1160                }
1161                _ => {}
1162            }
1163        }
1164        Ok(parsed)
1165    }
1166}
1167
1168/// What carries from one section to the next: the meter in force, the
1169/// barline the next measure opens with, and the measure count.
1170#[derive(Default)]
1171struct SectionState {
1172    meter: Option<TimeSignature>,
1173    next_left: Option<Barline>,
1174    backup: IntegerType,
1175}
1176
1177/// The `<staffDef>`s of a group and of the groups inside it.
1178fn descendants_in_groups<'a>(group: &'a Xml, out: &mut Vec<&'a Xml>) {
1179    for held in &group.children {
1180        match local(&held.tag) {
1181            "staffDef" => out.push(held),
1182            "staffGrp" => descendants_in_groups(held, out),
1183            _ => {}
1184        }
1185    }
1186}
1187
1188fn beam_type_of(text: &str) -> Result<BeamType> {
1189    match text {
1190        "start" => Ok(BeamType::Start),
1191        "continue" => Ok(BeamType::Continue),
1192        "stop" => Ok(BeamType::Stop),
1193        other => Err(mei_error(format!("a beam that does {other:?}"))),
1194    }
1195}
1196
1197/// music21's `sylFromElement`: a syllable, with the hyphen its place in the
1198/// word gives it.
1199fn syllable_of(element: &Xml) -> Result<Lyric> {
1200    let text = element
1201        .text()
1202        .ok_or_else(|| mei_error("a <syl> with no text"))?;
1203    let (text, syllabic) = step::syllable(text, element.get("wordpos"), element.get("con"))?;
1204    Ok(match syllabic {
1205        Some(syllabic) => {
1206            let mut lyric = Lyric::new(text);
1207            lyric.set_syllabic(syllabic);
1208            lyric
1209        }
1210        None => Lyric::from_raw_text(&text),
1211    })
1212}
1213
1214/// music21's `makeMetadata`: the title, composer and date of the first
1215/// `<work>`.
1216fn metadata_of(root: &Xml) -> Metadata {
1217    let mut metadata = Metadata::new();
1218    let mut works = Vec::new();
1219    descendants(root, "work", &mut works);
1220    let Some(work) = works.first() else {
1221        return metadata;
1222    };
1223    let statement = child(work, "titleStmt");
1224    let mut title: Option<String> = None;
1225    let mut subtitle: Option<String> = None;
1226    for held in statement
1227        .into_iter()
1228        .flat_map(|held| children(held, "title"))
1229    {
1230        let text = held.text().map(str::to_string);
1231        if held.get("type") == Some("subtitle") {
1232            subtitle = text;
1233        } else if title.is_none() {
1234            title = text;
1235        }
1236    }
1237    if let Some(subtitle) = subtitle.filter(|subtitle| !subtitle.is_empty()) {
1238        title = Some(format!(
1239            "{} ({subtitle})",
1240            title.as_deref().unwrap_or("None")
1241        ));
1242    }
1243    if let Some(title) = title {
1244        metadata.add_text("title", title);
1245    }
1246    if let Some(tempo) = child(work, "tempo") {
1247        metadata.add_text("movementName", tempo.text().unwrap_or("None"));
1248    }
1249    let mut composers: Vec<String> = Vec::new();
1250    if let Some(statement) = statement {
1251        for responsibility in children(statement, "respStmt") {
1252            for person in children(responsibility, "persName") {
1253                if person.get("role") == Some("composer")
1254                    && let Some(text) = person.text().filter(|text| !text.is_empty())
1255                {
1256                    composers.push(text.to_string());
1257                }
1258            }
1259        }
1260        for composer in children(statement, "composer") {
1261            let text = composer
1262                .text()
1263                .filter(|text| !text.is_empty())
1264                .or_else(|| child(composer, "persName").and_then(Xml::text));
1265            if let Some(text) = text.filter(|text| !text.is_empty()) {
1266                composers.push(text.to_string());
1267            }
1268        }
1269    }
1270    for composer in composers {
1271        metadata.add_contributor("composer", composer);
1272    }
1273    let date = child(work, "history")
1274        .and_then(|history| child(history, "creation"))
1275        .and_then(|creation| child(creation, "date"));
1276    if let Some(date) = date {
1277        let written = date
1278            .get("isodate")
1279            .filter(|text| !text.is_empty())
1280            .or(date.text().filter(|text| !text.is_empty()));
1281        // A date as music21 writes one: year, month and day, with two
1282        // hyphens for what is not said.
1283        let said = |written: &str| -> Option<String> {
1284            let parts: Vec<&str> = written.split(['-', '/']).collect();
1285            if parts.len() > 3 {
1286                return None;
1287            }
1288            let mut fields = Vec::new();
1289            for (index, part) in parts.iter().enumerate() {
1290                let number: u32 = part.parse().ok()?;
1291                fields.push(if index == 0 {
1292                    format!("{number:04}")
1293                } else {
1294                    format!("{number:02}")
1295                });
1296            }
1297            fields.resize(3, "--".to_string());
1298            Some(fields.join("/"))
1299        };
1300        if let Some(written) = written {
1301            if let Some(date) = said(written) {
1302                metadata.add_text("dateCreated", date);
1303            }
1304        } else {
1305            let start = date.get("notbefore").or(date.get("startdate"));
1306            let end = date.get("notafter").or(date.get("enddate"));
1307            if let (Some(start), Some(end)) = (start, end)
1308                && let (Some(start), Some(end)) = (said(start), said(end))
1309            {
1310                metadata.add_text("dateCreated", format!("{start} to {end}"));
1311            }
1312        }
1313    }
1314    metadata
1315}
1316
1317/// Reads an MEI document into a score: music21's `converter.parse` of one.
1318///
1319/// Every `<staffDef>` number is a part. A measure holds a voice for each
1320/// `<layer>`; a part with no staff in a measure rests through it, and a
1321/// measure rest lasts what the longest staff of its measure lasts. Beams,
1322/// tuplets, ties and slurs are read where they are written on the notes and
1323/// where they stand apart and name the notes by `xml:id`.
1324///
1325/// The text is the document's own, already decoded: the library opens no
1326/// file. A barline written inside a layer is passed over.
1327///
1328/// ```
1329/// use music21::mei::from_mei;
1330///
1331/// let score = from_mei(
1332///     r#"<mei xmlns="http://www.music-encoding.org/ns/mei"><music><score>
1333///     <scoreDef meter.count="2" meter.unit="4">
1334///       <staffGrp><staffDef n="1" clef.shape="G" clef.line="2"/></staffGrp>
1335///     </scoreDef>
1336///     <section><measure n="1"><staff n="1"><layer n="1">
1337///       <note pname="c" oct="4" dur="4"/><note pname="e" oct="4" dur="4" accid="f"/>
1338///     </layer></staff></measure></section>
1339///     </score></music></mei>"#,
1340/// )?;
1341/// let names: Vec<String> = score.parts()[0]
1342///     .pitches()
1343///     .iter()
1344///     .map(|pitch| pitch.name_with_octave())
1345///     .collect();
1346/// assert_eq!(names, ["C4", "Eb4"]);
1347/// # Ok::<(), music21::Error>(())
1348/// ```
1349pub fn from_mei(document: &str) -> Result<Stream> {
1350    // music21's words for it, at the place the XML reader stopped.
1351    let root = Xml::parse(document).map_err(|read| {
1352        let refused =
1353            mei_error("MEI document is not valid XML.").of_kind(FormatErrorKind::Malformed);
1354        match read.position() {
1355            Some(position) => refused.placed(|| position.clone()),
1356            None => refused,
1357        }
1358    })?;
1359    if local(&root.tag) != "mei" {
1360        return Err(mei_error(format!(
1361            "Root element should be <mei> in the MEI namespace, not <{}>.",
1362            root.tag
1363        )));
1364    }
1365    let score = child(&root, "music")
1366        .and_then(|music| {
1367            let mut found = Vec::new();
1368            descendants(music, "score", &mut found);
1369            found.first().copied()
1370        })
1371        .ok_or_else(|| mei_error("an MEI document with no <score> in its <music>"))?;
1372
1373    let mut reader = Reader {
1374        extra: HashMap::new(),
1375        slurs: Vec::new(),
1376        next_uid: 0,
1377        next_slur: 0,
1378    };
1379    reader.preprocess(score);
1380
1381    // music21's `allPartsPresent`: every staff number, in the order met.
1382    let mut definitions = Vec::new();
1383    descendants(score, "staffDef", &mut definitions);
1384    let mut parts: Vec<String> = Vec::new();
1385    for definition in definitions {
1386        let name = definition.get("n").unwrap_or("").to_string();
1387        if !parts.contains(&name) {
1388            parts.push(name);
1389        }
1390    }
1391    if parts.is_empty() {
1392        return Err(mei_error(
1393            "There appear to be no <staffDef> tags in this score.",
1394        ));
1395    }
1396
1397    let mut state = SectionState::default();
1398    let parsed = reader.section(score, &parts, &mut state)?;
1399
1400    // The parts, and the place among the score's leaves of every note a
1401    // slur may name.
1402    let mut events = Vec::new();
1403    let mut uids: Vec<Option<usize>> = Vec::new();
1404    // Where the longest part ends, which is where music21 appends the
1405    // slurs to the score.
1406    let mut end: FloatType = 0.0;
1407    for name in &parts {
1408        let mut held = Vec::new();
1409        let mut offset = 0.0;
1410        for thing in parsed.get(name).cloned().unwrap_or_default() {
1411            match thing {
1412                Held::Instrument(instrument) => {
1413                    uids.push(None);
1414                    held.push(StreamEvent::new(offset, *instrument));
1415                }
1416                Held::Measure(measure) => {
1417                    // What stands at the start sorts by its class, ahead of
1418                    // the voices.
1419                    let mut own: Vec<StreamEvent> = measure
1420                        .own
1421                        .into_iter()
1422                        .map(|element| StreamEvent::new(0.0, element))
1423                        .collect();
1424                    own.sort_by_key(|event| event.element().class_sort_order());
1425                    uids.extend(own.iter().map(|_| None));
1426                    let mut length: FloatType = 0.0;
1427                    for (id, things) in measure.voices {
1428                        let mut at = 0.0;
1429                        let mut inner = Vec::new();
1430                        for thing in things {
1431                            uids.push(Some(thing.uid));
1432                            let lasts = thing.element.quarter_length();
1433                            inner.push(StreamEvent::new(at, thing.element));
1434                            at = op_frac(at + lasts);
1435                        }
1436                        length = length.max(at);
1437                        let mut voice = Stream::with_kind(StreamKind::Voice).with_events(inner);
1438                        voice.set_id(Some(id));
1439                        own.push(StreamEvent::new(0.0, voice));
1440                    }
1441                    let mut stream = Stream::with_kind(StreamKind::Measure).with_events(own);
1442                    stream.set_number(measure.number);
1443                    stream.set_left_barline(measure.left);
1444                    stream.set_right_barline(measure.right);
1445                    held.push(StreamEvent::new(offset, stream));
1446                    offset = op_frac(offset + measure.length.unwrap_or(length));
1447                }
1448            }
1449        }
1450        end = end.max(offset);
1451        let mut part = Stream::with_kind(StreamKind::Part).with_events(held);
1452        // music21 says an MEI part is at written pitch.
1453        part.set_at_sounding_pitch(Some(false));
1454        events.push(StreamEvent::new(0.0, part));
1455    }
1456    let mut made = Stream::with_kind(StreamKind::Score).with_events(events);
1457    made.set_metadata(Some(metadata_of(&root)));
1458    for (name, joined) in reader.slurs {
1459        let positions: Vec<Option<usize>> = joined
1460            .iter()
1461            .map(|uid| uids.iter().position(|held| *held == Some(*uid)))
1462            .collect();
1463        let mut slur = Spanner::with_unplaced(SpannerKind::Slur, positions);
1464        slur.set_id_local(Some(name));
1465        slur.set_stands_in_score(true);
1466        slur.set_offset(end);
1467        made.add_spanner(slur);
1468    }
1469    Ok(made)
1470}
1471
1472#[cfg(test)]
1473mod tests {
1474    use super::*;
1475    use crate::notation::TieType;
1476
1477    fn document(body: &str) -> String {
1478        format!(
1479            r#"<mei xmlns="http://www.music-encoding.org/ns/mei"><music><score>
1480            <scoreDef meter.count="4" meter.unit="4"><staffGrp>
1481            <staffDef n="1" clef.shape="G" clef.line="2"/>
1482            <staffDef n="2" clef.shape="F" clef.line="4"/>
1483            </staffGrp></scoreDef><section>{body}</section></score></music></mei>"#
1484        )
1485    }
1486
1487    #[test]
1488    fn a_transposition_past_any_interval_is_refused() {
1489        for (steps, semitones) in [
1490            ("2147483647", "0"),
1491            ("-2147483648", "0"),
1492            ("0", "-2147483648"),
1493            ("-2147483648", "2147483647"),
1494        ] {
1495            let written = format!("<staffDef trans.diat=\"{steps}\" trans.semi=\"{semitones}\"/>");
1496            let staff = Xml::parse(&written).unwrap();
1497            assert!(transposition_of(&staff).is_err(), "{written}");
1498        }
1499        let staff = Xml::parse("<staffDef trans.diat=\"-1\" trans.semi=\"-2\"/>").unwrap();
1500        assert_eq!(transposition_of(&staff).unwrap().directed_name(), "M-2");
1501    }
1502
1503    #[test]
1504    fn a_staff_with_nothing_written_rests_through_the_measure() {
1505        let score = from_mei(&document(
1506            r#"<measure n="1"><staff n="1"><layer n="1">
1507            <note pname="c" oct="4" dur="2"/><note pname="d" oct="4" dur="2"/>
1508            </layer></staff></measure>"#,
1509        ))
1510        .unwrap();
1511        let parts = score.parts();
1512        assert_eq!(parts.len(), 2);
1513        let rests: Vec<FloatType> = parts[1]
1514            .recurse()
1515            .into_iter()
1516            .filter(|(_, element)| matches!(element, StreamElement::Rest(_)))
1517            .map(|(_, element)| element.quarter_length())
1518            .collect();
1519        assert_eq!(rests, [4.0]);
1520    }
1521
1522    #[test]
1523    fn a_beam_runs_from_its_first_note_to_its_last() {
1524        let score = from_mei(&document(
1525            r#"<measure n="1"><staff n="1"><layer n="1"><beam>
1526            <note pname="c" oct="4" dur="8"/><note pname="d" oct="4" dur="8"/>
1527            <note pname="e" oct="4" dur="8"/></beam></layer></staff>
1528            <staff n="2"><layer n="1"><mRest/></layer></staff></measure>"#,
1529        ))
1530        .unwrap();
1531        let beams: Vec<Option<BeamType>> = score.parts()[0]
1532            .recurse()
1533            .into_iter()
1534            .filter_map(|(_, element)| match element {
1535                StreamElement::Note(note) => {
1536                    Some(note.beams().by_number(1).and_then(|beam| beam.beam_type()))
1537                }
1538                _ => None,
1539            })
1540            .collect();
1541        assert_eq!(
1542            beams,
1543            [
1544                Some(BeamType::Start),
1545                Some(BeamType::Continue),
1546                Some(BeamType::Stop)
1547            ]
1548        );
1549    }
1550
1551    #[test]
1552    fn a_tuplet_scales_its_notes_and_brackets_them() {
1553        let score = from_mei(&document(
1554            r#"<measure n="1"><staff n="1"><layer n="1"><tuplet num="3" numbase="2">
1555            <note pname="c" oct="4" dur="4"/><note pname="d" oct="4" dur="4"/>
1556            <note pname="e" oct="4" dur="4"/></tuplet></layer></staff></measure>"#,
1557        ))
1558        .unwrap();
1559        let lengths: Vec<FloatType> = score.parts()[0]
1560            .notes()
1561            .into_iter()
1562            .map(|(_, element)| element.quarter_length())
1563            .collect();
1564        assert_eq!(lengths.len(), 3);
1565        assert!(
1566            lengths
1567                .iter()
1568                .all(|length| (length - 2.0 / 3.0).abs() < 1e-9)
1569        );
1570    }
1571
1572    #[test]
1573    fn a_tie_written_apart_names_its_notes() {
1574        let score = from_mei(&document(
1575            r##"<measure n="1"><staff n="1"><layer n="1">
1576            <note xml:id="a" pname="c" oct="4" dur="2"/><note xml:id="b" pname="c" oct="4" dur="2"/>
1577            </layer></staff><tie startid="#a" endid="#b"/></measure>"##,
1578        ))
1579        .unwrap();
1580        let ties: Vec<Option<TieType>> = score.parts()[0]
1581            .notes()
1582            .into_iter()
1583            .filter_map(|(_, element)| match element {
1584                StreamElement::Note(note) => Some(note.tie().map(Tie::tie_type)),
1585                _ => None,
1586            })
1587            .collect();
1588        assert_eq!(ties, [Some(TieType::Start), Some(TieType::Stop)]);
1589    }
1590
1591    #[test]
1592    fn a_chord_and_a_rest_keep_their_ids() {
1593        let score = from_mei(&document(
1594            r#"<measure n="1"><staff n="1"><layer n="1">
1595            <chord xml:id="c1" dur="2"><note pname="c" oct="4"/><note pname="e" oct="4"/></chord>
1596            <rest xml:id="r1" dur="2"/></layer></staff></measure>"#,
1597        ))
1598        .unwrap();
1599        let ids: Vec<Option<&str>> = score.parts()[0]
1600            .recurse()
1601            .into_iter()
1602            .filter_map(|(_, element)| match element {
1603                StreamElement::Chord(chord) => Some(chord.id()),
1604                StreamElement::Rest(rest) => Some(rest.id()),
1605                _ => None,
1606            })
1607            .collect();
1608        assert_eq!(ids, [Some("c1"), Some("r1")]);
1609    }
1610
1611    #[test]
1612    fn slurs_stand_in_the_score_after_its_last_measure() {
1613        let score = from_mei(&document(
1614            r##"<measure n="1"><staff n="1"><layer n="1">
1615            <note xml:id="a" pname="c" oct="4" dur="2" slur="1i"/>
1616            <note xml:id="b" pname="d" oct="4" dur="2" slur="1t"/>
1617            </layer></staff><slur startid="#a" endid="#b"/></measure>"##,
1618        ))
1619        .unwrap();
1620        let slurs = score.spanners();
1621        assert_eq!(slurs.len(), 2);
1622        assert!(slurs.iter().all(Spanner::stands_in_score));
1623        assert!(slurs.iter().all(|slur| slur.offset() == 4.0));
1624        // One written apart is named afresh each read, as music21 names it
1625        // with a random UUID; one written on its notes keeps its number.
1626        let apart = slurs[0].id_local().unwrap();
1627        assert_eq!(apart.len(), 36);
1628        assert_eq!(apart.as_bytes()[14], b'4');
1629        assert_eq!(slurs[1].id_local(), Some("1"));
1630    }
1631
1632    /// music21 makes an MEI grace note's duration from its length, which
1633    /// leaves the way it is written inferred, where the note's own `dur`
1634    /// was written.
1635    #[test]
1636    fn a_grace_notes_value_is_inferred() {
1637        let score = from_mei(&document(
1638            r#"<measure n="1"><staff n="1"><layer n="1">
1639            <note pname="c" oct="4" dur="8" grace="unacc"/><note pname="d" oct="4" dur="1"/>
1640            </layer></staff></measure>"#,
1641        ))
1642        .unwrap();
1643        let inferred: Vec<bool> = score.parts()[0]
1644            .notes()
1645            .into_iter()
1646            .filter_map(|(_, element)| element.duration().map(Duration::expression_is_inferred))
1647            .collect();
1648        assert_eq!(inferred, [true, false]);
1649    }
1650
1651    #[test]
1652    fn what_is_no_mei_is_refused() {
1653        assert!(from_mei("<score-partwise/>").is_err());
1654        assert!(from_mei("not xml at all").is_err());
1655    }
1656
1657    fn with_key(attributes: &str) -> String {
1658        format!(
1659            r#"<mei xmlns="http://www.music-encoding.org/ns/mei"><music><score>
1660            <scoreDef meter.count="4" meter.unit="4"><staffGrp>
1661            <staffDef n="1" clef.shape="G" clef.line="2" {attributes}/>
1662            </staffGrp></scoreDef><section><measure n="1"><staff n="1"><layer n="1">
1663            <note pname="c" oct="4" dur="1"/></layer></staff></measure></section>
1664            </score></music></mei>"#
1665        )
1666    }
1667
1668    #[test]
1669    fn a_key_in_a_mode_music21_has_no_scale_for_is_refused() {
1670        assert!(from_mei(&with_key(r#"key.pname="c" key.mode="dorian""#)).is_ok());
1671        assert!(
1672            from_mei(&with_key(
1673                r#"key.pname="c" key.mode='major #(system "touch x") %'"#
1674            ))
1675            .is_err()
1676        );
1677    }
1678
1679    #[test]
1680    fn a_key_signature_with_no_count_is_refused() {
1681        assert!(from_mei(&with_key(r#"key.sig="2s""#)).is_ok());
1682        for signature in ["", "és", "x"] {
1683            assert!(
1684                from_mei(&with_key(&format!(r#"key.sig="{signature}""#))).is_err(),
1685                "{signature:?}"
1686            );
1687        }
1688    }
1689}