chordsketch-chordpro 0.5.0

ChordPro parser, AST, and transforms
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
//! Single-pass lexer for ChordPro documents.
//!
//! The lexer consumes a `&str` input and produces a sequence of [`Token`]s.
//! It recognises the structural delimiters of the ChordPro format (`{`, `}`,
//! `[`, `]`, and `:` inside directives) and groups everything else into
//! [`TokenKind::Text`] runs. Newlines are emitted as separate tokens because
//! they are semantically significant in the format.
//!
//! The lexer tracks whether it is currently inside a directive (between `{`
//! and `}`) so that it only emits [`TokenKind::Colon`] in that context. Outside
//! directives, a colon is simply part of a text run.
//!
//! # Escaped Characters
//!
//! A backslash (`\`) before any of the special characters (`{`, `}`, `[`, `]`,
//! `:`) causes the character to be included in the current text run rather than
//! being treated as a delimiter. A backslash before a non-special character is
//! preserved literally (both the backslash and the following character appear
//! in the text).

use crate::token::{Position, Span, Token, TokenKind};

/// A single-pass lexer for ChordPro source text.
///
/// Create a `Lexer` with [`Lexer::new`] and call [`Lexer::tokenize`] to
/// produce the full token stream.
pub struct Lexer {
    /// Pre-collected `(byte_offset, char)` pairs from the input.
    chars: Vec<(usize, char)>,
    /// Current index into `chars`.
    pos: usize,
    /// Current 1-based line number.
    line: usize,
    /// Current 1-based column number.
    column: usize,
    /// Whether the lexer is currently inside a directive (`{` … `}`).
    in_directive: bool,
}

impl Lexer {
    /// Creates a new `Lexer` for the given source text.
    #[must_use]
    pub fn new(input: &str) -> Self {
        Self {
            chars: input.char_indices().collect(),
            pos: 0,
            line: 1,
            column: 1,
            in_directive: false,
        }
    }

    /// Tokenizes the entire input and returns a vector of tokens.
    ///
    /// The returned vector always ends with a [`TokenKind::Eof`] token.
    #[must_use]
    pub fn tokenize(mut self) -> Vec<Token> {
        let mut tokens = Vec::new();

        while !self.is_at_end() {
            if let Some(token) = self.next_token() {
                tokens.push(token);
            }
        }

        // Emit the final EOF token.
        let eof_pos = Position::new(self.line, self.column);
        tokens.push(Token::new(TokenKind::Eof, Span::new(eof_pos, eof_pos)));

        tokens
    }

    /// Returns `true` when all input has been consumed.
    fn is_at_end(&self) -> bool {
        self.pos >= self.chars.len()
    }

