Skip to main content

music21/musicxml/
step.rs

1//! music21's per-element steps of reading MusicXML: what its
2//! `MeasureParser` makes of one `<clef>`, one `<note>`, one `<measure>`.
3//!
4//! Each takes the element's text and reads it as the whole-document reader
5//! reads it in place. A step that depends on what came before it in the
6//! measure -- a note's duration on the divisions in force, a rest on the
7//! measure it fills -- reads the element inside a measure of its own, so
8//! that the reader's own measure logic decides it.
9//!
10//! ```
11//! use music21::musicxml::step;
12//!
13//! let clef = step::read_clef("<clef><sign>F</sign><line>4</line></clef>")?;
14//! assert_eq!(clef.sign(), Some("F"));
15//!
16//! let measure = step::read_measure(
17//!     "<measure><note><pitch><step>D</step><octave>5</octave></pitch>\
18//!      <duration>2</duration><type>half</type></note></measure>",
19//!     &mut step::MeasureContext::with_divisions(2),
20//! )?;
21//! assert_eq!(measure.pitches()[0].name_with_octave(), "D5");
22//! # Ok::<(), music21::Error>(())
23//! ```
24
25use super::read;
26pub use super::read::{
27    ActiveTuplets, DuplicateIds, Encoding, FitAsked, MeasureFit, SpannerId, SpannerState,
28    SpannerStep, SpannersRead, measure_fit,
29};
30use crate::articulations::Articulation;
31use crate::bar::Barline;
32use crate::clef::Clef;
33use crate::defaults::IntegerType;
34use crate::error::{Error, Result};
35use crate::instrument::Instrument;
36use crate::interval::Interval;
37use crate::key::KeySignature;
38use crate::layout::{PageLayout, StaffLayout, SystemLayout};
39use crate::metadata::MetadataValue;
40use crate::meter::TimeSignature;
41use crate::notation::{Beams, Lyric, Tie};
42use crate::pitch::{Accidental, Pitch};
43use crate::stream::{Stream, StreamElement};
44use crate::style::StreamStyle;
45use crate::text::TextBox;
46use crate::xml::Xml;
47
48/// The score a lone measure or part is read inside: one part, with no name.
49const SCORE_SHELL: &str = "<score-partwise><part-list><score-part id=\"P1\"/></part-list>\
50                           <part id=\"P1\"/></score-partwise>";
51
52/// An element's text read as XML, refused unless its tag is `tag`.
53fn element(text: &str, tag: &str) -> Result<Xml> {
54    let read = Xml::parse(text)?;
55    if read.tag != tag {
56        return Err(Error::music_xml(format!(
57            "expected a <{tag}>, not a <{}>",
58            read.tag
59        )));
60    }
61    Ok(read)
62}
63
64/// music21's `xmlToClef`: a `<clef>`.
65pub fn read_clef(text: &str) -> Result<Clef> {
66    read::clef_of(&element(text, "clef")?)
67}
68
69/// music21's `xmlToKeySignature`: a `<key>`, as a key signature, or a key
70/// where it names a mode.
71pub fn read_key(text: &str) -> Result<StreamElement> {
72    read::key_signature(&element(text, "key")?)
73}
74
75/// music21's `updateVoiceInformation`: the voices a `<measure>`'s notes
76/// and forwards are written in, sorted.
77pub fn read_voice_ids(text: &str) -> Result<Vec<String>> {
78    Ok(read::voice_ids(&element(text, "measure")?))
79}
80
81/// music21's `nonTraditionalKeySignature`: a `<key>` of steps and their
82/// alterations, its octaves read too.
83pub fn read_non_traditional_key(text: &str) -> Result<KeySignature> {
84    let written = element(text, "key")?;
85    let mut signature = read::non_traditional_key(&written)?;
86    read::key_octaves(&written, &mut signature)?;
87    Ok(signature)
88}
89
90/// music21's `mxKeyOctaves`: the octaves a `<key>`'s `<key-octave>`s put
91/// `signature`'s altered pitches in.
92pub fn read_key_octaves(text: &str, signature: &mut KeySignature) -> Result<()> {
93    read::key_octaves(&element(text, "key")?, signature)
94}
95
96/// music21's `xmlToTimeSignature`: a `<time>`; `None` for one that only
97/// hides the meter.
98pub fn read_time(text: &str) -> Result<Option<TimeSignature>> {
99    read::time_signature(&element(text, "time")?)
100}
101
102/// The text of a `<time>` of no meter, where it is one: what music21
103/// reads as a `SenzaMisuraTimeSignature`.
104pub fn read_senza_misura(text: &str) -> Result<Option<String>> {
105    Ok(read::senza_misura(&element(text, "time")?))
106}
107
108/// music21's `xmlStaffLayoutFromStaffDetails`: a `<staff-details>`
109/// written into `layout`.
110pub fn read_staff_details(text: &str, layout: &mut StaffLayout) -> Result<()> {
111    read::read_staff_details(&Xml::parse(text)?, layout);
112    Ok(())
113}
114
115/// music21's `xmlTransposeToInterval`: a `<transpose>`.
116pub fn read_transpose(text: &str) -> Result<Interval> {
117    read::transpose_interval(&element(text, "transpose")?)
118}
119
120/// music21's `xmlToTempoIndication`: a `<metronome>`.
121pub fn read_metronome(text: &str) -> Result<StreamElement> {
122    read::metronome(&element(text, "metronome")?, None)
123}
124
125/// music21's `xmlToPitch`: the pitch of a `<note>`, C4 where it has none.
126pub fn read_pitch(text: &str) -> Result<Pitch> {
127    read::pitch_of(&element(text, "note")?)
128}
129
130/// music21's `xmlToAccidental`: an `<accidental>`, or an alteration
131/// written by another tag's text.
132pub fn read_accidental(text: &str) -> Result<Accidental> {
133    read::accidental_of(&Xml::parse(text)?)
134}
135
136/// music21's `xmlToTie`: the tie of a `<note>`, where it has one.
137pub fn read_tie(text: &str) -> Result<Option<Tie>> {
138    Ok(read::tie_of(&element(text, "note")?))
139}
140
141/// music21's `xmlToBeams`: `<beam>`s, in order.
142pub fn read_beams(texts: &[&str]) -> Result<Beams> {
143    let read: Vec<Xml> = texts
144        .iter()
145        .map(|text| element(text, "beam"))
146        .collect::<Result<_>>()?;
147    let written: Vec<&Xml> = read.iter().collect();
148    read::beams_of(&written)
149}
150
151/// music21's `xmlToLyric`: a `<lyric>`.
152pub fn read_lyric(text: &str) -> Result<Lyric> {
153    read::lyric_of(&element(text, "lyric")?)
154}
155
156/// music21's `updateLyricsFromList`: `<lyric>`s of one note, one numbered
157/// nought taking its place among them.
158pub fn read_lyrics(texts: &[&str]) -> Result<Vec<Lyric>> {
159    let read: Vec<Xml> = texts
160        .iter()
161        .map(|text| element(text, "lyric"))
162        .collect::<Result<_>>()?;
163    read::lyrics_from(read.iter())
164}
165
166/// music21's `xmlToArticulation`: one mark of `<articulations>`, `None`
167/// for one music21 does not know.
168pub fn read_articulation(text: &str) -> Result<Option<Articulation>> {
169    Ok(read::articulation_of(&Xml::parse(text)?))
170}
171
172/// music21's `xmlTechnicalToArticulation`: one mark of `<technical>`,
173/// `None` for one music21 does not know; a bend's release is read in
174/// `divisions` to the quarter.
175pub fn read_technical(
176    text: &str,
177    divisions: crate::defaults::FloatType,
178) -> Result<Option<Articulation>> {
179    Ok(read::technical_of(&Xml::parse(text)?, divisions))
180}
181
182/// music21's `xmlToBarline` and `xmlToRepeat`: what a `<barline>` draws,
183/// a repeat in the direction written.
184pub fn read_barline(text: &str) -> Result<Barline> {
185    read::barline_of(&element(text, "barline")?)
186}
187
188/// One of music21's spanner-reading steps on an element -- a direction
189/// type, a `<notations>`, or one slur or other spanner mark -- within
190/// `state`, which keeps the spanners from one to the next. `target`, a
191/// uid of the state's, is the note it joins or ends a spanner with.
192pub fn read_spanners(
193    text: &str,
194    target: Option<usize>,
195    step: SpannerStep,
196    state: &mut SpannerState,
197) -> Result<SpannersRead> {
198    read::spanners_within(&Xml::parse(text)?, target, step, state)
199}
200
201/// music21's `creatorToContributor`: a `<creator>`, its type its role.
202pub fn read_creator(text: &str) -> Result<MetadataValue> {
203    Ok(read::creator_value(&element(text, "creator")?))
204}
205
206/// music21's `rightsToCopyright`: a `<rights>`, its type its role.
207pub fn read_rights(text: &str) -> Result<MetadataValue> {
208    Ok(read::rights_value(&element(text, "rights")?))
209}
210
211/// music21's `xmlCreditToTextBox`: a `<credit>`.
212pub fn read_credit(text: &str) -> Result<TextBox> {
213    read::text_box(&element(text, "credit")?)
214}
215
216/// music21's `styleFromXmlDefaults`: the appearance, fonts and lyric
217/// languages a `<defaults>` gives.
218pub fn read_defaults_style(text: &str) -> Result<StreamStyle> {
219    read::stream_style(&element(text, "defaults")?)
220}
221
222/// music21's `xmlAppearanceToStyle`: an `<appearance>`.
223pub fn read_appearance(text: &str) -> Result<StreamStyle> {
224    let mut style = StreamStyle::default();
225    read::read_appearance(&element(text, "appearance")?, &mut style);
226    Ok(style)
227}
228
229/// music21's `getDefaultInstrument`: the instrument a `<score-part>`
230/// names, before the part's own names are put on it, and what music21
231/// warns of as it reads it.
232pub fn read_default_instrument(text: &str) -> Result<(Instrument, Vec<Error>)> {
233    let mut warnings = Vec::new();
234    let read = read::default_instrument(&element(text, "score-part")?, &mut warnings);
235    Ok((read, warnings))
236}
237
238/// music21's `getStaffNumber`: the staff an element is written on, nought
239/// where it does not say.
240pub fn read_staff(text: &str) -> Result<i32> {
241    Ok(read::staff_number(&Xml::parse(text)?))
242}
243
244/// music21's `processEncoding`: an `<encoding>`.
245pub fn read_encoding(text: &str) -> Result<Encoding> {
246    Ok(read::encoding_of(&element(text, "encoding")?))
247}
248
249/// music21's `xmlPrintToPageLayout`: the page a `<print>` starts.
250pub fn read_print_page(text: &str) -> Result<PageLayout> {
251    Ok(read::print_page_layout(&element(text, "print")?))
252}
253
254/// music21's `xmlPrintToSystemLayout`: the system a `<print>` starts.
255pub fn read_print_system(text: &str) -> Result<SystemLayout> {
256    Ok(read::print_system_layout(&element(text, "print")?))
257}
258
259/// music21's `xmlPageLayoutToPageLayout`: a `<page-layout>`.
260pub fn read_page_layout(text: &str) -> Result<PageLayout> {
261    let mut read = PageLayout::default();
262    read::read_page_layout(&element(text, "page-layout")?, &mut read);
263    Ok(read)
264}
265
266/// music21's `xmlSystemLayoutToSystemLayout`: a `<system-layout>`.
267pub fn read_system_layout(text: &str) -> Result<SystemLayout> {
268    let mut read = SystemLayout::default();
269    read::read_system_layout(&element(text, "system-layout")?, &mut read);
270    Ok(read)
271}
272
273/// music21's `xmlStaffLayoutToStaffLayout`: a `<staff-layout>`.
274pub fn read_staff_layout(text: &str) -> Result<StaffLayout> {
275    Ok(read::staff_layout(&element(text, "staff-layout")?))
276}
277
278/// What a `<measure>` read on its own is read within: what music21's
279/// `MeasureParser` takes from the measures before it.
280#[derive(Clone, Debug, Default, PartialEq)]
281pub struct MeasureContext {
282    /// The divisions to the quarter, where the measure sets none.
283    pub divisions: Option<IntegerType>,
284    /// The tuplets it starts inside, which reading leaves as it ends.
285    pub tuplets: ActiveTuplets,
286}
287
288impl MeasureContext {
289    /// A measure read with `divisions` to the quarter, inside no tuplet.
290    pub fn with_divisions(divisions: IntegerType) -> Self {
291        Self {
292            divisions: Some(divisions),
293            ..Self::default()
294        }
295    }
296}
297
298/// music21's `MeasureParser.parse`: a `<measure>`, read within `context`,
299/// whose tuplets it leaves as the measure ends.
300pub fn read_measure(text: &str, context: &mut MeasureContext) -> Result<Stream> {
301    let mut measure = element(text, "measure")?;
302    if let Some(divisions) = context.divisions {
303        let attributes = Xml::parse(&format!(
304            "<attributes><divisions>{divisions}</divisions></attributes>"
305        ))?;
306        measure.children.insert(0, attributes);
307    }
308
309    // Read as the only measure of a score's only part.
310    let mut root = Xml::parse(SCORE_SHELL)?;
311    if let Some(part) = root.children.iter_mut().find(|child| child.tag == "part") {
312        part.children.push(measure);
313    }
314    let score = read::score_within(&root, &mut context.tuplets)?;
315    let measure = score
316        .parts()
317        .first()
318        .and_then(|part| part.measures().first().map(|measure| (*measure).clone()));
319    measure.ok_or_else(|| Error::music_xml("a measure read to nothing"))
320}
321
322/// A part read, and what music21 warns of as it reads it.
323#[derive(Clone, Debug)]
324pub struct PartRead {
325    /// The part, or a part for each staff where it is written on several.
326    pub parts: Vec<Stream>,
327    /// What music21 warns of, in order: a percussion key outside the
328    /// General MIDI map, which is read as a bare unpitched instrument.
329    pub warnings: Vec<Error>,
330}
331
332/// music21's `PartParser.parse`: a `<part>` with its `<score-part>`.
333pub fn read_part(part: &str, score_part: Option<&str>) -> Result<PartRead> {
334    let part = element(part, "part")?;
335    let id = part.get("id").unwrap_or("P1").to_string();
336    // The score part is the part's, whatever id it was written with.
337    let mut score_part = match score_part {
338        Some(text) => element(text, "score-part")?,
339        None => Xml::parse("<score-part/>")?,
340    };
341    score_part.set("id", &id);
342    let mut root = Xml::parse(&format!(
343        "<score-partwise><part-list/><part id=\"{id}\"/></score-partwise>"
344    ))?;
345    root.children[0].children.push(score_part);
346    root.children[1] = part;
347    let (score, warnings) = read::score_warned(&root)?;
348    Ok(PartRead {
349        parts: score.parts().into_iter().cloned().collect(),
350        warnings,
351    })
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn a_clef_is_read_as_music21_reads_it() {
360        let clef = read_clef(
361            "<clef><sign>G</sign><line>2</line><clef-octave-change>-1</clef-octave-change></clef>",
362        )
363        .unwrap();
364        assert_eq!(clef.octave_change(), -1);
365    }
366
367    #[test]
368    fn an_element_of_another_tag_is_refused() {
369        assert!(read_clef("<key><fifths>2</fifths></key>").is_err());
370    }
371
372    #[test]
373    fn a_measure_takes_the_divisions_given() {
374        let measure = read_measure(
375            "<measure><note><rest/><duration>40320</duration></note></measure>",
376            &mut MeasureContext::with_divisions(10080),
377        )
378        .unwrap();
379        assert_eq!(measure.end_offset(), 4.0);
380    }
381
382    #[test]
383    fn a_part_on_two_staves_is_two_parts() {
384        let parts = read_part(
385            "<part id=\"P2\"><measure number=\"1\"><attributes><divisions>1</divisions>\
386             <staves>2</staves></attributes>\
387             <note><pitch><step>C</step><octave>5</octave></pitch><duration>4</duration>\
388             <staff>1</staff></note><backup><duration>4</duration></backup>\
389             <note><pitch><step>C</step><octave>3</octave></pitch><duration>4</duration>\
390             <staff>2</staff></note></measure></part>",
391            None,
392        )
393        .unwrap();
394        assert_eq!(parts.parts.len(), 2);
395    }
396
397    #[test]
398    fn an_encoding_says_who_wrote_it_and_what_it_marks() {
399        let read = read_encoding(
400            "<encoding><software>Finale v26.3 for Mac</software>\
401             <supports attribute=\"new-system\" element=\"print\" type=\"yes\" value=\"no\"/>\
402             <supports attribute=\"new-page\" element=\"print\" type=\"yes\"/></encoding>",
403        )
404        .unwrap();
405        assert!(read.finale);
406        assert!(!read.system_breaks);
407        assert!(read.page_breaks);
408        assert_eq!(read.software, vec!["Finale v26.3 for Mac".to_string()]);
409    }
410
411    #[test]
412    fn a_print_starts_a_page_and_a_system() {
413        let print = "<print new-page=\"yes\" page-number=\"5\"><page-layout>\
414                     <page-height>4000</page-height></page-layout>\
415                     <system-layout><system-distance>55</system-distance></system-layout></print>";
416        let page = read_print_page(print).unwrap();
417        assert_eq!(page.is_new, Some(true));
418        assert_eq!(page.page_number, Some(5));
419        let system = read_print_system(print).unwrap();
420        assert_eq!(system.is_new, None);
421        assert!(system.distance.is_some());
422    }
423
424    #[test]
425    fn a_tuplet_started_in_one_reading_stops_in_the_next() {
426        let note = |notations: &str| {
427            format!(
428                "<measure><note><pitch><step>C</step><octave>4</octave></pitch>\
429                 <duration>1</duration><type>eighth</type><time-modification>\
430                 <actual-notes>3</actual-notes><normal-notes>2</normal-notes>\
431                 </time-modification>{notations}</note></measure>"
432            )
433        };
434        let mut context = MeasureContext::with_divisions(3);
435        let tuplet_type = |measure: &Stream| {
436            measure.notes()[0].1.duration().expect("a note").tuplets()[0].tuplet_type()
437        };
438        let started = read_measure(
439            &note("<notations><tuplet type=\"start\"/></notations>"),
440            &mut context,
441        )
442        .unwrap();
443        assert_eq!(
444            tuplet_type(&started),
445            Some(crate::duration::TupletType::Start)
446        );
447        let stopped = read_measure(
448            &note("<notations><tuplet type=\"stop\"/></notations>"),
449            &mut context,
450        )
451        .unwrap();
452        assert_eq!(
453            tuplet_type(&stopped),
454            Some(crate::duration::TupletType::Stop)
455        );
456    }
457
458    #[test]
459    fn a_percussion_key_outside_the_map_is_warned_of() {
460        let score_part = "<score-part><midi-instrument id=\"I1\"><midi-unpitched>23</midi-unpitched>\
461                          </midi-instrument></score-part>";
462        let read = read_part("<part><measure/></part>", Some(score_part)).unwrap();
463        assert_eq!(read.warnings.len(), 1);
464        assert!(
465            read.warnings[0]
466                .to_string()
467                .contains("22 does not map to a valid instrument!")
468        );
469    }
470
471    #[test]
472    fn a_spanner_begun_in_one_reading_ends_in_the_next() {
473        let mut state = SpannerState::default();
474        let note = state.new_uid();
475        let begun = read_spanners(
476            "<wedge type=\"crescendo\" number=\"2\"/>",
477            Some(note),
478            SpannerStep::DirectionType {
479                staff: 0,
480                offset: 0.0,
481            },
482            &mut state,
483        )
484        .unwrap();
485        assert_eq!(begun.started.len(), 1);
486        let wedge = begun.started[0];
487        assert!(!state.spanner(wedge).unwrap().complete());
488        let ended = read_spanners(
489            "<wedge type=\"stop\" number=\"2\"/>",
490            Some(note),
491            SpannerStep::DirectionType {
492                staff: 0,
493                offset: 0.0,
494            },
495            &mut state,
496        )
497        .unwrap();
498        assert!(ended.started.is_empty());
499        assert!(state.spanner(wedge).unwrap().complete());
500        assert_eq!(state.joined(wedge), &[note]);
501    }
502
503    #[test]
504    fn a_pedal_puts_its_bounces_and_gaps_where_they_are_read() {
505        let mut state = SpannerState::default();
506        let pedal = |text: &str, offset, state: &mut SpannerState| {
507            read_spanners(
508                text,
509                None,
510                SpannerStep::DirectionType { staff: 1, offset },
511                state,
512            )
513            .unwrap()
514        };
515        let begun = pedal(
516            "<pedal type=\"sostenuto\" sign=\"yes\" number=\"2\"/>",
517            0.5,
518            &mut state,
519        );
520        assert_eq!(begun.started.len(), 1);
521        assert!(
522            pedal(
523                "<pedal type=\"resume\" line=\"yes\" number=\"2\"/>",
524                0.5,
525                &mut state
526            )
527            .marks
528            .is_empty()
529        );
530        let bounce = pedal(
531            "<pedal type=\"change\" line=\"yes\" number=\"2\"/>",
532            1.0,
533            &mut state,
534        );
535        assert_eq!(bounce.marks.len(), 1);
536        assert_eq!(bounce.marks[0].1, 1.0);
537        assert_eq!(state.joined(begun.started[0]), &[bounce.marks[0].0]);
538    }
539
540    #[test]
541    fn defaults_give_a_scores_appearance_fonts_and_lyric_languages() {
542        let style = read_defaults_style(
543            "<defaults><appearance><line-width type=\"beam\">5</line-width>\
544             <other-appearance type=\"sharps\">dotted</other-appearance></appearance>\
545             <music-font font-family=\"Maestro, Opus\" font-weight=\"bold\"/>\
546             <lyric-language name=\"verse\" xml:lang=\"fr\"/>\
547             <lyric-language name=\"chorus\"/></defaults>",
548        )
549        .unwrap();
550        assert_eq!(style.line_widths[0].0, "beam");
551        assert_eq!(
552            style.other_appearances[0].1,
553            crate::style::StyleValue::Text("dotted".to_string())
554        );
555        let font = style.music_font.unwrap();
556        assert_eq!(
557            font.font_family,
558            Some(vec!["Maestro".to_string(), "Opus".to_string()])
559        );
560        assert_eq!(
561            style.lyric_languages,
562            vec![
563                (Some("verse".to_string()), Some("fr".to_string())),
564                (Some("chorus".to_string()), Some("en".to_string())),
565            ]
566        );
567    }
568
569    #[test]
570    fn a_bend_and_a_harmonic_say_how_they_are_played() {
571        let bend = read_technical(
572            "<bend><bend-alter>-1</bend-alter><pre-bend/><with-bar>dip</with-bar>\
573             <release offset=\"2\"/></bend>",
574            4.0,
575        )
576        .unwrap()
577        .unwrap();
578        assert_eq!(bend.bend_alter().map(|alter| alter.semitones()), Some(-1.0));
579        assert!(bend.pre_bend());
580        assert_eq!(bend.with_bar(), Some("dip"));
581        assert_eq!(bend.release(), Some(0.5));
582        let harmonic = read_technical("<harmonic><artificial/><sounding-pitch/></harmonic>", 1.0)
583            .unwrap()
584            .unwrap();
585        assert_eq!(harmonic.harmonic_type(), Some("artificial"));
586        assert_eq!(harmonic.pitch_type(), Some("sounding"));
587    }
588
589    #[test]
590    fn a_keys_octaves_place_its_altered_pitches() {
591        let mut signature = KeySignature::new(-4);
592        read_key_octaves(
593            "<key><fifths>-4</fifths><key-octave number=\"1\">3</key-octave>\
594             <key-octave number=\"4\">3</key-octave></key>",
595            &mut signature,
596        )
597        .unwrap();
598        let names: Vec<String> = signature
599            .altered_pitches()
600            .unwrap()
601            .iter()
602            .map(Pitch::name_with_octave)
603            .collect();
604        assert_eq!(names, ["Bb3", "Eb", "Ab", "Db3"]);
605        let sharp = read_non_traditional_key(
606            "<key><key-step>G</key-step><key-alter>1</key-alter>\
607             <key-accidental>sharp</key-accidental></key>",
608        )
609        .unwrap();
610        assert_eq!(sharp.altered_pitches().unwrap()[0].name(), "G#");
611    }
612
613    #[test]
614    fn a_slur_begun_on_one_note_ends_on_another() {
615        let mut state = SpannerState::default();
616        let (first, second) = (state.new_uid(), state.new_uid());
617        let begun = read_spanners(
618            "<notations><slur type=\"start\" number=\"1\"/></notations>",
619            Some(first),
620            SpannerStep::Notations,
621            &mut state,
622        )
623        .unwrap();
624        assert_eq!(begun.started.len(), 1);
625        let one = SpannerStep::One {
626            kind: crate::spanner::SpannerKind::Slur,
627            duplicates: DuplicateIds::Join,
628        };
629        let ended = read_spanners(
630            "<slur type=\"stop\" number=\"1\"/>",
631            Some(second),
632            one,
633            &mut state,
634        )
635        .unwrap();
636        assert_eq!(ended.returned, begun.started);
637        assert!(ended.started.is_empty());
638        assert_eq!(state.joined(begun.started[0]), &[first, second]);
639        assert!(state.spanner(begun.started[0]).unwrap().complete());
640    }
641
642    #[test]
643    fn a_staff_is_read_off_a_note() {
644        assert_eq!(read_staff("<note><staff>2</staff></note>").unwrap(), 2);
645        assert_eq!(read_staff("<note/>").unwrap(), 0);
646    }
647}