guitar-tab-generator 2.0.0

Generate fingerstyle guitar tabs based on the difficulty of different finger positions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use crate::{
    arrangement::{BeatVec, Line},
    guitar::{STD_6_STRING_TUNING_OPEN_PITCHES, create_string_tuning},
    pitch::Pitch,
    string_number::StringNumber,
};
use itertools::Itertools;
use memoize::memoize;
use regex::{Regex, RegexBuilder};
use serde::Serialize;
use std::{collections::BTreeMap, result::Result::Ok};
use std::{collections::HashSet, str::FromStr};
use strum::IntoEnumIterator;
use strum_macros::{EnumIter, EnumString};
use tsify_next::Tsify;
use wasm_bindgen::prelude::*;

const PITCH_PATTERN: &str =
    r"(?P<three_char_pitch>[A-G][#♯b♭][0-9])|(?P<two_char_pitch>[A-G][0-9])";

#[cfg(test)]
fn test_pitch_regex() -> Regex {
    RegexBuilder::new(PITCH_PATTERN)
        .case_insensitive(true)
        .build()
        .expect("Regex pattern should be valid")
}

/// Named tuning presets. Parsed case-insensitively from strings.
///
/// Additional variants may be added in a non-breaking release; the `#[non_exhaustive]`
/// attribute requires external matches to include a wildcard arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumString, EnumIter, Serialize, Tsify)]
#[strum(ascii_case_insensitive)]
#[tsify(into_wasm_abi)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum TuningName {
    OpenG,
    OpenD,
    C6,
    #[strum(serialize = "dsus4", serialize = "dadgad")]
    Dsus4,
    DropD,
    DropC,
    OpenC,
    DropB,
    OpenE,
}

/// Returns the supported `TuningName` variants, typed for JS consumption via tsify.
#[wasm_bindgen(js_name = "getTuningNames")]
#[must_use]
pub fn get_tuning_names() -> Vec<TuningName> {
    TuningName::iter().collect()
}

/// Returns the 6-element semitone offsets for a named tuning, relative to standard 6-string
/// tuning.
///
/// Accepts the case-insensitive literal `"standard"` as standard tuning (all-zero offsets).
/// Returns `TabError::TuningNameUnknown { value }` for any string that does not match a
/// `TuningName` variant or `"standard"`.
pub fn parse_tuning(tuning_name: &str) -> Result<[i8; 6], crate::error::TabError> {
    // Offsets are semitones per string relative to standard tuning, ordered string 1
    // (highest) to string 6 (lowest).
    match TuningName::from_str(tuning_name) {
        Ok(TuningName::OpenG) => Ok([-2, 0, 0, 0, -2, -2]),
        Ok(TuningName::OpenD) => Ok([-2, 0, 0, -1, -2, -2]),
        Ok(TuningName::C6) => Ok([-4, 0, -2, 0, 1, 0]),
        Ok(TuningName::Dsus4) => Ok([-2, 0, 0, 0, -2, -2]),
        Ok(TuningName::DropD) => Ok([-2, 0, 0, 0, 0, 0]),
        Ok(TuningName::DropC) => Ok([-4, -2, -2, -2, -2, -2]),
        Ok(TuningName::OpenC) => Ok([-4, -2, -2, 0, 1, 0]),
        Ok(TuningName::DropB) => Ok([-5, -3, -3, -3, -3, -3]),
        Ok(TuningName::OpenE) => Ok([0, -2, -2, -2, 0, 0]),
        Err(_) if tuning_name.eq_ignore_ascii_case("standard") => Ok([0; 6]),
        Err(_) => Err(crate::error::TabError::TuningNameUnknown {
            value: tuning_name.to_owned(),
        }),
    }
}
#[cfg(test)]
mod test_parse_tuning {
    use super::*;
    use crate::error::TabError;