    /// Peeks at the current character without advancing.
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).map(|&(_, ch)| ch)
    }

    /// Advances past the current character and updates line/column tracking.
    fn advance(&mut self) -> Option<char> {
        if let Some(&(_, ch)) = self.chars.get(self.pos) {
            self.pos += 1;
            if ch == '\n' {
                self.line += 1;
                self.column = 1;
            } else {
                self.column += 1;
            }
            Some(ch)
        } else {
            None
        }
    }

    /// Produces the next token, or `None` if the input is exhausted.
    fn next_token(&mut self) -> Option<Token> {
        let ch = self.peek()?;

        match ch {
            '\n' => self.lex_newline(),
            '\r' => self.lex_carriage_return(),
            '{' => self.lex_single(TokenKind::DirectiveOpen, true),
            '}' => self.lex_single(TokenKind::DirectiveClose, false),
            '[' => self.lex_single(TokenKind::ChordOpen, false),
            ']' => self.lex_single(TokenKind::ChordClose, false),
            ':' if self.in_directive => self.lex_single(TokenKind::Colon, false),
            _ => self.lex_text(),
        }
    }

    /// Lexes a single-character token. If `enter_directive` is `true`, sets
    /// `in_directive` to `true`; if the token kind is `DirectiveClose`, sets
    /// it to `false`.
    fn lex_single(&mut self, kind: TokenKind, enter_directive: bool) -> Option<Token> {
        let start = Position::new(self.line, self.column);
        self.advance();
        let end = Position::new(self.line, self.column);

        if enter_directive {
            self.in_directive = true;
        }
        if kind == TokenKind::DirectiveClose {
            self.in_directive = false;
        }

        Some(Token::new(kind, Span::new(start, end)))
    }

    /// Lexes a newline token (`\n`).
    fn lex_newline(&mut self) -> Option<Token> {
        let start = Position::new(self.line, self.column);
        self.advance(); // consume '\n'
        let end = Position::new(self.line, self.column);
        Some(Token::new(TokenKind::Newline, Span::new(start, end)))
    }

    /// Lexes a `\r` character. If followed by `\n`, emits a single newline
    /// token covering both characters. Otherwise the `\r` is treated as text.
    fn lex_carriage_return(&mut self) -> Option<Token> {
        let start = Position::new(self.line, self.column);

        // Peek ahead: is this \r\n?
        let is_crlf = self.chars.get(self.pos + 1).map(|&(_, c)| c) == Some('\n');

        if is_crlf {
            // Advance past \r (advance() only bumps line on \n, so \r just bumps column)
            self.advance(); // consumes '\r'
            // Advance past \n (bumps line)
            self.advance(); // consumes '\n'
            let end = Position::new(self.line, self.column);
            Some(Token::new(TokenKind::Newline, Span::new(start, end)))
        } else {
            // Bare \r — treat as text.
            self.lex_text()
        }
    }

    /// Lexes a run of text characters.
    ///
    /// Text continues until a special delimiter, a newline, or end of input is
    /// reached. Backslash-escaped special characters are included in the text
    /// run rather than acting as delimiters.
    fn lex_text(&mut self) -> Option<Token> {
        let start = Position::new(self.line, self.column);
        let mut buf = String::new();

        while let Some(ch) = self.peek() {
            match ch {
                '\n' => break,
                '\r' => {
                    // Check for \r\n
                    let is_crlf = self.chars.get(self.pos + 1).map(|&(_, c)| c) == Some('\n');
                    if is_crlf {
                        break;
                    }
                    // Bare \r — include in text.
                    self.advance();
                    buf.push(ch);
                }
                '\\' => {
                    // Look ahead to see if the next char is a special character.
                    if let Some(&(_, next_ch)) = self.chars.get(self.pos + 1) {
                        if is_special(next_ch, self.in_directive) {
                            // Skip the backslash, include the escaped character.
                            self.advance(); // skip '\'
                            self.advance(); // consume the special char
                            buf.push(next_ch);
                        } else {
                            // Not a special char — keep both backslash and char.
                            self.advance();
                            buf.push(ch);
                        }
                    } else {
                        // Backslash at end of input — include it literally.
                        self.advance();
                        buf.push(ch);
                    }
                }
                '{' | '}' | '[' | ']' => break,
                ':' if self.in_directive => break,
                _ => {
                    self.advance();
                    buf.push(ch);
                }
            }
        }

        if buf.is_empty() {
            return None;
        }

        let end = Position::new(self.line, self.column);
        Some(Token::new(TokenKind::Text(buf), Span::new(start, end)))
    }
}

