Skip to main content

music21/abc/
step.rs

1//! ABC's tokens and the handler that reads them: music21's `abcFormat`.
2//!
3//! The text is cut into tokens one character at a time ([`Handler::tokenize`]),
4//! each token is told what is in force where it stands -- the default length,
5//! the key, a tuplet, a tie -- and then read ([`Handler::process`]). A
6//! processed handler is cut into tunes, voices and measures by token index,
7//! so a caller keeping tokens of its own can cut those the same way. The
8//! order and the oddities are music21's throughout.
9//!
10//! Each step is one music21 exposes: a token starts as music21's does, with
11//! only its text, and its fields are filled by the step music21 calls
12//! (`pre_parse`, `parse`, `update_ratio`), so a token can be read, changed and
13//! read on between steps.
14
15use std::ops::Range;
16
17use crate::bar::{Barline, BarlineType, RepeatDirection};
18use crate::clef::Clef;
19use crate::defaults::{FloatType, IntegerType};
20use crate::duration::{Duration, Tuplet};
21use crate::error::{Error, FormatErrorKind, Position, Result};
22use crate::key::KeySignature;
23use crate::meter::TimeSignature;
24use crate::notation::TieType;
25use crate::pitch::Pitch;
26use crate::spanner::SpannerKind;
27use crate::stream::StreamElement;
28use crate::tempo::MetronomeMark;
29
30pub(super) fn abc_error(message: impl Into<String>) -> Error {
31    Error::abc(message.into())
32}
33
34/// The ABC version a file is read as where it names none: music21's
35/// `defaults.abcVersionDefault`.
36pub const DEFAULT_VERSION: (u32, u32, u32) = (1, 3, 0);
37
38/// The version from which accidentals carry through a measure.
39const PROPAGATING_VERSION: (u32, u32, u32) = (2, 0, 0);
40
41/// Every bar token and what music21 calls it, in the order music21 tries
42/// them: music21's `ABC_BARS`.
43pub const BARS: [(&str, &str); 14] = [
44    (":|1", "light-heavy-repeat-end-first"),
45    (":|2", "light-heavy-repeat-end-second"),
46    ("|]", "light-heavy"),
47    ("||", "light-light"),
48    ("[|", "heavy-light"),
49    ("[1", "regular-first"),
50    ("[2", "regular-second"),
51    ("|1", "regular-first"),
52    ("|2", "regular-second"),
53    (":|", "light-heavy-repeat-end"),
54    ("|:", "heavy-light-repeat-start"),
55    ("::", "heavy-heavy-repeat-bidirectional"),
56    ("|", "regular"),
57    (":", "dotted"),
58];
59
60/// The marks that may stand before a note's letter.
61const DECORATIONS: &str = ".~^=_HLMOPSTuv";
62
63/// The marks that alter a note's pitch.
64const ACCIDENTALS: &str = "^=_";
65
66/// The articulations a note can carry, in the order music21 gives them.
67const ARTICULATIONS: [&str; 6] = [
68    "staccato",
69    "upbow",
70    "downbow",
71    "accent",
72    "strongaccent",
73    "tenuto",
74];
75
76/// music21's `opFrac`, near enough for lengths: the nearest fraction with a
77/// small denominator where the float is within a hair of one.
78pub(super) fn op_frac(value: FloatType) -> FloatType {
79    if (value * 32768.0).fract() == 0.0 {
80        return value;
81    }
82    for denominator in 1..=65535u32 {
83        let scaled = value * FloatType::from(denominator);
84        if (scaled - scaled.round()).abs() < 1e-9 * FloatType::from(denominator).max(1.0) {
85            return scaled.round() / FloatType::from(denominator);
86        }
87    }
88    value
89}
90
91/// music21's `ABCToken.stripComment`: the text before any `%`.
92///
93/// ```
94/// use music21::abc::step::strip_comment;
95///
96/// assert_eq!(strip_comment("asdf  %     234"), "asdf  ");
97/// ```
98pub fn strip_comment(src: &str) -> &str {
99    src.split('%').next().unwrap_or("")
100}
101
102// ------------------------------------------------------------------ tokens
103
104/// A bar token: music21's `ABCBar`. Its fields are empty until
105/// [`Bar::parse`].
106#[derive(Clone, Debug, Default, PartialEq)]
107pub struct Bar {
108    /// The text it was read from.
109    pub src: String,
110    /// `repeat` or `barline`; empty where the text is no bar at all.
111    pub bar_type: String,
112    /// `regular`, `light-heavy` and the like.
113    pub bar_style: String,
114    /// `end`, `start`, `first` or `second`.
115    pub repeat_form: String,
116}
117
118impl Bar {
119    /// An unread bar of `src`.
120    pub fn new(src: &str) -> Self {
121        Self {
122            src: src.to_string(),
123            ..Self::default()
124        }
125    }
126
127    /// A bar of `src`, read.
128    pub fn parsed(src: &str) -> Self {
129        let mut bar = Self::new(src);
130        bar.parse();
131        bar
132    }
133
134    /// music21's `ABCBar.parse`: the type, style and repeat form its text
135    /// names.
136    ///
137    /// ```
138    /// use music21::abc::step::Bar;
139    ///
140    /// let bar = Bar::parsed("|:");
141    /// assert_eq!((bar.bar_type.as_str(), bar.bar_style.as_str()), ("repeat", "heavy-light"));
142    /// assert_eq!(bar.repeat_form, "start");
143    /// ```
144    pub fn parse(&mut self) {
145        let Some((_, described)) = BARS.iter().find(|(text, _)| *text == self.src.trim()) else {
146            return;
147        };
148        let parts: Vec<&str> = described.split('-').collect();
149        self.bar_type = if parts.contains(&"repeat") {
150            "repeat"
151        } else {
152            "barline"
153        }
154        .to_string();
155        if parts.len() == 1 {
156            self.bar_style = parts[0].to_string();
157        } else if parts.contains(&"first") {
158            self.bar_style = "regular".to_string();
159            self.repeat_form = "first".to_string();
160        } else if parts.contains(&"second") {
161            self.bar_style = "regular".to_string();
162            self.repeat_form = "second".to_string();
163        } else {
164            self.bar_style = format!("{}-{}", parts[0], parts[1]);
165        }
166        if parts.len() > 2 {
167            self.repeat_form = parts[3].to_string();
168        }
169    }
170
171    /// music21's `isRepeat`.
172    pub fn is_repeat(&self) -> bool {
173        self.bar_type == "repeat"
174    }
175
176    /// music21's `isRegular`: a single light barline.
177    pub fn is_regular(&self) -> bool {
178        !self.is_repeat() && self.bar_style == "regular"
179    }
180
181    /// music21's `isRepeatBracket`: which ending the bar opens, where it
182    /// opens one.
183    pub fn repeat_bracket(&self) -> Option<u32> {
184        match self.repeat_form.as_str() {
185            "first" => Some(1),
186            "second" => Some(2),
187            _ => None,
188        }
189    }
190
191    /// music21's `getBarObject`: nothing for a plain barline or an ending.
192    pub fn barline(&self) -> Option<Barline> {
193        if self.is_repeat() {
194            return match self.repeat_form.as_str() {
195                "start" => Some(Barline::repeat(RepeatDirection::Start, None)),
196                "end" => Some(Barline::repeat(RepeatDirection::End, None)),
197                _ => None,
198            };
199        }
200        if self.bar_style == "regular" || self.bar_style.is_empty() {
201            return None;
202        }
203        if self.repeat_bracket().is_some() {
204            return None;
205        }
206        BarlineType::from_name(&self.bar_style)
207            .ok()
208            .map(Barline::new)
209    }
210}
211
212/// A line of metadata, `T:Title` and the like: music21's `ABCMetadata`. Its
213/// tag and data are empty until [`AbcMetadata::pre_parse`].
214#[derive(Clone, Debug, Default, PartialEq)]
215pub struct AbcMetadata {
216    /// The text it was read from.
217    pub src: String,
218    /// The capital letter, or `w`, before the colon.
219    pub tag: String,
220    /// What follows the colon, trimmed, a comment taken off.
221    pub data: String,
222    /// The line of the text it stands on, counted from one; nought where
223    /// unknown.
224    pub line: usize,
225}
226
227impl AbcMetadata {
228    /// An unread line of `src`.
229    pub fn new(src: &str) -> Self {
230        Self {
231            src: src.to_string(),
232            ..Self::default()
233        }
234    }
235
236    /// music21's `preParse`: the tag and the data split apart.
237    ///
238    /// ```
239    /// use music21::abc::step::AbcMetadata;
240    ///
241    /// let mut line = AbcMetadata::new("T:tagData % a comment");
242    /// line.pre_parse();
243    /// assert_eq!((line.tag.as_str(), line.data.as_str()), ("T", "tagData"));
244    /// ```
245    pub fn pre_parse(&mut self) {
246        let chars: Vec<char> = self.src.chars().collect();
247        let is_tag = chars.len() >= 2
248            && (chars[0].is_ascii_uppercase() || chars[0] == 'w')
249            && chars[1] == ':';
250        if !is_tag {
251            return;
252        }
253        let mut pieces = strip_comment(&self.src).chars();
254        self.tag = pieces.by_ref().take(1).collect();
255        self.data = pieces.skip(1).collect::<String>().trim().to_string();
256    }
257
258    fn is(&self, tag: &str) -> bool {
259        self.tag == tag
260    }
261
262    /// music21's `getTimeSignatureParameters`: the meter's numerator,
263    /// denominator and symbol (`normal`, `common` or `cut`), nothing for
264    /// `M:none`.
265    pub fn meter_parameters(&self) -> Result<Option<(u32, u32, &'static str)>> {
266        if !self.is("M") {
267            return Err(abc_error("no time signature associated with this metadata"));
268        }
269        let data = self.data.as_str();
270        if data.to_lowercase() == "none" {
271            return Ok(None);
272        }
273        match data {
274            "C" => return Ok(Some((4, 4, "common"))),
275            "C|" => return Ok(Some((2, 2, "cut"))),
276            _ => {}
277        }
278        let (numerator, denominator) = data
279            .split_once('/')
280            .ok_or_else(|| abc_error(format!("cannot read the meter {data:?}")))?;
281        let digits = |text: &str| -> Result<u32> {
282            text.chars()
283                .filter(char::is_ascii_digit)
284                .collect::<String>()
285                .parse()
286                .map_err(|_| abc_error(format!("cannot read the meter {data:?}")))
287        };
288        Ok(Some((digits(numerator)?, digits(denominator)?, "normal")))
289    }
290
291    /// music21's `getTimeSignatureObject`.
292    pub fn meter(&self) -> Result<Option<TimeSignature>> {
293        if !self.is("M") {
294            return Err(abc_error(
295                "no time signature associated with this non-metrical metadata.",
296            ));
297        }
298        match self.meter_parameters()? {
299            Some((numerator, denominator, _)) => {
300                Ok(Some(TimeSignature::new(numerator, denominator)?))
301            }
302            None => Ok(None),
303        }
304    }
305
306    /// music21's `getKeySignatureParameters`: the signed count of sharps and
307    /// the mode, where the key names one.
308    ///
309    /// ```
310    /// use music21::abc::step::AbcMetadata;
311    ///
312    /// let mut line = AbcMetadata::new("K:Eb Lydian");
313    /// line.pre_parse();
314    /// assert_eq!(line.key_parameters()?, (-2, Some("lydian")));
315    /// # Ok::<(), music21::Error>(())
316    /// ```
317    pub fn key_parameters(&self) -> Result<(IntegerType, Option<&'static str>)> {
318        if !self.is("K") {
319            return Err(abc_error("no key signature associated with this metadata."));
320        }
321        key_parameters(&self.data)
322    }
323
324    /// music21's `getKeySignatureObject`: a key where there is a mode, a
325    /// signature otherwise.
326    pub fn key(&self) -> Result<StreamElement> {
327        if !self.is("K") {
328            return Err(abc_error("no key signature associated with this metadata"));
329        }
330        let (sharps, mode) = key_parameters(&self.data)?;
331        Ok(key_element(sharps, mode))
332    }
333
334    /// music21's `getClefObject`: the clef a key line names, and how far the
335    /// notes under it are moved.
336    pub fn clef(&self) -> Result<Option<(Clef, IntegerType)>> {
337        if !self.is("K") {
338            return Err(abc_error(
339                "no key signature associated with this metadata; needed for getting Clef Object",
340            ));
341        }
342        let lower = self.data.to_lowercase();
343        if lower.contains("-8va") {
344            return Ok(Clef::from_string("treble8vb", 0)
345                .ok()
346                .map(|clef| (clef, -12)));
347        }
348        if lower.contains("bass") {
349            return Ok(Some((Clef::bass(), -24)));
350        }
351        Ok(None)
352    }
353
354    /// music21's `getMetronomeMarkObject`.
355    pub fn tempo(&self) -> Result<MetronomeMark> {
356        if !self.is("Q") {
357            return Err(abc_error("no tempo associated with this metadata"));
358        }
359        tempo_of(&self.data)
360    }
361
362    /// music21's `getDefaultQuarterLength`, for an `L:` or an `M:` line.
363    ///
364    /// ```
365    /// use music21::abc::step::AbcMetadata;
366    ///
367    /// let mut line = AbcMetadata::new("M:2/4");
368    /// line.pre_parse();
369    /// assert_eq!(line.default_quarter_length()?, 0.25);
370    /// # Ok::<(), music21::Error>(())
371    /// ```
372    pub fn default_quarter_length(&self) -> Result<FloatType> {
373        let data = self.data.as_str();
374        if self.is("L") && data.contains('/') {
375            let (numerator, denominator) = data.split_once('/').unwrap_or(("1", "8"));
376            let read = |text: &str| -> Result<FloatType> {
377                text.trim()
378                    .parse()
379                    .map_err(|_| abc_error(format!("cannot read the default length {data:?}")))
380            };
381            // `L:1/G` is in some of the Essen files.
382            let denominator = if denominator == "G" {
383                4.0
384            } else {
385                read(denominator)?
386            };
387            return Ok(read(numerator)? * 4.0 / denominator);
388        }
389        if self.is("M") {
390            return Ok(match self.meter_parameters()? {
391                None => 0.5,
392                // Under three quarters of a whole note the unit is a sixteenth.
393                Some((numerator, denominator, _))
394                    if FloatType::from(numerator) / FloatType::from(denominator) < 0.75 =>
395                {
396                    0.25
397                }
398                Some(_) => 0.5,
399            });
400        }
401        Err(abc_error(format!(
402            "no quarter length associated with this metadata: {data}"
403        )))
404    }
405}
406
407/// A key where there is a mode, a signature otherwise, as music21's
408/// `KeySignature(sharps).asKey(mode)`.
409pub(super) fn key_element(sharps: IntegerType, mode: Option<&str>) -> StreamElement {
410    let signature = KeySignature::new(sharps);
411    let Some(mode) = mode else {
412        return signature.into();
413    };
414    match signature.try_as_key(Some(mode), None) {
415        Ok(key) => key.into(),
416        Err(_) => signature.into(),
417    }
418}
419
420fn key_parameters(data: &str) -> Result<(IntegerType, Option<&'static str>)> {
421    const NAMES: [&str; 20] = [
422        "c", "g", "d", "a", "e", "b", "f#", "g#", "a#", "f", "bb", "eb", "d#", "ab", "e#", "db",
423        "c#", "gb", "cb", "hp",
424    ];
425    let mut names: Vec<&str> = NAMES.to_vec();
426    // Longest first, and the sort is stable.
427    names.sort_by_key(|name| std::cmp::Reverse(name.len()));
428    let chars: Vec<char> = data.chars().collect();
429    let mut standard = "C".to_string();
430    let mut remain = String::new();
431    for target in names {
432        let length = target.chars().count();
433        let head: String = chars.iter().take(length).collect();
434        if head.to_lowercase() == target {
435            standard = head;
436            remain = chars.iter().skip(length).collect();
437            break;
438        }
439    }
440    let letters: Vec<char> = standard.chars().collect();
441    if letters.len() > 1 && letters[1] == 'b' {
442        standard = format!("{}-", letters[0]);
443    }
444    let remain = remain.trim().to_lowercase();
445    let mut mode: Option<&'static str> = if remain.is_empty() {
446        Some("major")
447    } else {
448        [
449            ("dor", "dorian"),
450            ("phr", "phrygian"),
451            ("lyd", "lydian"),
452            ("mix", "mixolydian"),
453            ("maj", "major"),
454            ("ion", "ionian"),
455            ("aeo", "aeolian"),
456            ("m", "minor"),
457        ]
458        .into_iter()
459        .find(|(prefix, _)| remain.starts_with(prefix))
460        .map(|(_, mode)| mode)
461    };
462    // The Highland pipes: no signature written, or two sharps and a natural.
463    if standard == "HP" {
464        standard = "C".to_string();
465        mode = None;
466    } else if standard == "Hp" {
467        standard = "D".to_string();
468        mode = None;
469    }
470    let tonic = Pitch::from_name(&standard)?;
471    let sharps = crate::key::pitch_to_sharps(&tonic, mode)?;
472    Ok((sharps, mode))
473}
474
475fn tempo_of(data: &str) -> Result<MetronomeMark> {
476    let mut text: Option<String> = None;
477    let non_text = if data.contains('"') {
478        let mut quoted = String::new();
479        let mut outside = String::new();
480        let mut open = false;
481        for character in data.chars() {
482            if character == '"' {
483                open = !open;
484            } else if open {
485                quoted.push(character);
486            } else {
487                outside.push(character);
488            }
489        }
490        text = Some(quoted.trim().to_string()).filter(|text| !text.is_empty());
491        outside.trim().to_string()
492    } else {
493        data.trim().to_string()
494    };
495    let read = |number: &str| -> Result<FloatType> {
496        number
497            .trim()
498            .parse::<FloatType>()
499            .map_err(|_| abc_error(format!("cannot read the tempo {data:?}")))
500    };
501    let mut number: Option<FloatType> = None;
502    let mut referent: Option<FloatType> = None;
503    if !non_text.is_empty() {
504        if let Some((lengths, count)) = non_text.split_once('=') {
505            number = Some(read(count)?);
506            let mut quarters = 0.0;
507            for length in lengths.split(' ') {
508                let (numerator, denominator) = length.split_once('/').unwrap_or(("1", "1"));
509                quarters += read(numerator)? / read(denominator)? * 4.0;
510            }
511            referent = Some(quarters);
512        } else {
513            number = Some(read(&non_text)?);
514        }
515    }
516    let mut mark = match (number, text) {
517        (Some(number), Some(text)) => MetronomeMark::with_number_and_text(number, text),
518        (Some(number), None) => MetronomeMark::new(number),
519        (None, Some(text)) => MetronomeMark::from_text(text),
520        (None, None) => MetronomeMark::default(),
521    };
522    if let Some(referent) = referent {
523        mark.set_referent(Duration::new(referent)?);
524    }
525    Ok(mark)
526}
527
528/// A tuplet's opening, `(3` or `(p:q:r`: music21's `ABCTuplet`. Its ratio
529/// is unknown until [`AbcTuplet::update_ratio`].
530#[derive(Clone, Debug, PartialEq)]
531pub struct AbcTuplet {
532    /// The text it was read from.
533    pub src: String,
534    /// The line of the text it stands on, counted from one; nought where unknown.
535    pub line: usize,
536    /// How many notes it still takes; -1 until counted.
537    pub note_count: i32,
538    /// The notes played: 3 in 3:2; -1 until known.
539    pub actual: i32,
540    /// The notes they take the time of: 2 in 3:2.
541    pub normal: i32,
542}
543
544impl AbcTuplet {
545    /// An unread tuplet of `src`.
546    pub fn new(src: &str) -> Self {
547        Self {
548            src: src.to_string(),
549            line: 0,
550            note_count: -1,
551            actual: -1,
552            normal: 1,
553        }
554    }
555
556    fn pieces(&self) -> Vec<&str> {
557        self.src.trim().split(':').collect()
558    }
559
560    /// music21's `updateRatio`: the ratio, which for 5, 7 and 9 depends on
561    /// whether the meter in force is compound.
562    ///
563    /// ```
564    /// use music21::abc::step::AbcTuplet;
565    /// use music21::TimeSignature;
566    ///
567    /// let mut tuplet = AbcTuplet::new("(5");
568    /// tuplet.update_ratio(Some(&TimeSignature::new(6, 8)?))?;
569    /// assert_eq!((tuplet.actual, tuplet.normal), (5, 3));
570    /// # Ok::<(), music21::Error>(())
571    /// ```
572    pub fn update_ratio(&mut self, meter: Option<&TimeSignature>) -> Result<()> {
573        let switch = match meter {
574            Some(meter) if meter.beat_division_count() == 3 => 3,
575            _ => 2,
576        };
577        let pieces = self.pieces();
578        let (actual, normal) = match pieces[0] {
579            "(1" => (1, 1),
580            "(2" => (2, 3),
581            "(3" => (3, 2),
582            "(4" => (4, 3),
583            "(5" => (5, switch),
584            "(6" => (6, 2),
585            "(7" => (7, switch),
586            "(8" => (8, 3),
587            "(9" => (9, switch),
588            other => {
589                return Err(abc_error(format!(
590                    "cannot handle tuplet of form: '{other}'"
591                )));
592            }
593        };
594        let given = pieces.get(1).and_then(|piece| piece.parse::<i32>().ok());
595        self.actual = actual;
596        self.normal = given.unwrap_or(normal);
597        Ok(())
598    }
599
600    /// music21's `updateNoteCount`: how many notes the tuplet takes, and the
601    /// tuplet itself.
602    pub fn update_note_count(&mut self) -> Result<Tuplet> {
603        if self.actual == -1 {
604            return Err(abc_error("must set numberNotesActual with updateRatio()"));
605        }
606        let given = self
607            .pieces()
608            .get(2)
609            .and_then(|piece| piece.parse::<i32>().ok());
610        self.note_count = given.unwrap_or(self.actual);
611        Ok(Tuplet::ratio(self.actual as u32, self.normal.max(0) as u32))
612    }
613}
614
615/// A broken rhythm, `>` to `<<<`: music21's `ABCBrokenRhythmMarker`. Its
616/// data is empty until [`BrokenRhythm::pre_parse`].
617#[derive(Clone, Debug, Default, PartialEq)]
618pub struct BrokenRhythm {
619    /// The text it was read from.
620    pub src: String,
621    /// The mark, trimmed.
622    pub data: String,
623}
624
625impl BrokenRhythm {
626    /// music21's `preParse`.
627    pub fn pre_parse(&mut self) {
628        self.data = self.src.trim().to_string();
629    }
630}
631
632/// Which side of a broken-rhythm mark a note stands on.
633#[derive(Clone, Copy, Debug, PartialEq, Eq)]
634pub enum Side {
635    /// Before the mark.
636    Left,
637    /// After the mark.
638    Right,
639}
640
641impl Side {
642    /// music21's name for the side.
643    pub fn name(self) -> &'static str {
644        match self {
645            Self::Left => "left",
646            Self::Right => "right",
647        }
648    }
649}
650
651/// A note, a rest, or with `is_chord` a chord: music21's `ABCNote` and
652/// `ABCChord`. Its context is filled by [`Handler::process`], its pitch and
653/// length by [`AbcNote::parse`].
654#[derive(Clone, Debug, Default, PartialEq)]
655pub struct AbcNote {
656    /// The text it was read from.
657    pub src: String,
658    /// The line of the text it starts on; nought where unknown.
659    pub line: usize,
660    /// Whether it is a chord.
661    pub is_chord: bool,
662    /// The accidental carried from earlier in the measure.
663    pub carried_accidental: String,
664    /// The chord symbols written over it, quotes kept.
665    pub chord_symbols: Vec<String>,
666    /// Whether it is a grace note.
667    pub in_grace: bool,
668    /// The default length in force, in quarter notes.
669    pub default_quarter_length: Option<FloatType>,
670    /// The broken-rhythm mark and the side of it the note stands on.
671    pub broken_rhythm: Option<(String, Side)>,
672    /// The key in force.
673    pub key: Option<KeySignature>,
674    /// The tuplet it is in.
675    pub tuplet: Option<Tuplet>,
676    /// The spanners in force, by where they stand among the handler's.
677    pub spanners: Vec<usize>,
678    /// The tie it starts, continues or stops.
679    pub tie: Option<TieType>,
680    /// music21's names: `staccato`, `upbow` and the rest.
681    pub articulations: Vec<String>,
682    /// Whether the accidental is shown: nothing where undecided.
683    pub accidental_display: Option<bool>,
684    /// Whether it is a rest.
685    pub is_rest: bool,
686    /// The pitch as music21 names one; nothing for a rest or a chord.
687    pub pitch_name: Option<String>,
688    /// The length in quarter notes.
689    pub quarter_length: FloatType,
690    /// A chord's notes, once parsed.
691    pub sub_tokens: Vec<AbcNote>,
692}
693
694impl AbcNote {
695    /// An unread note of `src`, carrying the accidental `carried`.
696    pub fn new(src: &str, carried: &str) -> Self {
697        Self {
698            src: src.to_string(),
699            carried_accidental: carried.to_string(),
700            ..Self::default()
701        }
702    }
703
704    /// An unread chord of `src`.
705    pub fn chord(src: &str) -> Self {
706        Self {
707            src: src.to_string(),
708            is_chord: true,
709            ..Self::default()
710        }
711    }
712
713    /// music21's `_splitChordSymbols`: the quoted strings, and what is left
714    /// after the last of them.
715    ///
716    /// ```
717    /// use music21::abc::step::AbcNote;
718    ///
719    /// let (symbols, rest) = AbcNote::split_chord_symbols("\"D7\"\"D\"d2");
720    /// assert_eq!((symbols, rest.as_str()), (vec!["\"D7\"".to_string(), "\"D\"".to_string()], "d2"));
721    /// ```
722    pub fn split_chord_symbols(src: &str) -> (Vec<String>, String) {
723        if !src.contains('"') {
724            return (Vec::new(), src.to_string());
725        }
726        let chars: Vec<char> = src.chars().collect();
727        let mut symbols = Vec::new();
728        let mut index = 0;
729        let mut after = 0;
730        while index < chars.len() {
731            if chars[index] == '"'
732                && let Some(length) = chars[index + 1..].iter().position(|c| *c == '"')
733            {
734                let close = index + 1 + length;
735                symbols.push(chars[index..=close].iter().collect::<String>());
736                index = close + 1;
737                after = index;
738                continue;
739            }
740            index += 1;
741        }
742        if symbols.is_empty() {
743            return (Vec::new(), src.to_string());
744        }
745        (symbols, chars[after..].iter().collect())
746    }
747
748    /// music21's `getPitchName`: the pitch as music21 names one, or nothing
749    /// for a rest, and whether its accidental is shown. `forced_key` stands
750    /// in for the note's own key.
751    ///
752    /// ```
753    /// use music21::abc::step::AbcNote;
754    /// use music21::KeySignature;
755    ///
756    /// let note = AbcNote::new("", "");
757    /// assert_eq!(note.pitch_name("_g''", None)?, (Some("G-7".to_string()), Some(true)));
758    /// let key = KeySignature::new(3);
759    /// assert_eq!(note.pitch_name("c", Some(&key))?, (Some("C#5".to_string()), Some(false)));
760    /// # Ok::<(), music21::Error>(())
761    /// ```
762    pub fn pitch_name(
763        &self,
764        src: &str,
765        forced_key: Option<&KeySignature>,
766    ) -> Result<(Option<String>, Option<bool>)> {
767        let chars: Vec<char> = src.chars().collect();
768        let mut text: String = if chars.len() > 1 && matches!(chars[0], 'u' | 'T') {
769            chars[1..].iter().collect()
770        } else {
771            src.to_string()
772        };
773        text = text.replace('T', "");
774        let name = text
775            .chars()
776            .find(|c| matches!(c, 'a'..='g' | 'A'..='G' | 'z'))
777            .ok_or_else(|| abc_error(format!("cannot find any pitch information in: '{text}'")))?;
778        if name == 'z' {
779            return Ok((None, None));
780        }
781        let key = forced_key.or(self.key.as_ref());
782        let count = |wanted: char| text.chars().filter(|c| *c == wanted).count();
783        let mut octave: i32 = if name.is_lowercase() { 5 } else { 4 };
784        octave -= count(',') as i32;
785        octave += count('\'') as i32;
786        let marks = |source: &str| -> String {
787            let count = |wanted: char| source.chars().filter(|c| *c == wanted).count();
788            format!(
789                "{}{}{}",
790                "-".repeat(count('_')),
791                "#".repeat(count('^')),
792                "n".repeat(count('='))
793            )
794        };
795        let written = marks(&text);
796        let carried = marks(&self.carried_accidental);
797        if !carried.is_empty() && !written.is_empty() {
798            return Err(abc_error("Carried accidentals not rendered moot."));
799        }
800        let mut name = name.to_uppercase().to_string();
801        let display = if !carried.is_empty() {
802            None
803        } else if !written.is_empty() {
804            Some(true)
805        } else {
806            match key {
807                None => None,
808                Some(key) => {
809                    // The signature's own spelling of the note, not shown.
810                    if let Ok(altered) = key.altered_pitches()
811                        && let Some(pitch) = altered
812                            .iter()
813                            .find(|pitch| pitch.step().as_char().to_string() == name)
814                    {
815                        // music21 writes a flat `-`.
816                        let modifier = pitch.accidental().modifier().replace('b', "-");
817                        name = format!("{}{modifier}", pitch.step().as_char());
818                    }
819                    Some(false)
820                }
821            }
822        };
823        let accidental = if carried.is_empty() { written } else { carried };
824        Ok((Some(format!("{name}{accidental}{octave}")), display))
825    }
826
827    /// music21's `getQuarterLength`: the length `src` writes, against the
828    /// default length (or `forced_default`), stretched by a broken rhythm.
829    ///
830    /// ```
831    /// use music21::abc::step::{AbcNote, Side};
832    ///
833    /// let mut note = AbcNote::new("", "");
834    /// note.default_quarter_length = Some(0.5);
835    /// assert_eq!(note.quarter_length_of("A3/2", None)?, 0.75);
836    /// note.broken_rhythm = Some(("<<".to_string(), Side::Right));
837    /// assert_eq!(note.quarter_length_of("A", None)?, 0.875);
838    /// # Ok::<(), music21::Error>(())
839    /// ```
840    pub fn quarter_length_of(
841        &self,
842        src: &str,
843        forced_default: Option<FloatType>,
844    ) -> Result<FloatType> {
845        let default = forced_default
846            .or(self.default_quarter_length)
847            .ok_or_else(|| {
848                abc_error("cannot calculate quarter length without a default quarter length")
849            })?;
850        let number: String = src
851            .chars()
852            .filter(|c| c.is_ascii_digit() || *c == '/')
853            .collect();
854        let whole = |text: &str| -> Result<FloatType> {
855            text.trim()
856                .parse::<FloatType>()
857                .map_err(|_| abc_error(format!("cannot read the length in {src:?}")))
858        };
859        let mut length = match number.as_str() {
860            "" => default,
861            "/" => default * 0.5,
862            "//" => default * 0.25,
863            "///" => default * 0.125,
864            text if text.starts_with('/') => {
865                op_frac(default / whole(text.split('/').nth(1).unwrap_or(""))?)
866            }
867            text if text.ends_with('/') => {
868                default * whole(text.split('/').next().unwrap_or(""))? / 2.0
869            }
870            text if text.matches('/').count() == 2 => 1.0,
871            text if text.contains('/') => {
872                let (numerator, denominator) = text.split_once('/').unwrap_or(("1", "1"));
873                op_frac(default * whole(numerator)? / whole(denominator)?)
874            }
875            text => default * whole(text)?,
876        };
877        if let Some((symbol, side)) = &self.broken_rhythm {
878            let (first, second) = match symbol.as_str() {
879                ">" => (1.5, 0.5),
880                "<" => (0.5, 1.5),
881                ">>" => (1.75, 0.25),
882                "<<" => (0.25, 1.75),
883                ">>>" => (1.875, 0.125),
884                "<<<" => (0.125, 1.875),
885                _ => (1.0, 1.0),
886            };
887            length *= match side {
888                Side::Left => first,
889                Side::Right => second,
890            };
891        }
892        Ok(length)
893    }
894
895    /// music21's `ABCNote.parse` and `ABCChord.parse`: the chord symbols,
896    /// the pitch and the length, or for a chord its notes and length.
897    /// `forced_default` and `forced_key` stand in for the note's own.
898    pub fn parse(
899        &mut self,
900        forced_default: Option<FloatType>,
901        forced_key: Option<&KeySignature>,
902    ) -> Result<()> {
903        let (symbols, rest) = Self::split_chord_symbols(&self.src);
904        self.chord_symbols = symbols;
905        if self.is_chord {
906            return self.parse_chord(&rest, forced_key);
907        }
908        // A note music21 can find no pitch in is read as a C.
909        let (name, display) = match self.pitch_name(&rest, forced_key) {
910            Ok(read) => read,
911            Err(Error::Abc(read)) if read.message.starts_with("cannot find any pitch") => {
912                (Some("C".to_string()), Some(false))
913            }
914            Err(error) => return Err(error),
915        };
916        self.is_rest = name.is_none();
917        self.pitch_name = name;
918        self.accidental_display = display;
919        self.quarter_length = self.quarter_length_of(&rest, forced_default)?;
920        Ok(())
921    }
922
923    /// `ABCChord.parse`: the notes inside the brackets, each read alone,
924    /// and the length of the first times the length after the brackets.
925    fn parse_chord(&mut self, rest: &str, forced_key: Option<&KeySignature>) -> Result<()> {
926        let chars: Vec<char> = rest.chars().collect();
927        let close = chars.iter().position(|c| *c == ']').ok_or_else(|| {
928            abc_error(format!(
929                "Bad chord indicator: {}: no closing bracket found.",
930                self.src
931            ))
932        })?;
933        let outer: String = chars[close + 1..].iter().collect();
934        let inner: String = chars[1..close].iter().collect();
935        let outer_length = self.quarter_length_of(&outer, Some(1.0))?;
936        let key = forced_key.cloned().or_else(|| self.key.clone());
937        let mut handler = Handler::new(DEFAULT_VERSION);
938        // What goes wrong inside is placed where the chord stands.
939        handler.read_tokens(&inner).map_err(|(_, error)| error)?;
940        let mut inner_length = 0.0;
941        for token in handler.tokens {
942            let Token::Note(mut note) = token else {
943                continue;
944            };
945            note.parse(self.default_quarter_length, key.as_ref())?;
946            if note.is_rest {
947                continue;
948            }
949            if inner_length == 0.0 {
950                inner_length = note.quarter_length;
951            }
952            self.sub_tokens.push(*note);
953        }
954        self.quarter_length = outer_length * inner_length;
955        Ok(())
956    }
957}
958
959/// What a closing mark closes.
960#[derive(Clone, Copy, Debug, PartialEq, Eq)]
961pub enum Closes {
962    /// `)`: the latest slur.
963    Slur,
964    /// `!crescendo)!` or `!diminuendo)!`: the latest hairpin.
965    Hairpin,
966}
967
968/// One token of ABC: music21's `ABCToken` and its subclasses.
969#[derive(Clone, Debug, PartialEq)]
970pub enum Token {
971    /// `T:Title` and the like.
972    Metadata(AbcMetadata),
973    /// `|`, `:|` and the like.
974    Bar(Bar),
975    /// `(3` and the like.
976    Tuplet(AbcTuplet),
977    /// `-`.
978    Tie,
979    /// A slur or a hairpin opening, and once processed the spanner it
980    /// starts, by where it stands among the handler's.
981    SpannerStart(SpannerKind, Option<usize>),
982    /// `)`, `!crescendo)!` or `!diminuendo)!`.
983    ParenStop(Closes),
984    /// `.`.
985    Staccato,
986    /// `u`.
987    Upbow,
988    /// `v`.
989    Downbow,
990    /// `K`.
991    Accent,
992    /// `k`.
993    Straccent,
994    /// `M`.
995    Tenuto,
996    /// `{`.
997    GraceStart,
998    /// `}`.
999    GraceStop,
1000    /// `>` to `<<<`.
1001    BrokenRhythm(BrokenRhythm),
1002    /// A note, rest or chord.
1003    Note(Box<AbcNote>),
1004}
1005
1006impl Token {
1007    /// The text the token was read from, as music21 keeps it.
1008    pub fn src(&self) -> String {
1009        let fixed = match self {
1010            Self::Metadata(line) => return line.src.clone(),
1011            Self::Bar(bar) => return bar.src.clone(),
1012            Self::Tuplet(tuplet) => return tuplet.src.clone(),
1013            Self::BrokenRhythm(mark) => return mark.src.clone(),
1014            Self::Note(note) => return note.src.clone(),
1015            Self::Tie => "-",
1016            Self::SpannerStart(SpannerKind::Slur, _) => "(",
1017            Self::SpannerStart(..) => "!",
1018            Self::ParenStop(Closes::Slur) => ")",
1019            Self::ParenStop(Closes::Hairpin) => "!",
1020            Self::Staccato => ".",
1021            Self::Upbow => "u",
1022            Self::Downbow => "v",
1023            Self::Accent => "K",
1024            Self::Straccent => "k",
1025            Self::Tenuto => "M",
1026            Self::GraceStart => "{",
1027            Self::GraceStop => "}",
1028        };
1029        fixed.to_string()
1030    }
1031
1032    /// Whether the token is a note, rest or chord.
1033    pub fn is_note(&self) -> bool {
1034        matches!(self, Self::Note(_))
1035    }
1036
1037    /// The tag and data of a line of metadata.
1038    pub fn metadata(&self) -> Option<(&str, &str)> {
1039        match self {
1040            Self::Metadata(line) => Some((&line.tag, &line.data)),
1041            _ => None,
1042        }
1043    }
1044
1045    /// The line of the text the token starts on, where it is one that can
1046    /// be refused.
1047    pub(super) fn line(&self) -> Option<usize> {
1048        match self {
1049            Self::Metadata(line) => Some(line.line),
1050            Self::Tuplet(tuplet) => Some(tuplet.line),
1051            Self::Note(note) => Some(note.line),
1052            _ => None,
1053        }
1054    }
1055}
1056
1057/// `error`, placed at `line` where the token knows one.
1058pub(super) fn at_line(error: Error, line: Option<usize>) -> Error {
1059    match line {
1060        Some(line) if line > 0 => error.placed(|| Position::line(line)),
1061        _ => error,
1062    }
1063}
1064
1065// ------------------------------------------------------------ text helpers
1066
1067/// The items before, at, after and two after a place.
1068pub type Context<T> = (Option<T>, T, Option<T>, Option<T>);
1069
1070/// music21's `_getLinearContext`: the items before, at, after and two after
1071/// `index`.
1072///
1073/// ```
1074/// use music21::abc::step::linear_context;
1075///
1076/// let chars: Vec<char> = "12345".chars().collect();
1077/// assert_eq!(linear_context(&chars, 3)?, (Some('3'), '4', Some('5'), None));
1078/// # Ok::<(), music21::Error>(())
1079/// ```
1080pub fn linear_context<T: Clone>(source: &[T], index: usize) -> Result<Context<T>> {
1081    let Some(here) = source.get(index) else {
1082        return Err(abc_error(format!(
1083            "bad index value {index}, max is {}",
1084            source.len() as i64 - 1
1085        )));
1086    };
1087    let before = index.checked_sub(1).and_then(|at| source.get(at)).cloned();
1088    Ok((
1089        before,
1090        here.clone(),
1091        source.get(index + 1).cloned(),
1092        source.get(index + 2).cloned(),
1093    ))
1094}
1095
1096/// music21's `_getNextLineBreak`: where the next line break after `index`
1097/// stands, or the end.
1098pub fn next_line_break(chars: &[char], index: usize) -> usize {
1099    (index + 1..chars.len())
1100        .find(|at| chars[*at] == '\n')
1101        .unwrap_or(chars.len())
1102}
1103
1104/// music21's `startsMetadata`: a capital letter, or `w`, then a colon, then
1105/// something other than a barline.
1106pub fn starts_metadata(c: char, next: Option<char>, next_next: Option<char>) -> bool {
1107    if next != Some(':') {
1108        return false;
1109    }
1110    match next_next {
1111        None | Some('|') => false,
1112        Some(_) => c == 'w' || (c.is_alphabetic() && c.is_uppercase()),
1113    }
1114}
1115
1116/// A comment read by [`comment_at`].
1117#[derive(Clone, Debug, PartialEq, Eq)]
1118pub struct Comment {
1119    /// How many characters after the `%` the comment runs on.
1120    pub skip: usize,
1121    /// A `%%key value` directive's key and value.
1122    pub directive: Option<(String, String)>,
1123}
1124
1125/// music21's `processComment`: the comment at `pos`, to the end of its line.
1126pub fn comment_at(chars: &[char], pos: usize) -> Comment {
1127    let end = next_line_break(chars, pos);
1128    let skip = end.saturating_sub(pos + 1);
1129    let line: String = chars[pos.min(end)..end].iter().collect();
1130    Comment {
1131        skip,
1132        directive: directive_of(&line),
1133    }
1134}
1135
1136/// `^%%([a-z\-]+)\s+(\S+)`: a directive's key and value.
1137fn directive_of(line: &str) -> Option<(String, String)> {
1138    let directive = line.strip_prefix("%%")?;
1139    let key: String = directive
1140        .chars()
1141        .take_while(|c| c.is_ascii_lowercase() || *c == '-')
1142        .collect();
1143    let after = &directive[key.len()..];
1144    if key.is_empty() || !after.starts_with(char::is_whitespace) {
1145        return None;
1146    }
1147    let value = after.split_whitespace().next()?;
1148    Some((key, value.to_string()))
1149}
1150
1151/// `%abc-(\d+)\.(\d+)\.?(\d+)?` searched for: the first ABC version named.
1152pub fn version_in(text: &str) -> Option<(u32, u32, u32)> {
1153    let digits = |text: &str| -> usize { text.chars().take_while(char::is_ascii_digit).count() };
1154    for (at, _) in text.match_indices("%abc-") {
1155        let rest = &text[at + 5..];
1156        let major_end = digits(rest);
1157        if major_end == 0 || !rest[major_end..].starts_with('.') {
1158            continue;
1159        }
1160        let minor = &rest[major_end + 1..];
1161        let minor_end = digits(minor);
1162        if minor_end == 0 {
1163            continue;
1164        }
1165        let tail = minor[minor_end..]
1166            .strip_prefix('.')
1167            .unwrap_or(&minor[minor_end..]);
1168        let patch_end = digits(tail);
1169        let (Ok(major), Ok(minor_number)) = (rest[..major_end].parse(), minor[..minor_end].parse())
1170        else {
1171            continue;
1172        };
1173        let patch = tail[..patch_end].parse().unwrap_or(0);
1174        return Some((major, minor_number, patch));
1175    }
1176    None
1177}
1178
1179/// music21's `_buildMeasureBoundaryIndices`: the start and end of each
1180/// measure from the places of its barlines, a span of one passed over.
1181///
1182/// ```
1183/// use music21::abc::step::measure_boundaries;
1184///
1185/// assert_eq!(measure_boundaries(&[8, 12, 13, 16], 20), [(0, 8), (8, 12), (13, 16), (16, 20)]);
1186/// ```
1187pub fn measure_boundaries(positions: &[usize], last_valid: usize) -> Vec<(usize, usize)> {
1188    let Some(first) = positions.first().copied() else {
1189        return Vec::new();
1190    };
1191    let mut pairs = vec![(0, first)];
1192    let mut start = first;
1193    for end in positions.iter().skip(1).copied() {
1194        if end == start + 1 {
1195            start = end;
1196            continue;
1197        }
1198        pairs.push((start, end));
1199        start = end;
1200    }
1201    if start != last_valid {
1202        pairs.push((start, last_valid));
1203    }
1204    pairs
1205}
1206
1207/// One handler of [`merge_plan`]'s.
1208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1209pub enum Merge {
1210    /// Every handler joined into one.
1211    Whole,
1212    /// The handler at this place, as it is.
1213    Kept(usize),
1214    /// The handler at this place joined to the one after it.
1215    Pair(usize),
1216}
1217
1218/// music21's `mergeLeadingMetaData`, given whether each bar's handler holds
1219/// notes: a handler of nothing but metadata is joined to the one after it,
1220/// and a tune of one measure or none is one handler.
1221pub fn merge_plan(has_notes: &[bool]) -> Vec<Merge> {
1222    let sounding = has_notes.iter().filter(|holds| **holds).count();
1223    if sounding <= 1 {
1224        return vec![Merge::Whole];
1225    }
1226    let mut plan = Vec::new();
1227    let mut index = 0;
1228    while index < has_notes.len() {
1229        if !has_notes[index] && index != has_notes.len() - 1 {
1230            plan.push(Merge::Pair(index));
1231            index += 2;
1232        } else {
1233            plan.push(Merge::Kept(index));
1234            index += 1;
1235        }
1236    }
1237    plan
1238}
1239
1240/// music21's `ABCFile.extractReferenceNumber`: the lines of one tune, and
1241/// how many lines of the text stand before them.
1242pub fn extract_reference_number(text: &str, number: IntegerType) -> Result<(usize, String)> {
1243    let mut collected = Vec::new();
1244    let mut gathering = false;
1245    let mut before = 0;
1246    for line in text.split('\n') {
1247        let starts = line.trim().starts_with("X:");
1248        if starts && !gathering {
1249            let named = line.replace(' ', "");
1250            let named = named.trim_end().trim_start_matches("X:");
1251            if named.parse::<IntegerType>() == Ok(number) {
1252                gathering = true;
1253            }
1254        } else if starts && gathering {
1255            break;
1256        }
1257        if gathering {
1258            collected.push(line);
1259        } else if collected.is_empty() {
1260            before += 1;
1261        }
1262    }
1263    if collected.is_empty() {
1264        return Err(abc_error(format!(
1265            "cannot find requested reference number in source file: {number}"
1266        ))
1267        .of_kind(FormatErrorKind::NotFound));
1268    }
1269    Ok((before, collected.join("\n")))
1270}
1271
1272// ----------------------------------------------------------------- handler
1273
1274/// A spanner as the handler makes one: what kind, and the notes it joins.
1275#[derive(Clone, Debug)]
1276pub struct Spanning {
1277    /// A slur, crescendo or diminuendo.
1278    pub kind: SpannerKind,
1279    pub(super) uids: Vec<usize>,
1280    /// The notes it took that no stream holds, by their uid: a grace
1281    /// note's own, which music21 copies as the grace it places.
1282    pub(super) strays: Vec<(usize, StreamElement)>,
1283    /// Where its part had got to when it opened, which is where music21
1284    /// appends it to the part.
1285    pub(super) offset: FloatType,
1286}
1287
1288impl Spanning {
1289    /// A spanner of `kind` joining nothing yet.
1290    pub fn new(kind: SpannerKind) -> Self {
1291        Self {
1292            kind,
1293            uids: Vec::new(),
1294            strays: Vec::new(),
1295            offset: 0.0,
1296        }
1297    }
1298}
1299
1300/// A measure of [`Handler::split_by_measure`]'s, by token index.
1301#[derive(Clone, Debug, PartialEq, Eq)]
1302pub struct MeasureSplit {
1303    /// The tokens inside the measure.
1304    pub tokens: Range<usize>,
1305    /// The bar opening it.
1306    pub left: Option<usize>,
1307    /// The bar closing it.
1308    pub right: Option<usize>,
1309}
1310
1311/// music21's `ABCHandler`: the tokens of a text and what reading them keeps.
1312#[derive(Clone, Debug, Default)]
1313pub struct Handler {
1314    /// The ABC version read as: `(1, 3, 0)` and the like.
1315    pub version: (u32, u32, u32),
1316    /// The `%%key value` directives read, in order.
1317    pub directives: Vec<(String, String)>,
1318    /// The tokens, in the order of the text.
1319    pub tokens: Vec<Token>,
1320    /// The spanners still open after [`Handler::process`], by where they
1321    /// stand among those it handed back.
1322    pub active: Vec<usize>,
1323}
1324
1325impl Handler {
1326    /// A handler of no tokens, reading as ABC `version`.
1327    pub fn new(version: (u32, u32, u32)) -> Self {
1328        Self {
1329            version,
1330            ..Self::default()
1331        }
1332    }
1333
1334    /// music21's `_accidentalPropagation`: `not`, `pitch` or `octave`.
1335    pub fn accidental_propagation(&self) -> &str {
1336        if self.version < PROPAGATING_VERSION {
1337            return "not";
1338        }
1339        self.directives
1340            .iter()
1341            .rev()
1342            .find(|(key, _)| key == "propagate-accidentals")
1343            .map_or("pitch", |(_, value)| value.as_str())
1344    }
1345
1346    /// music21's `parseHeaderForVersionInformation`: the version named by
1347    /// `%abc-2.1` in `text`.
1348    pub fn read_version(&mut self, text: &str) {
1349        if let Some(version) = version_in(text) {
1350            self.version = version;
1351        }
1352    }
1353
1354    /// music21's `barlineTokenFilter`: a bar written as two in one, each
1355    /// unread.
1356    pub fn bar_tokens(text: &str) -> Vec<Bar> {
1357        let pair = match text {
1358            "::" => Some((":|", "|:")),
1359            "|1" => Some(("|", "[1")),
1360            "|2" => Some(("|", "[2")),
1361            ":|1" => Some((":|", "[1")),
1362            ":|2" => Some((":|", "[2")),
1363            _ => None,
1364        };
1365        match pair {
1366            Some((first, second)) => vec![Bar::new(first), Bar::new(second)],
1367            None => vec![Bar::new(text)],
1368        }
1369    }
1370
1371    /// music21's `tokenize`: the tokens of `source` added to the handler's,
1372    /// what goes wrong placed at its line and column.
1373    pub fn tokenize(&mut self, source: &str) -> Result<()> {
1374        self.read_tokens(source).map_err(|(at, error)| {
1375            let byte = source
1376                .char_indices()
1377                .nth(at)
1378                .map_or(source.len(), |(byte, _)| byte);
1379            error.placed(|| Position::in_text(source, byte))
1380        })
1381    }
1382
1383    /// The tokens of `source`, or what went wrong and the character it
1384    /// went wrong at.
1385    fn read_tokens(&mut self, source: &str) -> std::result::Result<(), (usize, Error)> {
1386        let src: Vec<char> = source.chars().collect();
1387        let len = src.len();
1388        // Where each line starts, to tell a token its line.
1389        let line_starts: Vec<usize> = std::iter::once(0)
1390            .chain((0..len).filter(|at| src[*at] == '\n').map(|at| at + 1))
1391            .collect();
1392        let line_of = |at: usize| line_starts.partition_point(|start| *start <= at);
1393        let at = |index: usize| src.get(index).copied();
1394        let slice =
1395            |from: usize, to: usize| -> String { src[from.min(len)..to.min(len)].iter().collect() };
1396
1397        let mut active_chord_symbol = String::new();
1398        let mut accidentalized: Vec<(String, String)> = Vec::new();
1399        let mut accidental = String::new();
1400        let mut abc_pitch = String::new();
1401        let mut pos = 0usize;
1402        while pos < len {
1403            let c = src[pos];
1404            let next = at(pos + 1);
1405            let next_next = at(pos + 2);
1406            // What is taken past this character.
1407            let mut skip = 0usize;
1408
1409            // A comment, or a directive, to the end of its line.
1410            if c == '%' {
1411                let comment = comment_at(&src, pos);
1412                if let Some(directive) = comment.directive {
1413                    self.directives.push(directive);
1414                }
1415                pos += comment.skip + 1;
1416                continue;
1417            }
1418
1419            if starts_metadata(c, next, next_next) {
1420                let end = next_line_break(&src, pos);
1421                let mut line = AbcMetadata::new(slice(pos, end).trim());
1422                line.line = line_of(pos);
1423                self.tokens.push(Token::Metadata(line));
1424                pos = end;
1425                continue;
1426            }
1427
1428            if !c.is_whitespace() && !c.is_alphanumeric() && c != '~' && c != '(' {
1429                let mut matched = None;
1430                for (text, _) in BARS {
1431                    let wanted: Vec<char> = text.chars().collect();
1432                    let fits = match wanted.len() {
1433                        3 => next.is_some() && next_next.is_some() && slice(pos, pos + 3) == text,
1434                        2 => next.is_some() && slice(pos, pos + 2) == text,
1435                        _ => c == wanted[0],
1436                    };
1437                    if fits {
1438                        matched = Some(wanted.len());
1439                        break;
1440                    }
1441                }
1442                if let Some(length) = matched {
1443                    accidentalized.clear();
1444                    accidental.clear();
1445                    for bar in Self::bar_tokens(&slice(pos, pos + length)) {
1446                        self.tokens.push(Token::Bar(bar));
1447                    }
1448                    pos += length;
1449                    continue;
1450                }
1451            }
1452
1453            if c == '(' && next.is_some_and(|c| c.is_ascii_digit()) {
1454                let mut j = pos + 2;
1455                if j >= len {
1456                    return Err((
1457                        pos,
1458                        abc_error(format!("bad index value {j}, max is {}", len - 1)),
1459                    ));
1460                }
1461                if at(j) == Some(':') {
1462                    j += 1;
1463                    if at(j).is_some_and(|c| c.is_ascii_digit()) {
1464                        j += 1;
1465                    }
1466                    if at(j) == Some(':') {
1467                        j += 1;
1468                        if at(j).is_some_and(|c| c.is_ascii_digit()) {
1469                            j += 1;
1470                        }
1471                    }
1472                }
1473                let mut tuplet = AbcTuplet::new(&slice(pos, j));
1474                tuplet.line = line_of(pos);
1475                self.tokens.push(Token::Tuplet(tuplet));
1476                pos = j;
1477                continue;
1478            }
1479
1480            if c == '<' || c == '>' {
1481                let mut j = pos + 1;
1482                while j + 1 < len && matches!(src[j], '<' | '>') {
1483                    j += 1;
1484                }
1485                self.tokens.push(Token::BrokenRhythm(BrokenRhythm {
1486                    src: slice(pos, j),
1487                    data: String::new(),
1488                }));
1489                pos = j;
1490                continue;
1491            }
1492
1493            if c == '!' {
1494                let mut j = pos + 1;
1495                while j < pos + 20 && j < len {
1496                    if src[j] == '!' {
1497                        match slice(pos, j + 1).as_str() {
1498                            "!crescendo(!" => self
1499                                .tokens
1500                                .push(Token::SpannerStart(SpannerKind::Crescendo, None)),
1501                            "!diminuendo(!" => self
1502                                .tokens
1503                                .push(Token::SpannerStart(SpannerKind::Diminuendo, None)),
1504                            "!crescendo)!" | "!diminuendo)!" => {
1505                                self.tokens.push(Token::ParenStop(Closes::Hairpin));
1506                            }
1507                            _ => {}
1508                        }
1509                        skip = j - pos;
1510                        break;
1511                    }
1512                    j += 1;
1513                }
1514                pos += skip + 1;
1515                continue;
1516            }
1517
1518            if c == '(' && next.is_some() {
1519                self.tokens
1520                    .push(Token::SpannerStart(SpannerKind::Slur, None));
1521                pos += 1;
1522                continue;
1523            }
1524            let simple = match c {
1525                ')' => Some(Token::ParenStop(Closes::Slur)),
1526                '-' => Some(Token::Tie),
1527                _ => None,
1528            };
1529            if let Some(token) = simple {
1530                self.tokens.push(token);
1531                pos += 1;
1532                continue;
1533            }
1534
1535            if c == '"' {
1536                let mut j = pos + 1;
1537                while j + 1 < len && src[j] != '"' {
1538                    j += 1;
1539                }
1540                j += 1;
1541                active_chord_symbol.push_str(&slice(pos, j));
1542                pos = j.max(pos + 1);
1543                continue;
1544            }
1545
1546            if c == '[' {
1547                let mut j = pos + 1;
1548                while j + 1 < len && src[j] != ']' {
1549                    j += 1;
1550                }
1551                j += 1;
1552                while j < len && (src[j].is_ascii_digit() || src[j] == '/') {
1553                    j += 1;
1554                }
1555                let collected = format!("{}{}", active_chord_symbol, slice(pos, j));
1556                active_chord_symbol.clear();
1557                let mut chord = AbcNote::chord(&collected);
1558                chord.line = line_of(pos);
1559                self.tokens.push(Token::Note(Box::new(chord)));
1560                pos = j.max(pos + 1);
1561                continue;
1562            }
1563
1564            let mark = match c {
1565                '.' => Some(Token::Staccato),
1566                'u' => Some(Token::Upbow),
1567                '{' => Some(Token::GraceStart),
1568                '}' => Some(Token::GraceStop),
1569                'v' => Some(Token::Downbow),
1570                'K' => Some(Token::Accent),
1571                'k' => Some(Token::Straccent),
1572                'M' => Some(Token::Tenuto),
1573                _ => None,
1574            };
1575            if let Some(token) = mark {
1576                self.tokens.push(token);
1577                pos += 1;
1578                continue;
1579            }
1580
1581            if c.is_alphabetic() || "~^=_".contains(c) {
1582                let mut found = c.is_alphabetic() && !DECORATIONS.contains(c);
1583                if found {
1584                    abc_pitch = c.to_string();
1585                }
1586                if ACCIDENTALS.contains(c) {
1587                    accidental = c.to_string();
1588                }
1589                let mut j = pos + 1;
1590                while j < len {
1591                    let here = src[j];
1592                    if !found && DECORATIONS.contains(here) {
1593                        j += 1;
1594                        // music21 looks at the character after the one it
1595                        // has just passed.
1596                        match at(j) {
1597                            Some(after) if ACCIDENTALS.contains(after) => accidental.push(after),
1598                            Some(_) => {}
1599                            None => {
1600                                return Err((pos, abc_error("a decoration ends the text")));
1601                            }
1602                        }
1603                    } else if !found && here.is_alphabetic() && !"~wuvhHLTSN".contains(here) {
1604                        found = true;
1605                        abc_pitch = here.to_string();
1606                        j += 1;
1607                    } else if here.is_ascii_digit() || ",/'".contains(here) {
1608                        if here == ',' || here == '\'' {
1609                            abc_pitch.push(here);
1610                        }
1611                        j += 1;
1612                    } else {
1613                        break;
1614                    }
1615                }
1616                let collected = format!("{}{}", active_chord_symbol, slice(pos, j));
1617                active_chord_symbol.clear();
1618
1619                if !is_passed_over(&collected) {
1620                    let mut carried = String::new();
1621                    if !abc_pitch.is_empty() {
1622                        let class: String = abc_pitch
1623                            .chars()
1624                            .take(1)
1625                            .flat_map(char::to_uppercase)
1626                            .collect();
1627                        let key = match self.accidental_propagation() {
1628                            "octave" => Some(abc_pitch.clone()),
1629                            "pitch" => Some(class),
1630                            _ => None,
1631                        };
1632                        if !accidental.is_empty() {
1633                            if let Some(key) = key {
1634                                accidentalized.retain(|(known, _)| *known != key);
1635                                accidentalized.push((key, accidental.clone()));
1636                            }
1637                            accidental.clear();
1638                        } else if let Some(key) = key
1639                            && let Some((_, held)) =
1640                                accidentalized.iter().find(|(known, _)| *known == key)
1641                        {
1642                            carried = held.clone();
1643                        }
1644                    }
1645                    let mut note = AbcNote::new(&collected, &carried);
1646                    note.line = line_of(pos);
1647                    self.tokens.push(Token::Note(Box::new(note)));
1648                }
1649                pos = j.max(pos + 1);
1650                continue;
1651            }
1652
1653            pos += 1;
1654        }
1655        Ok(())
1656    }
1657
1658    /// music21's `tokenProcess`: each token pre-parsed, told what is in
1659    /// force where it stands, and then parsed. Hands back the spanners the
1660    /// tokens started; those left open are in `active`.
1661    pub fn process(&mut self) -> Result<Vec<Spanning>> {
1662        for token in &mut self.tokens {
1663            match token {
1664                Token::Metadata(line) => line.pre_parse(),
1665                Token::BrokenRhythm(mark) => mark.pre_parse(),
1666                _ => {}
1667            }
1668        }
1669
1670        let mut spanners: Vec<Spanning> = Vec::new();
1671        let mut active_parens: Vec<SpannerKind> = Vec::new();
1672        self.active.clear();
1673        let mut default_length: Option<FloatType> = None;
1674        let mut key: Option<KeySignature> = None;
1675        let mut meter: Option<TimeSignature> = None;
1676        // The tuplet token in force and its tuplet.
1677        let mut tuplet: Option<(usize, Tuplet)> = None;
1678        let mut tie_waiting = false;
1679        let mut marks: Vec<&'static str> = Vec::new();
1680        let mut in_grace = false;
1681        let mut last_note: Option<usize> = None;
1682
1683        for index in 0..self.tokens.len() {
1684            let previous_is_note = index > 0 && self.tokens[index - 1].is_note();
1685            let next_is_note = self.tokens.get(index + 1).is_some_and(Token::is_note);
1686            let here = |error: Error, tokens: &[Token]| at_line(error, tokens[index].line());
1687            match self.tokens[index].clone() {
1688                Token::Metadata(line) => {
1689                    if line.tag == "M" {
1690                        meter = line.meter().map_err(|e| here(e, &self.tokens))?;
1691                    }
1692                    if line.tag == "L" || (line.tag == "M" && default_length.is_none()) {
1693                        let read = line.default_quarter_length();
1694                        default_length = Some(read.map_err(|e| here(e, &self.tokens))?);
1695                    } else if line.tag == "K" {
1696                        let (sharps, _) =
1697                            line.key_parameters().map_err(|e| here(e, &self.tokens))?;
1698                        key = Some(KeySignature::new(sharps));
1699                    }
1700                    if line.tag == "X" {
1701                        active_parens.clear();
1702                        self.active.clear();
1703                    }
1704                }
1705                Token::BrokenRhythm(mark) => {
1706                    if previous_is_note && next_is_note {
1707                        if let Token::Note(note) = &mut self.tokens[index - 1] {
1708                            note.broken_rhythm = Some((mark.data.clone(), Side::Left));
1709                        }
1710                        if let Token::Note(note) = &mut self.tokens[index + 1] {
1711                            note.broken_rhythm = Some((mark.data, Side::Right));
1712                        }
1713                    }
1714                }
1715                Token::Tuplet(_) => {
1716                    let Token::Tuplet(held) = &mut self.tokens[index] else {
1717                        continue;
1718                    };
1719                    let made = held
1720                        .update_ratio(meter.as_ref())
1721                        .and_then(|()| held.update_note_count());
1722                    let made = made.map_err(|e| here(e, &self.tokens))?;
1723                    tuplet = Some((index, made));
1724                }
1725                Token::SpannerStart(kind, _) => {
1726                    spanners.push(Spanning::new(kind));
1727                    let made = spanners.len() - 1;
1728                    self.tokens[index] = Token::SpannerStart(kind, Some(made));
1729                    self.active.push(made);
1730                    active_parens.push(kind);
1731                }
1732                Token::ParenStop(closes) => {
1733                    // Slurs and hairpins may overlap, so each stop ends the
1734                    // latest of its own kind.
1735                    let closed = |kind: &SpannerKind| match closes {
1736                        Closes::Slur => *kind == SpannerKind::Slur,
1737                        Closes::Hairpin => *kind != SpannerKind::Slur,
1738                    };
1739                    if let Some(at) = active_parens.iter().rposition(closed) {
1740                        active_parens.remove(at);
1741                        self.active.remove(at);
1742                    }
1743                }
1744                Token::Tie => {
1745                    if let Some(last) = last_note
1746                        && let Token::Note(note) = &mut self.tokens[last]
1747                    {
1748                        note.tie = Some(if note.tie == Some(TieType::Stop) {
1749                            TieType::Continue
1750                        } else {
1751                            TieType::Start
1752                        });
1753                    }
1754                    tie_waiting = true;
1755                }
1756                Token::Staccato => marks.push("staccato"),
1757                Token::Upbow => marks.push("upbow"),
1758                Token::Downbow => marks.push("downbow"),
1759                Token::Accent => marks.push("accent"),
1760                Token::Straccent => marks.push("strongaccent"),
1761                Token::Tenuto => marks.push("tenuto"),
1762                Token::GraceStart => in_grace = true,
1763                Token::GraceStop => in_grace = false,
1764                Token::Bar(_) => {}
1765                Token::Note(_) => {
1766                    let Some(default_length) = default_length else {
1767                        return Err(here(
1768                            abc_error(
1769                                "no active default note length provided for note processing.",
1770                            ),
1771                            &self.tokens,
1772                        ));
1773                    };
1774                    // The tuplet's count, run down; nought ends it.
1775                    let mut in_tuplet = None;
1776                    if let Some((at, made)) = tuplet
1777                        && let Token::Tuplet(held) = &mut self.tokens[at]
1778                    {
1779                        if held.note_count == 0 {
1780                            tuplet = None;
1781                        } else {
1782                            held.note_count -= 1;
1783                            in_tuplet = Some(made);
1784                        }
1785                    }
1786                    let Token::Note(note) = &mut self.tokens[index] else {
1787                        continue;
1788                    };
1789                    note.default_quarter_length = Some(default_length);
1790                    note.key = key.clone();
1791                    note.spanners = self.active.clone();
1792                    if std::mem::take(&mut tie_waiting) {
1793                        note.tie = Some(TieType::Stop);
1794                    }
1795                    // Each kind of mark once, in music21's order.
1796                    for mark in ARTICULATIONS {
1797                        if marks.contains(&mark) {
1798                            note.articulations.push(mark.to_string());
1799                        }
1800                    }
1801                    marks.clear();
1802                    if in_grace {
1803                        note.in_grace = true;
1804                    }
1805                    if in_tuplet.is_some() {
1806                        note.tuplet = in_tuplet;
1807                    }
1808                    last_note = Some(index);
1809                }
1810            }
1811        }
1812
1813        // The last pass: bars and notes read.
1814        for token in &mut self.tokens {
1815            match token {
1816                Token::Bar(bar) => bar.parse(),
1817                Token::Note(note) => {
1818                    let line = Some(note.line);
1819                    note.parse(None, None)
1820                        .map_err(|error| at_line(error, line))?;
1821                }
1822                _ => {}
1823            }
1824        }
1825        Ok(spanners)
1826    }
1827
1828    fn reference_lines(&self) -> impl Iterator<Item = &str> {
1829        self.tokens
1830            .iter()
1831            .filter_map(Token::metadata)
1832            .filter(|(tag, _)| *tag == "X")
1833            .map(|(_, data)| data)
1834    }
1835
1836    /// music21's `definesReferenceNumbers`: more than one `X:`.
1837    pub fn defines_reference_numbers(&self) -> bool {
1838        self.reference_lines().count() > 1
1839    }
1840
1841    /// music21's `getReferenceNumber`: the first `X:` line's data.
1842    pub fn reference_number(&self) -> Option<&str> {
1843        self.reference_lines().next()
1844    }
1845
1846    /// music21's `getTitle`: the first `T:` line's data.
1847    pub fn title(&self) -> Option<&str> {
1848        self.tokens
1849            .iter()
1850            .filter_map(Token::metadata)
1851            .find(|(tag, _)| *tag == "T")
1852            .map(|(_, data)| data)
1853    }
1854
1855    /// music21's `splitByReferenceNumber`: each tune's tokens by index, the
1856    /// tokens before the first `X:` in front of each, keyed by number in
1857    /// the order the numbers first stand. A number met again takes the
1858    /// later tune. With no `X:` at all, the one tune has no number.
1859    pub fn split_by_reference_number(&self) -> Result<Vec<(Option<IntegerType>, Vec<usize>)>> {
1860        let mut before: Vec<usize> = Vec::new();
1861        let mut tunes: Vec<(Option<IntegerType>, Vec<usize>)> = Vec::new();
1862        let mut current: Option<usize> = None;
1863        for (index, token) in self.tokens.iter().enumerate() {
1864            if let Some(("X", data)) = token.metadata() {
1865                let number = data.trim().parse::<IntegerType>().map_err(|_| {
1866                    let refused = abc_error(format!("the reference number {data:?} is no number"));
1867                    at_line(refused, token.line())
1868                })?;
1869                current = match tunes.iter().position(|(known, _)| *known == Some(number)) {
1870                    Some(place) => {
1871                        tunes[place].1.clear();
1872                        Some(place)
1873                    }
1874                    None => {
1875                        tunes.push((Some(number), Vec::new()));
1876                        Some(tunes.len() - 1)
1877                    }
1878                };
1879            }
1880            match current {
1881                Some(place) => tunes[place].1.push(index),
1882                None => before.push(index),
1883            }
1884        }
1885        if tunes.is_empty() {
1886            tunes.push((None, Vec::new()));
1887        }
1888        for (_, indices) in &mut tunes {
1889            let mut joined = before.clone();
1890            joined.append(indices);
1891            *indices = joined;
1892        }
1893        Ok(tunes)
1894    }
1895
1896    /// music21's `definesMeasures`: two plain barlines or more.
1897    pub fn defines_measures(&self) -> bool {
1898        self.tokens
1899            .iter()
1900            .filter(|token| matches!(token, Token::Bar(bar) if bar.is_regular()))
1901            .count()
1902            >= 2
1903    }
1904
1905    /// music21's `hasNotes`.
1906    pub fn has_notes(&self) -> bool {
1907        has_notes(&self.tokens)
1908    }
1909
1910    /// music21's `splitByVoice`: the header, and the tokens of each voice
1911    /// whose `V:` line starts with a digit; all the tokens where there are
1912    /// fewer than two voices.
1913    pub fn split_by_voice(&self) -> Vec<Range<usize>> {
1914        let positions: Vec<usize> = self
1915            .tokens
1916            .iter()
1917            .enumerate()
1918            .filter(|(_, token)| {
1919                token.metadata().is_some_and(|(tag, data)| {
1920                    tag == "V" && data.chars().next().is_some_and(|c| c.is_ascii_digit())
1921                })
1922            })
1923            .map(|(index, _)| index)
1924            .collect();
1925        if positions.len() <= 1 {
1926            return std::iter::once(0..self.tokens.len()).collect();
1927        }
1928        let mut pieces = Vec::with_capacity(positions.len() + 1);
1929        pieces.push(0..positions[0]);
1930        for pair in positions.windows(2) {
1931            pieces.push(pair[0]..pair[1]);
1932        }
1933        pieces.push(positions[positions.len() - 1]..self.tokens.len());
1934        pieces
1935    }
1936
1937    /// music21's `tokensToBarIndices`: where each bar stands, and each line
1938    /// of metadata a note follows.
1939    pub fn bar_indices(&self) -> Vec<usize> {
1940        let tokens = &self.tokens;
1941        (0..tokens.len())
1942            .filter(|index| {
1943                let note_follows = tokens.get(index + 1).is_some_and(Token::is_note);
1944                match &tokens[*index] {
1945                    Token::Bar(_) => true,
1946                    Token::Metadata(_) => note_follows,
1947                    _ => false,
1948                }
1949            })
1950            .collect()
1951    }
1952
1953    /// music21's `splitByMeasure`: the tokens of each measure and the bars
1954    /// either side, a repeat's end kept for the measure before it and a
1955    /// repeat's start for the one after.
1956    pub fn split_by_measure(&self) -> Vec<MeasureSplit> {
1957        let tokens = &self.tokens;
1958        if tokens.is_empty() {
1959            return Vec::new();
1960        }
1961        let mut splits = Vec::new();
1962        for (x, y) in measure_boundaries(&self.bar_indices(), tokens.len() - 1) {
1963            let mut split = MeasureSplit {
1964                tokens: 0..0,
1965                left: None,
1966                right: None,
1967            };
1968            let mut from = x;
1969            let mut to = y as isize;
1970            match &tokens[x] {
1971                Token::Bar(bar) => {
1972                    if !(bar.is_repeat() && bar.repeat_form == "end") {
1973                        split.left = Some(x);
1974                    }
1975                    from = x + 1;
1976                }
1977                Token::Metadata(_) if x != 0 => from = x + 1,
1978                _ => {}
1979            }
1980            match &tokens[y] {
1981                Token::Bar(bar) => {
1982                    if !(bar.is_repeat() && bar.repeat_form == "start") {
1983                        split.right = Some(y);
1984                    }
1985                    to = y as isize - 1;
1986                }
1987                Token::Metadata(_) => {}
1988                token => {
1989                    if !(token.is_note() && y == tokens.len() - 1) {
1990                        to = y as isize - 1;
1991                    }
1992                }
1993            }
1994            let end = (to + 1).max(0) as usize;
1995            if from >= end {
1996                continue;
1997            }
1998            split.tokens = from..end;
1999            splits.push(split);
2000        }
2001        splits
2002    }
2003}
2004
2005/// Whether any of the tokens is a note, rest or chord.
2006pub(super) fn has_notes(tokens: &[Token]) -> bool {
2007    tokens.iter().any(Token::is_note)
2008}
2009
2010/// Whether music21 drops what it collected as a note: decorations it does
2011/// not read, and marks it reads as errors.
2012fn is_passed_over(collected: &str) -> bool {
2013    const PASSED: [&str; 38] = [
2014        "w", "u", "v", "v.", "h", "H", "vk", "uk", "U", "~", ".", "=", "V", "v.", "S", "s", "i",
2015        "I", "ui", "u.", "Q", "Hy", "Hx", "r", "m", "M", "n", "N", "o", "O", "P", "l", "L", "R",
2016        "y", "T", "t", "x",
2017    ];
2018    let chars: Vec<char> = collected.chars().collect();
2019    let last = chars.last().copied().unwrap_or(' ');
2020    PASSED.contains(&collected)
2021        || collected == "Z"
2022        || (collected.starts_with('"')
2023            && ("uvkKQ.yTwhx".contains(last) || collected.ends_with("v.")))
2024        || collected.starts_with('x')
2025        || collected.starts_with('H')
2026        || collected.starts_with('Z')
2027        || (chars.len() > 1 && chars[0] == '=' && chars[1].is_ascii_digit())
2028}
2029
2030#[cfg(test)]
2031mod tests {
2032    use super::*;
2033
2034    fn tokens_of(text: &str) -> Vec<Token> {
2035        let mut handler = Handler::new(DEFAULT_VERSION);
2036        handler.tokenize(text).unwrap();
2037        handler.tokens
2038    }
2039
2040    fn processed(text: &str) -> Handler {
2041        let mut handler = Handler::new(DEFAULT_VERSION);
2042        handler.tokenize(text).unwrap();
2043        handler.process().unwrap();
2044        handler
2045    }
2046
2047    #[test]
2048    fn a_bar_says_what_it_is() {
2049        // music21's `ABCBar.parse` docstring.
2050        let bar = Bar::parsed("|");
2051        assert!(bar.is_regular() && !bar.is_repeat());
2052        assert_eq!(bar.bar_type, "barline");
2053        let end = Bar::parsed(":|");
2054        assert!(end.is_repeat() && end.repeat_form == "end" && end.bar_style == "light-heavy");
2055        assert_eq!(Bar::parsed("[1").repeat_bracket(), Some(1));
2056        assert_eq!(
2057            Bar::parsed("||").barline().unwrap().bar_type(),
2058            BarlineType::Double
2059        );
2060        // Unread, or no bar at all, it is nothing.
2061        assert_eq!(Bar::new("|").bar_type, "");
2062        assert_eq!(Bar::parsed("hi").bar_type, "");
2063    }
2064
2065    #[test]
2066    fn text_is_cut_into_tokens_as_music21_cuts_it() {
2067        let tokens = tokens_of("M:6/8\nL:1/8\nK:G\nB3 A3 | (3GAB c2 :|\n");
2068        let kinds: Vec<&str> = tokens
2069            .iter()
2070            .map(|token| match token {
2071                Token::Metadata(_) => "meta",
2072                Token::Bar(_) => "bar",
2073                Token::Tuplet(_) => "tuplet",
2074                Token::Note(_) => "note",
2075                _ => "other",
2076            })
2077            .collect();
2078        assert_eq!(
2079            kinds,
2080            [
2081                "meta", "meta", "meta", "note", "note", "bar", "tuplet", "note", "note", "note",
2082                "note", "bar"
2083            ]
2084        );
2085        // A token keeps its text, and metadata is unread until processed.
2086        assert_eq!(tokens[0].src(), "M:6/8");
2087        assert_eq!(tokens[0].metadata(), Some(("", "")));
2088        let srcs: Vec<String> = tokens_of("(6::2f").iter().map(Token::src).collect();
2089        assert_eq!(srcs, ["(6::2", "f"]);
2090    }
2091
2092    #[test]
2093    fn a_comment_sets_a_directive_and_runs_to_the_line_end() {
2094        // music21's `processComment` docstring.
2095        let chars: Vec<char> = "\nHello % this is a comment\nBye\n".chars().collect();
2096        assert_eq!(comment_at(&chars, 6).skip, 19);
2097        let chars: Vec<char> = "%%abc-hello world".chars().collect();
2098        assert_eq!(
2099            comment_at(&chars, 0).directive,
2100            Some(("abc-hello".to_string(), "world".to_string()))
2101        );
2102        assert_eq!(version_in("x %abc-2.3.2"), Some((2, 3, 2)));
2103        assert_eq!(version_in("%abc-1.7"), Some((1, 7, 0)));
2104        assert_eq!(version_in("%abc-x %abc-2.1"), Some((2, 1, 0)));
2105    }
2106
2107    #[test]
2108    fn a_tuplet_counts_its_notes_down() {
2109        let handler = processed("L:1/8\n(3abcd\n");
2110        let Token::Tuplet(tuplet) = &handler.tokens[1] else {
2111            panic!("no tuplet");
2112        };
2113        assert_eq!((tuplet.actual, tuplet.normal, tuplet.note_count), (3, 2, 0));
2114        let in_tuplet: Vec<bool> = handler
2115            .tokens
2116            .iter()
2117            .filter_map(|token| match token {
2118                Token::Note(note) => Some(note.tuplet.is_some()),
2119                _ => None,
2120            })
2121            .collect();
2122        assert_eq!(in_tuplet, [true, true, true, false]);
2123        let mut bad = AbcTuplet::new("(10");
2124        let error = bad.update_ratio(None).unwrap_err();
2125        assert_eq!(
2126            error.to_string(),
2127            "ABC error: cannot handle tuplet of form: '(10'"
2128        );
2129    }
2130
2131    #[test]
2132    fn a_handler_is_cut_by_tune_voice_and_measure() {
2133        // music21's `splitByReferenceNumber` docstring.
2134        let text = "X:5\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||\
2135                    X:6\nM:6/8\nL:1/8\nK:G\nB3 A3 | G6 | B3 A3 | G6 ||";
2136        let handler = processed(&format!("O: Irish\n{text}"));
2137        let tunes = handler.split_by_reference_number().unwrap();
2138        let numbers: Vec<_> = tunes.iter().map(|(number, _)| *number).collect();
2139        assert_eq!(numbers, [Some(5), Some(6)]);
2140        assert_eq!(tunes[0].1.len(), 15);
2141        assert_eq!(tunes[1].1[0], 0);
2142        assert_eq!(handler.reference_number(), Some("5"));
2143
2144        let voices = processed("M:6/8\nL:1/8\nK:G\nV:1\nB3 A3 | G6 ||\nV:2\nD3 D3 | D6 ||");
2145        assert_eq!(voices.split_by_voice(), [0..3, 3..9, 9..15]);
2146
2147        let tune = processed("M:6/8\nL:1/8\nK:G\nc1D2");
2148        let splits = tune.split_by_measure();
2149        assert_eq!(splits.len(), 2);
2150        assert_eq!(splits[1].tokens, 3..5);
2151        let has: Vec<bool> = splits
2152            .iter()
2153            .map(|split| has_notes(&tune.tokens[split.tokens.clone()]))
2154            .collect();
2155        assert_eq!(merge_plan(&has), [Merge::Whole]);
2156        assert_eq!(
2157            merge_plan(&[false, true, true, false]),
2158            [Merge::Pair(0), Merge::Kept(2), Merge::Kept(3)]
2159        );
2160    }
2161
2162    /// Each note's source and the kinds of the spanners in force on it.
2163    fn spanners_of(body: &str) -> Vec<(String, Vec<SpannerKind>)> {
2164        let mut handler = Handler::new(DEFAULT_VERSION);
2165        handler
2166            .tokenize(&format!("X:1\nM:4/4\nL:1/8\nK:C\n{body}\n"))
2167            .unwrap();
2168        let spanners = handler.process().unwrap();
2169        handler
2170            .tokens
2171            .iter()
2172            .filter_map(|token| match token {
2173                Token::Note(note) => Some((
2174                    note.src.trim().to_string(),
2175                    note.spanners
2176                        .iter()
2177                        .map(|index| spanners[*index].kind)
2178                        .collect(),
2179                )),
2180                _ => None,
2181            })
2182            .collect()
2183    }
2184
2185    #[test]
2186    fn a_closing_mark_ends_the_latest_spanner_of_its_kind() {
2187        // music21's `testSlurAroundTuplet` (cuthbertLab #1798).
2188        use SpannerKind::{Crescendo, Diminuendo, Slur};
2189        let expect = |pairs: &[(&str, &[SpannerKind])]| -> Vec<(String, Vec<SpannerKind>)> {
2190            pairs
2191                .iter()
2192                .map(|(src, kinds)| (src.to_string(), kinds.to_vec()))
2193                .collect()
2194        };
2195        // A tuplet has no closing parenthesis, so ')' ends the slur.
2196        assert_eq!(
2197            spanners_of("(a(3bcd e) f|"),
2198            expect(&[
2199                ("a", &[Slur]),
2200                ("b", &[Slur]),
2201                ("c", &[Slur]),
2202                ("d", &[Slur]),
2203                ("e", &[Slur]),
2204                ("f", &[]),
2205            ])
2206        );
2207        assert_eq!(
2208            spanners_of("!crescendo(! (3abc d !crescendo)! e|"),
2209            expect(&[
2210                ("a", &[Crescendo]),
2211                ("b", &[Crescendo]),
2212                ("c", &[Crescendo]),
2213                ("d", &[Crescendo]),
2214                ("e", &[]),
2215            ])
2216        );
2217        // A slur and a crescendo can overlap without nesting.
2218        assert_eq!(
2219            spanners_of("(a !crescendo(! b) c !crescendo)! d|"),
2220            expect(&[
2221                ("a", &[Slur]),
2222                ("b", &[Slur, Crescendo]),
2223                ("c", &[Crescendo]),
2224                ("d", &[]),
2225            ])
2226        );
2227        assert_eq!(
2228            spanners_of("!diminuendo(! a (b !diminuendo)! c) d|"),
2229            expect(&[
2230                ("a", &[Diminuendo]),
2231                ("b", &[Diminuendo, Slur]),
2232                ("c", &[Slur]),
2233                ("d", &[]),
2234            ])
2235        );
2236    }
2237
2238    #[test]
2239    fn a_key_line_gives_its_sharps_and_mode() {
2240        // music21's `getKeySignatureParameters` docstring.
2241        assert_eq!(key_parameters("Eb").unwrap(), (-3, Some("major")));
2242        assert_eq!(
2243            key_parameters("A mixolydian").unwrap(),
2244            (2, Some("mixolydian"))
2245        );
2246        assert_eq!(key_parameters("F#m").unwrap(), (3, Some("minor")));
2247        assert_eq!(key_parameters("HP").unwrap(), (0, None));
2248        assert_eq!(key_parameters("Hp").unwrap(), (2, None));
2249        // Only a key line has a key.
2250        assert!(AbcMetadata::new("Q:40").key_parameters().is_err());
2251    }
2252
2253    #[test]
2254    fn a_length_is_read_against_the_default() {
2255        // music21's `getQuarterLength` docstring.
2256        let mut note = AbcNote::new("", "");
2257        note.default_quarter_length = Some(0.5);
2258        assert_eq!(note.quarter_length_of("f", None).unwrap(), 0.5);
2259        assert_eq!(note.quarter_length_of("f2", None).unwrap(), 1.0);
2260        assert_eq!(note.quarter_length_of("f/", None).unwrap(), 0.25);
2261        assert_eq!(note.quarter_length_of("f3/2", None).unwrap(), 0.75);
2262        note.broken_rhythm = Some((">".to_string(), Side::Left));
2263        assert_eq!(note.quarter_length_of("A", None).unwrap(), 0.75);
2264    }
2265
2266    #[test]
2267    fn a_pitch_takes_its_accidental_from_the_key() {
2268        let mut note = AbcNote::new("f", "");
2269        note.key = Some(KeySignature::new(1));
2270        assert_eq!(
2271            note.pitch_name("f", None).unwrap(),
2272            (Some("F#5".to_string()), Some(false))
2273        );
2274        assert_eq!(
2275            note.pitch_name("=f", None).unwrap(),
2276            (Some("Fn5".to_string()), Some(true))
2277        );
2278        assert_eq!(note.pitch_name("z", None).unwrap(), (None, None));
2279        assert_eq!(
2280            note.pitch_name("C,,", None).unwrap(),
2281            (Some("C2".to_string()), Some(false))
2282        );
2283        // A flat in the key is spelled as music21 spells it.
2284        let flats = KeySignature::new(-3);
2285        assert_eq!(
2286            note.pitch_name("B", Some(&flats)).unwrap(),
2287            (Some("B-4".to_string()), Some(false))
2288        );
2289        assert_eq!(
2290            note.pitch_name("x", None).unwrap_err().to_string(),
2291            "ABC error: cannot find any pitch information in: 'x'"
2292        );
2293    }
2294}