    #[test]
    fn standard_tuning_returns_zero_offsets() {
        assert_eq!(parse_tuning("standard").unwrap(), [0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn standard_is_case_insensitive() {
        assert_eq!(parse_tuning("STANDARD").unwrap(), [0, 0, 0, 0, 0, 0]);
        assert_eq!(parse_tuning("Standard").unwrap(), [0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn empty_string_returns_tuning_name_unknown() {
        let err = parse_tuning("").unwrap_err();
        match err {
            TabError::TuningNameUnknown { value } => assert_eq!(value, ""),
            other => panic!("expected TuningNameUnknown, got {other:?}"),
        }
    }

    #[test]
    fn non_standard_tunings() {
        assert_eq!(parse_tuning("openg").unwrap(), [-2, 0, 0, 0, -2, -2]);
        assert_eq!(parse_tuning("opend").unwrap(), [-2, 0, 0, -1, -2, -2]);
        assert_eq!(parse_tuning("c6").unwrap(), [-4, 0, -2, 0, 1, 0]);
        assert_eq!(parse_tuning("dadgad").unwrap(), [-2, 0, 0, 0, -2, -2]);
        assert_eq!(parse_tuning("dsus4").unwrap(), [-2, 0, 0, 0, -2, -2]);
        assert_eq!(parse_tuning("dropd").unwrap(), [-2, 0, 0, 0, 0, 0]);
        assert_eq!(parse_tuning("dropc").unwrap(), [-4, -2, -2, -2, -2, -2]);
        assert_eq!(parse_tuning("openc").unwrap(), [-4, -2, -2, 0, 1, 0]);
        assert_eq!(parse_tuning("dropb").unwrap(), [-5, -3, -3, -3, -3, -3]);
        assert_eq!(parse_tuning("opene").unwrap(), [0, -2, -2, -2, 0, 0]);
    }

    #[test]
    fn unrecognized_name_returns_tuning_name_unknown() {
        let err = parse_tuning("opan G").unwrap_err();
        match err {
            TabError::TuningNameUnknown { value } => assert_eq!(value, "opan G"),
            other => panic!("expected TuningNameUnknown, got {other:?}"),
        }
    }
}

/// Generates a tuning map of open string pitches from an array of pitch offsets
/// relative to the standard 6-string tuning open pitches.
///
/// # Examples
///
/// `create_string_tuning_offset([0, 0, 0, 0, 0, 0])` creates the standard tuning.
///
/// # Panics
///
/// Panics only if an internal invariant is violated: an offset that pushes a standard
/// open-string pitch out of the `Pitch` range, or a 6-element tuning that fails
/// `create_string_tuning`. Both are BUG conditions given the fixed 6-string std tuning.
#[must_use]
pub fn create_string_tuning_offset(offsets: [i8; 6]) -> BTreeMap<StringNumber, Pitch> {
    let offset_tuning_open_pitches: Vec<Pitch> = STD_6_STRING_TUNING_OPEN_PITCHES
        .iter()
        .zip(offsets)
        .map(|(std_tuning_pitch, offset)| {
            std_tuning_pitch
                .plus_offset(offset as i16)
                .expect("BUG: Tuning pitch offset should be valid")
        })
        .collect();

    create_string_tuning(&offset_tuning_open_pitches)
        .expect("BUG: standard tuning offsets produce valid pitches")
}
#[cfg(test)]
mod test_create_string_tuning_offset {
    use super::*;

    #[test]
    fn no_offset() {
        assert_eq!(
            create_string_tuning_offset([0, 0, 0, 0, 0, 0]),
            create_string_tuning(&STD_6_STRING_TUNING_OPEN_PITCHES).unwrap()
        );
    }
    #[test]
    fn single_offset() {
        assert_eq!(
            create_string_tuning_offset([-2, 0, 0, 0, 0, 0]),
            create_string_tuning(&[
                Pitch::D4,
                Pitch::B3,
                Pitch::G3,
                Pitch::D3,
                Pitch::A2,
                Pitch::E2,
            ])
            .unwrap()
        );
    }
    #[test]
    fn random_offsets() {
        // Test case with random offsets
        assert_eq!(
            create_string_tuning_offset([2, -1, 3, 0, -2, 1]),
            create_string_tuning(&[
                Pitch::FSharpGFlat4,
                Pitch::ASharpBFlat3,
                Pitch::ASharpBFlat3,
                Pitch::D3,
                Pitch::G2,
                Pitch::F2,
            ])
            .unwrap()
        );
    }
}

/// Upper bound on input lines. Ties to `u16::MAX` so the pathfinding graph's
/// `Node::line_index` (`u16`) can address every beat without truncating.
pub(crate) const MAX_INPUT_LINES: usize = u16::MAX as usize;

/// Parses a newline-delimited input string into a sequence of `Line` values.
///
/// Each input line is classified as `Playable` (one or more pitches, e.g. `"A3"` or
/// `"G4Bb2"`), `Rest` (empty or comment-only), or `MeasureBreak` (a line of dash
/// characters: `-`, `–`, or `—`). Call results are cached for the 10 most recent inputs.
///
/// # Errors
///
/// Returns [`crate::error::TabError::Parse`] listing every unparseable substring with its
/// 1-indexed line number, or [`crate::error::TabError::InputTooManyLines`] when the input
/// exceeds `MAX_INPUT_LINES` lines.
#[memoize(Capacity: 10)]
pub fn parse_lines(input: String) -> Result<Vec<Line<BeatVec<Pitch>>>, crate::error::TabError> {
    // Reject pathological input up front so every beat index stays within the u16 range
    // used by the pathfinding graph. `take` short-circuits, so an enormous paste is not
    // fully scanned. A real transcription is far below this bound. The cap is its own
    // variant rather than a Parse error because no single line is at fault.
    if input.lines().take(MAX_INPUT_LINES + 1).count() > MAX_INPUT_LINES {
        return Err(crate::error::TabError::InputTooManyLines {
            max: MAX_INPUT_LINES as u32,
        });
    }

    let pitch_regex = RegexBuilder::new(PITCH_PATTERN)
        .case_insensitive(true)
        .build()
        .expect("BUG: Regex pattern should be valid");

    let (parsed_lines, errors): (
        Vec<Line<BeatVec<Pitch>>>,
        Vec<Vec<crate::error::ParseError>>,
    ) = input
        .lines()
        .enumerate()
        .map(|(input_index, input_line)| parse_line(&pitch_regex, input_index, input_line))
        .partition_map(|result| match result {
            Ok(line) => itertools::Either::Left(line),
            Err(errs) => itertools::Either::Right(errs),
        });

    let flat_errors: Vec<crate::error::ParseError> = errors.into_iter().flatten().collect();
    if !flat_errors.is_empty() {
        return Err(crate::error::TabError::Parse {
            errors: flat_errors,
        });
    }

    Ok(parsed_lines)
}
#[cfg(test)]
mod test_parse_lines {
    use super::*;

    #[test]
    fn parses_mixed_pitches_rests_and_measure_breaks() {
        let input = "A3\nE2// Comment\n\nG4BB2G4\n-\nE4".to_owned();
        let expected = vec![
            Line::Playable(vec![Pitch::A3]),
            Line::Playable(vec![Pitch::E2]),
            Line::Rest,
            Line::Playable(vec![Pitch::G4, Pitch::ASharpBFlat2, Pitch::G4]),
            Line::MeasureBreak,
            Line::Playable(vec![Pitch::E4]),
        ];
        assert_eq!(parse_lines(input).unwrap(), expected);
    }
    #[test]
    fn reports_line_and_content_for_unparseable_input() {
        let input = "A3xyz\nE2\n\nG4BB.2\n-\nE4".to_owned();

        let err = parse_lines(input).unwrap_err();
        assert_eq!(
            err,
            crate::error::TabError::Parse {
                errors: vec![
                    crate::error::ParseError {
                        line: 1,
                        text: "xyz".to_owned()
                    },
                    crate::error::ParseError {
                        line: 4,
                        text: "BB.2".to_owned()
                    },
                ],
            },
        );
    }
    #[test]
    fn rejects_input_beyond_max_lines() {
        // One line past the cap fails fast as InputTooManyLines, instead of letting the beat
        // count overflow the u16 pathfinding index.
        let input = "A2\n".repeat(MAX_INPUT_LINES + 1);

        let err = parse_lines(input).unwrap_err();
        assert_eq!(
            err,
            crate::error::TabError::InputTooManyLines {
                max: MAX_INPUT_LINES as u32,
            }
        );
    }
}

fn parse_line(
    regex: &Regex,
    input_index: usize,
    mut input_line: &str,
) -> Result<Line<Vec<Pitch>>, Vec<crate::error::ParseError>> {
    input_line = remove_comments(input_line);
    let line_content: String = remove_whitespace(input_line);

    if let Some(rest) = parse_rest(&line_content) {
        return Ok(rest);
    }
    if let Some(measure_break) = parse_measure_break(&line_content) {
        return Ok(measure_break);
    }
    parse_pitch(regex, input_index, &line_content)
}
#[cfg(test)]
mod test_parse_line {
    use super::*;

    #[test]
    fn empty() {
        assert_eq!(parse_line(&test_pitch_regex(), 0, "").unwrap(), Line::Rest);
    }
    #[test]
    fn only_comment() {
        assert_eq!(
            parse_line(&test_pitch_regex(), 0, "  // Long comment.... ").unwrap(),
            Line::Rest
        );
    }
    #[test]
    fn measure_break() {
        assert_eq!(
            parse_line(&test_pitch_regex(), 0, "    --    ").unwrap(),
            Line::MeasureBreak
        );
        assert_eq!(
            parse_line(&test_pitch_regex(), 0, "- //comment").unwrap(),
            Line::MeasureBreak
        );
    }
    #[test]
    fn parses_line_with_pitches_whitespace_and_comments() {
        let expected = Line::Playable(vec![Pitch::GSharpAFlat2, Pitch::A4, Pitch::E3, Pitch::G2]);
        assert_eq!(
            parse_line(&test_pitch_regex(), 123, "    G#2A4  E3 G2 ").unwrap(),
            expected
        );
        assert_eq!(
            parse_line(&test_pitch_regex(), 123, "G#2A4E3 G2// Comment").unwrap(),
            expected
        );
    }
    #[test]
    fn reports_error_for_unparseable_text() {
        let errors = parse_line(&test_pitch_regex(), 4, "  Invalid Text  ").unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].line, 5);
        assert_eq!(errors[0].text, "InvalidText");
    }
}

fn remove_comments(input_line: &str) -> &str {
    input_line.split("//").next().unwrap_or(input_line)
}
#[cfg(test)]
mod test_remove_comments {
    use super::*;

    #[test]
    fn no_comment() {
        assert_eq!(remove_comments("Hello, World!"), "Hello, World!");
        assert_eq!(remove_comments("B3C1"), "B3C1");
    }
    #[test]
    fn single_comment() {
        assert_eq!(
            remove_comments("Hello, World! // This is a comment"),
            "Hello, World! "
        );
    }
    #[test]
    fn multiple_comments() {
        assert_eq!(
            remove_comments("Hello, // Comment 1\nWorld! // Comment 2"),
            "Hello, "
        );
    }
    #[test]
    fn comment_at_start() {
        assert_eq!(remove_comments("// Comment at the start"), "");
    }
}

fn remove_whitespace(input: &str) -> String {
    input.chars().filter(|c| !c.is_whitespace()).collect()
}

fn parse_rest(input_line: &str) -> Option<Line<Vec<Pitch>>> {
    if input_line.is_empty() {
        return Some(Line::Rest);
    }
    None
}
#[cfg(test)]
mod test_parse_rest {
    use super::*;

    #[test]
    fn empty_input() {
        assert_eq!(parse_rest(""), Some(Line::Rest));
    }
    #[test]
    fn pitch_input() {
        assert_eq!(parse_rest("G7"), None);
    }
}

fn parse_measure_break(input_line: &str) -> Option<Line<Vec<Pitch>>> {
    let unique_chars: HashSet<char> = input_line.chars().collect();
    if unique_chars == HashSet::<char>::from(['-'])
        || unique_chars == HashSet::<char>::from([''])
        || unique_chars == HashSet::<char>::from([''])
    {
        return Some(Line::MeasureBreak);
    }
    None
}
#[cfg(test)]
mod test_parse_measure_break {
    use super::*;

    #[test]
    fn measure_break_dash() {
        assert_eq!(parse_measure_break("-"), Some(Line::MeasureBreak));
    }
    #[test]
    fn measure_break_en_dash() {
        assert_eq!(parse_measure_break(""), Some(Line::MeasureBreak));
    }
    #[test]
    fn measure_break_em_dash() {
        assert_eq!(parse_measure_break(""), Some(Line::MeasureBreak));
    }
    #[test]
    fn empty_input() {
        assert_eq!(parse_measure_break(""), None);
    }
    #[test]
    fn no_measure_break() {
        assert_eq!(parse_measure_break("ABCDEF"), None);
    }
    #[test]
    fn whitespace_input() {
        assert_eq!(parse_measure_break(" "), None);
    }
    #[test]
    fn multiple_dashes() {
        assert_eq!(parse_measure_break("---"), Some(Line::MeasureBreak));
    }
    #[test]
    fn multiple_en_dashes() {
        assert_eq!(parse_measure_break("–––"), Some(Line::MeasureBreak));
    }
    #[test]
    fn mixed_dashes() {
        assert_eq!(parse_measure_break("-–—"), None);
    }
}

/// Parses input line to extract valid musical pitches, returning structured errors for any
/// substring that cannot be parsed.
fn parse_pitch(
    regex: &Regex,
    input_index: usize,
    input_line: &str,
) -> Result<Line<Vec<Pitch>>, Vec<crate::error::ParseError>> {
    let mut matched_mask = vec![false; input_line.len()];
    let mut matched_pitches: Vec<Pitch> = Vec::new();

    for regex_match in regex.find_iter(input_line) {
        if let Ok(pitch) = Pitch::from_str(regex_match.as_str()) {
            matched_pitches.push(pitch);
            for slot in matched_mask
                .iter_mut()
                .take(regex_match.end())
                .skip(regex_match.start())
            {
                *slot = true;
            }
        }
    }

    let unmatched_indices: Vec<usize> = matched_mask
        .iter()
        .enumerate()
        .filter_map(|(idx, matched)| if *matched { None } else { Some(idx) })
        .collect();

    if !unmatched_indices.is_empty() {
        let line_number = (input_index + 1) as u32;
        let consecutive_indices = consecutive_slices(&unmatched_indices);
        let errors: Vec<crate::error::ParseError> = consecutive_indices
            .into_iter()
            .map(|unmatched_input_indices| {
                let first_idx = *unmatched_input_indices
                    .first()
                    .expect("BUG: consecutive_slices never yields an empty group");
                let last_idx = *unmatched_input_indices
                    .last()
                    .expect("BUG: consecutive_slices never yields an empty group");
                // Collect by char so the unmatched run can never slice across a UTF-8
                // boundary: `matched_mask` is byte-indexed, so `input_line[first..=last]`
                // could panic on a non-boundary index.
                let unmatched_input: String = input_line
                    .char_indices()
                    .filter(|(byte_idx, _)| (first_idx..=last_idx).contains(byte_idx))
                    .map(|(_, ch)| ch)
                    .collect();
                crate::error::ParseError {
                    line: line_number,
                    text: unmatched_input,
                }
            })
            .collect();
        return Err(errors);
    }

    Ok(Line::Playable(matched_pitches))
}
#[cfg(test)]
mod test_parse_pitch {
    use super::*;

    #[test]
    fn single_natural_pitch() {
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "A0").unwrap(),
            Line::Playable(vec![Pitch::A0])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "E6").unwrap(),
            Line::Playable(vec![Pitch::E6])
        );
    }
    #[test]
    fn single_sharp_pitch() {
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "D#2").unwrap(),
            Line::Playable(vec![Pitch::DSharpEFlat2])
        );
    }
    #[test]
    fn single_flat_pitch() {
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "Db2").unwrap(),
            Line::Playable(vec![Pitch::CSharpDFlat2])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "Bb2").unwrap(),
            Line::Playable(vec![Pitch::ASharpBFlat2])
        );
    }
    #[test]
    fn multibyte_unmatched_char_reports_full_char() {
        // A multibyte character that matches no pitch surfaces intact in the error text,
        // never sliced across a UTF-8 boundary.
        let errors = parse_pitch(&test_pitch_regex(), 0, "A2🎸").unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].text, "🎸");
        assert_eq!(errors[0].line, 1);
    }
    #[test]
    fn case_insensitivity() {
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "A3").unwrap(),
            Line::Playable(vec![Pitch::A3])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "a3").unwrap(),
            Line::Playable(vec![Pitch::A3])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "Bb2").unwrap(),
            Line::Playable(vec![Pitch::ASharpBFlat2])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "bB2").unwrap(),
            Line::Playable(vec![Pitch::ASharpBFlat2])
        );
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "bb2").unwrap(),
            Line::Playable(vec![Pitch::ASharpBFlat2])
        );
    }
    #[test]
    fn multiple_pitches() {
        assert_eq!(
            parse_pitch(&test_pitch_regex(), 0, "C3G2A#1F8").unwrap(),
            Line::Playable(vec![Pitch::C3, Pitch::G2, Pitch::ASharpBFlat1, Pitch::F8])
        );
    }
    #[test]
    fn invalid_typo() {
        let errors = parse_pitch(&test_pitch_regex(), 12, "ZA2G#444B3").unwrap_err();
        assert_eq!(errors.len(), 2);
        assert_eq!(errors[0].line, 13);
        assert_eq!(errors[0].text, "Z");
        assert_eq!(errors[1].line, 13);
        assert_eq!(errors[1].text, "44");
    }
    #[test]
    fn invalid_pitch() {
        let errors = parse_pitch(&test_pitch_regex(), 28, "Fb3").unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].line, 29);
        assert_eq!(errors[0].text, "Fb3");
    }
    #[test]
    fn invalid_random() {
        let errors = parse_pitch(&test_pitch_regex(), 0, "baS3Q-hNr").unwrap_err();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].line, 1);
        assert_eq!(errors[0].text, "baS3Q-hNr");
    }
}