/// Returns `true` if the character is a special ChordPro delimiter.
///
/// The colon is only special inside directives.
fn is_special(ch: char, in_directive: bool) -> bool {
    matches!(ch, '{' | '}' | '[' | ']') || (ch == ':' && in_directive)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::token::TokenKind::*;

    /// Helper: tokenize the input and return only the token kinds (dropping
    /// spans) for easier assertion.
    fn kinds(input: &str) -> Vec<TokenKind> {
        Lexer::new(input)
            .tokenize()
            .into_iter()
            .map(|t| t.kind)
            .collect()
    }

    // ------------------------------------------------------------------
    // Basic token types
    // ------------------------------------------------------------------

    #[test]
    fn empty_input() {
        let tokens = Lexer::new("").tokenize();
        assert_eq!(tokens.len(), 1);
        assert_eq!(tokens[0].kind, Eof);
    }

    #[test]
    fn single_newline() {
        assert_eq!(kinds("\n"), vec![Newline, Eof]);
    }

    #[test]
    fn crlf_newline() {
        assert_eq!(kinds("\r\n"), vec![Newline, Eof]);
    }

    #[test]
    fn plain_text() {
        assert_eq!(kinds("Hello world"), vec![Text("Hello world".into()), Eof],);
    }

    // ------------------------------------------------------------------
    // Directive syntax
    // ------------------------------------------------------------------

    #[test]
    fn simple_directive() {
        assert_eq!(
            kinds("{title: My Song}"),
            vec![
                DirectiveOpen,
                Text("title".into()),
                Colon,
                Text(" My Song".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn directive_without_value() {
        assert_eq!(
            kinds("{soc}"),
            vec![DirectiveOpen, Text("soc".into()), DirectiveClose, Eof,],
        );
    }

    #[test]
    fn directive_with_spaces_around_colon() {
        assert_eq!(
            kinds("{key : Am}"),
            vec![
                DirectiveOpen,
                Text("key ".into()),
                Colon,
                Text(" Am".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn colon_outside_directive_is_text() {
        assert_eq!(kinds("Note: hello"), vec![Text("Note: hello".into()), Eof],);
    }

    // ------------------------------------------------------------------
    // Chord syntax
    // ------------------------------------------------------------------

    #[test]
    fn chord_in_lyrics() {
        assert_eq!(
            kinds("[Am]Hello [G]world"),
            vec![
                ChordOpen,
                Text("Am".into()),
                ChordClose,
                Text("Hello ".into()),
                ChordOpen,
                Text("G".into()),
                ChordClose,
                Text("world".into()),
                Eof,
            ],
        );
    }

    #[test]
    fn chord_only_line() {
        assert_eq!(
            kinds("[Am]  [G]  [C]"),
            vec![
                ChordOpen,
                Text("Am".into()),
                ChordClose,
                Text("  ".into()),
                ChordOpen,
                Text("G".into()),
                ChordClose,
                Text("  ".into()),
                ChordOpen,
                Text("C".into()),
                ChordClose,
                Eof,
            ],
        );
    }

    // ------------------------------------------------------------------
    // Multiple lines
    // ------------------------------------------------------------------

    #[test]
    fn multiple_lines() {
        assert_eq!(
            kinds("{title: Test}\n[Am]Hello\nWorld"),
            vec![
                DirectiveOpen,
                Text("title".into()),
                Colon,
                Text(" Test".into()),
                DirectiveClose,
                Newline,
                ChordOpen,
                Text("Am".into()),
                ChordClose,
                Text("Hello".into()),
                Newline,
                Text("World".into()),
                Eof,
            ],
        );
    }

    #[test]
    fn empty_lines() {
        assert_eq!(
            kinds("Hello\n\nWorld"),
            vec![
                Text("Hello".into()),
                Newline,
                Newline,
                Text("World".into()),
                Eof,
            ],
        );
    }

    #[test]
    fn text_only_lines() {
        assert_eq!(
            kinds("just text here"),
            vec![Text("just text here".into()), Eof],
        );
    }

    // ------------------------------------------------------------------
    // Escaped characters
    // ------------------------------------------------------------------

    #[test]
    fn escaped_brace_in_text() {
        assert_eq!(
            kinds("hello \\{ world"),
            vec![Text("hello { world".into()), Eof],
        );
    }

    #[test]
    fn escaped_bracket() {
        assert_eq!(
            kinds("\\[not a chord\\]"),
            vec![Text("[not a chord]".into()), Eof],
        );
    }

    #[test]
    fn escaped_colon_inside_directive() {
        assert_eq!(
            kinds("{comment: 10\\:30 AM}"),
            vec![
                DirectiveOpen,
                Text("comment".into()),
                Colon,
                Text(" 10:30 AM".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn backslash_before_normal_char() {
        // Backslash before a non-special char is kept literally.
        assert_eq!(kinds("back\\slash"), vec![Text("back\\slash".into()), Eof],);
    }

    #[test]
    fn backslash_at_end_of_input() {
        assert_eq!(kinds("end\\"), vec![Text("end\\".into()), Eof],);
    }

    // ------------------------------------------------------------------
    // Span / position tracking
    // ------------------------------------------------------------------

    #[test]
    fn spans_for_directive() {
        let tokens = Lexer::new("{t: X}").tokenize();

        // {
        assert_eq!(tokens[0].span.start, Position::new(1, 1));
        assert_eq!(tokens[0].span.end, Position::new(1, 2));

        // t
        assert_eq!(tokens[1].span.start, Position::new(1, 2));
        assert_eq!(tokens[1].span.end, Position::new(1, 3));

        // :
        assert_eq!(tokens[2].span.start, Position::new(1, 3));
        assert_eq!(tokens[2].span.end, Position::new(1, 4));

        // " X"
        assert_eq!(tokens[3].span.start, Position::new(1, 4));
        assert_eq!(tokens[3].span.end, Position::new(1, 6));

        // }
        assert_eq!(tokens[4].span.start, Position::new(1, 6));
        assert_eq!(tokens[4].span.end, Position::new(1, 7));

        // EOF
        assert_eq!(tokens[5].span.start, Position::new(1, 7));
    }

    #[test]
    fn spans_across_lines() {
        let tokens = Lexer::new("AB\nCD").tokenize();

        // "AB"
        assert_eq!(tokens[0].span.start, Position::new(1, 1));
        assert_eq!(tokens[0].span.end, Position::new(1, 3));

        // \n
        assert_eq!(tokens[1].span.start, Position::new(1, 3));
        assert_eq!(tokens[1].span.end, Position::new(2, 1));

        // "CD"
        assert_eq!(tokens[2].span.start, Position::new(2, 1));
        assert_eq!(tokens[2].span.end, Position::new(2, 3));
    }

    #[test]
    fn spans_across_crlf_lines() {
        let tokens = Lexer::new("AB\r\nCD").tokenize();

        // "AB"
        assert_eq!(tokens[0].span.start, Position::new(1, 1));
        assert_eq!(tokens[0].span.end, Position::new(1, 3));

        // \r\n — span mirrors the bare-LF case: the newline token starts at
        // the CR column on line 1 and ends at column 1 of the next line.
        assert_eq!(tokens[1].span.start, Position::new(1, 3));
        assert_eq!(tokens[1].span.end, Position::new(2, 1));

        // "CD"
        assert_eq!(tokens[2].span.start, Position::new(2, 1));
        assert_eq!(tokens[2].span.end, Position::new(2, 3));
    }

    // ------------------------------------------------------------------
    // Edge cases
    // ------------------------------------------------------------------

    #[test]
    fn nested_braces_produce_separate_tokens() {
        // Nested braces are not valid ChordPro, but the lexer should still
        // tokenize them without crashing.
        let toks = kinds("{{inner}}");
        assert_eq!(
            toks,
            vec![
                DirectiveOpen,
                DirectiveOpen,
                Text("inner".into()),
                DirectiveClose,
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn bracket_inside_directive() {
        // A bracket inside a directive is just a bracket token.
        assert_eq!(
            kinds("{comment: [Am] chord}"),
            vec![
                DirectiveOpen,
                Text("comment".into()),
                Colon,
                Text(" ".into()),
                ChordOpen,
                Text("Am".into()),
                ChordClose,
                Text(" chord".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn empty_directive() {
        assert_eq!(kinds("{}"), vec![DirectiveOpen, DirectiveClose, Eof],);
    }

    #[test]
    fn empty_chord() {
        assert_eq!(kinds("[]"), vec![ChordOpen, ChordClose, Eof],);
    }

    #[test]
    fn directive_across_lines_is_not_special() {
        // If a user forgets to close a directive, the lexer keeps
        // `in_directive` true through the newline. This is intentional —
        // the parser will report the error.
        let toks = kinds("{title\nvalue}");
        assert_eq!(
            toks,
            vec![
                DirectiveOpen,
                Text("title".into()),
                Newline,
                Text("value".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn multiple_colons_in_directive() {
        assert_eq!(
            kinds("{meta: key:value}"),
            vec![
                DirectiveOpen,
                Text("meta".into()),
                Colon,
                Text(" key".into()),
                Colon,
                Text("value".into()),
                DirectiveClose,
                Eof,
            ],
        );
    }

    #[test]
    fn unicode_text() {
        assert_eq!(
            kinds("[Am]こんにちは"),
            vec![
                ChordOpen,
                Text("Am".into()),
                ChordClose,
                Text("こんにちは".into()),
                Eof,
            ],
        );
    }

    #[test]
    fn full_song_snippet() {
        let input = "\
{title: Amazing Grace}
{artist: John Newton}

[G]Amazing [G7]grace, how [C]sweet the [G]sound
[G]That saved a [Em]wretch like [D]me";

        let toks = kinds(input);
        assert_eq!(
            toks,
            vec![
                // {title: Amazing Grace}
                DirectiveOpen,
                Text("title".into()),
                Colon,
                Text(" Amazing Grace".into()),
                DirectiveClose,
                Newline,
                // {artist: John Newton}
                DirectiveOpen,
                Text("artist".into()),
                Colon,
                Text(" John Newton".into()),
                DirectiveClose,
                Newline,
                // empty line
                Newline,
                // [G]Amazing [G7]grace, how [C]sweet the [G]sound
                ChordOpen,
                Text("G".into()),
                ChordClose,
                Text("Amazing ".into()),
                ChordOpen,
                Text("G7".into()),
                ChordClose,
                Text("grace, how ".into()),
                ChordOpen,
                Text("C".into()),
                ChordClose,
                Text("sweet the ".into()),
                ChordOpen,
                Text("G".into()),
                ChordClose,
                Text("sound".into()),
                Newline,
                // [G]That saved a [Em]wretch like [D]me
                ChordOpen,
                Text("G".into()),
                ChordClose,
                Text("That saved a ".into()),
                ChordOpen,
                Text("Em".into()),
                ChordClose,
                Text("wretch like ".into()),
                ChordOpen,
                Text("D".into()),
                ChordClose,
                Text("me".into()),
                Eof,
            ],
        );
    }
}