/// Splits `numbers` into runs of consecutive values, preserving input order (no sorting).
fn consecutive_slices(numbers: &[usize]) -> Vec<&[usize]> {
    let mut slice_start = 0;
    let mut result = Vec::with_capacity(numbers.len());
    for i in 1..numbers.len() {
        if numbers[i - 1] + 1 != numbers[i] {
            result.push(&numbers[slice_start..i]);
            slice_start = i;
        }
    }
    if !numbers.is_empty() {
        result.push(&numbers[slice_start..]);
    }
    result
}
#[cfg(test)]
mod test_consecutive_slices {
    use super::*;

    #[test]
    fn simple() {
        let flat_nums = vec![1, 2, 3, 4];
        let consecutive_nums = vec![vec![1, 2, 3, 4]];

        assert_eq!(consecutive_slices(&flat_nums), consecutive_nums);
    }
    #[test]
    fn complex() {
        let flat_nums = vec![1, 2, 3, 4, 113, 115, 116, 6, 7, 8];
        let consecutive_nums = vec![vec![1, 2, 3, 4], vec![113], vec![115, 116], vec![6, 7, 8]];

        assert_eq!(consecutive_slices(&flat_nums), consecutive_nums);
    }
    #[test]
    fn no_consecutive() {
        let flat_nums = vec![95, 65, 74, 96, 68, 29, 34, 32];
        let consecutive_nums = vec![
            vec![95],
            vec![65],
            vec![74],
            vec![96],
            vec![68],
            vec![29],
            vec![34],
            vec![32],
        ];

        assert_eq!(consecutive_slices(&flat_nums), consecutive_nums);
    }
}

#[cfg(test)]
mod test_get_tuning_names {
    use super::*;

    #[test]
    fn returns_non_empty_set() {
        assert!(!get_tuning_names().is_empty());
    }
}

#[cfg(test)]
mod test_pitch_pattern {
    use super::*;

    #[test]
    fn accidentals_match_but_literal_pipe_does_not() {
        let re = test_pitch_regex();
        assert!(re.is_match("C#1"));
        assert!(re.is_match("Cb1"));
        assert!(re.is_match("C\u{266f}1")); // C sharp
        assert!(re.is_match("C\u{266d}1")); // C flat
        // A pipe is not an accidental; the character class must not accept it.
        assert!(!re.is_match("C|1"));
    }
}