barmark 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,90 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.23.0] - 2026-11-10
13
+
14
+ Grammar changes: an unreadable slot keeps its bar, stacked chord
15
+ spellings read, and an ending may continue onto the lines after it
16
+ (Kevin, 2026-11-10). Implements the
17
+ [grammar v0.1 draft](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md).
18
+
19
+ ### Added
20
+
21
+ - **Stacked chord spellings read, with a warning** (grammar 3, A.5;
22
+ stem-shovel issue 16). Notation programs print alterations run together
23
+ ("D6 add9 omit5"): items run together in one parenthesis
24
+ (`D6(omit5add9)`, `D6(no5add9)`, `C7(b9#11)`) and a bare `omit`/`no`
25
+ trailing the chord's name, after the quality however it is spelled and
26
+ before any parenthesis or slash bass (`Gadd9omit3`, `Gomit5`, `Gno5`,
27
+ `G-7omit5`, `CΔno3`; not `Cno5maj7` or `Cno3add9`) now read as their
28
+ comma-separated form instead of being unreadable. The warning's
29
+ `suggestion` is that form (`D6(omit5,add9)`, `Gadd9(omit3)`,
30
+ `G(omit5)`); the printer writes the canonical form (`D6(9,no5)`), so
31
+ `format` fixes them. Items that are wrong on their own stay errors
32
+ (`C(omit5omit5)`). A chord warning's `suggestion` now reaches the
33
+ chart's diagnostic.
34
+ - **An altered fifth before the parenthesis gets a suggestion**:
35
+ `F#b5(omit3)` is still an error (grammar 3 keeps `Ab5` the A♭ power
36
+ chord), now suggesting `F#(b5,omit3)`. Where the root's accidental could
37
+ be the fifth's, there is no suggestion, and the message says the symbol
38
+ is ambiguous when the fifth reading would itself read (`Gb5(omit3)`,
39
+ as `G(b5,omit3)`; not `Gb5(no7)`).
40
+ - **An ending may continue onto the lines after it** (grammar 5.1, Kevin
41
+ 2026-11-10, stem-shovel issue #16). An ending not closed by `:|` on its
42
+ own line continues through the plain `|` lines after it, up to its `:|`
43
+ or the next ending: `|1 G | A | B | C |` then `| D :|` is a five-bar
44
+ first ending, so a chart keeps four bars a row. The last ending still
45
+ ends at its own line. Each continuation line carries the ending's passes
46
+ as the new optional `continues` on its bar line in the parse tree (A.7),
47
+ and plays on that ending's passes only. Text, credit, lyric-row and
48
+ `---` lines may sit between an ending's lines; a heading, a directive
49
+ line, a `|:` line or a line that can't be read ends it, and a directive
50
+ line that stops an ending continuing is an error naming it. Only the
51
+ endings of a paired repeat continue. A chart that
52
+ read cleanly before reads the same; an ending before the last that runs
53
+ into the next ending with no `:|` now gives one error, "an ending before
54
+ the last goes back with :|", on its first line, where it gave two.
55
+ - **`printedAsWritten(parse)`** and **`unreadSlots(line)`**: the lines the
56
+ printer prints as written (spec §8), and a bar line's unreadable slots,
57
+ so a renderer draws what the printer prints.
58
+
59
+ ### Changed
60
+
61
+ - **An unreadable slot is kept as unknown harmony with its text** (grammar
62
+ principle 4, 2.3, 3). An unknown chord symbol (`CM7`, `CSus4`, `C69`),
63
+ a bad note set (`{H}`), a voicing note not in its chord, a syllable on a
64
+ chord name, a lone `-`, a mark that can't be read (`<<<C`, `+?`) or a
65
+ misplaced or bad dot (`| C. |`, `C._D._E`) is
66
+ still an error with the same message, token and suggestion, so `check`
67
+ still fails; but the slot becomes `{ kind: "unknown", text }` and the
68
+ line keeps its bars, so a chart plays as long as it is written. Only a
69
+ bar line whose structure can't be read (a stray `|:` or `:|`, a bad
70
+ ending or `x N`, an empty group member, `%`, `...`, a direction or a
71
+ mark sharing a cell, an empty cell, a bad `[n/d]`, an unclosed quote)
72
+ is still excluded.
73
+ Before, any error dropped the whole line.
74
+ - **`SimpleSlot`'s `unknown` has an optional `text`** (A.7): the slot as
75
+ written, absent for a written `?`. `printSlot` and `printLine` print it
76
+ as written, a dotted member's dot back in its place.
77
+ - **`format` prints a bar line whose only errors are unreadable slots in
78
+ canonical form** (spec §8), each slot's text as written. A line
79
+ excluded for its structure, or with any other error, still prints as
80
+ written.
81
+ - **`transposeChart` moves the readable chords on a line with an
82
+ unreadable slot** (Kevin, 2026-11-10): `key: C`, `| C | CM7 | G |` to D
83
+ is `| D | CM7 | A |`, with the warning "CM7 can't move: it can't be
84
+ read, so it stays as written" on the slot. A line excluded for its
85
+ structure still stays as written, with "not transposed: this line has
86
+ an error".
87
+ - A part's notes line (7.6) with an unreadable note set has that error
88
+ alone, not a second one for harmony on the line.
89
+
90
+ ### Fixed
91
+
92
+ - A chord symbol with many `add` tones in its parenthesis read in time
93
+ quadratic in its length (20,000 items took seconds); reading a chord
94
+ symbol is now linear.
95
+
12
96
  ## [0.22.0] - 2026-11-09
13
97
 
14
98
  A grammar change: a chart's pickup is bar 0 (2.4), which now defines a
@@ -760,7 +844,8 @@ The first working release: the reference parser and printer for the
760
844
 
761
845
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
762
846
 
763
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.22.0...HEAD
847
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.23.0...HEAD
848
+ [0.23.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.22.0...barmark-v0.23.0
764
849
  [0.22.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.21.0...barmark-v0.22.0
765
850
  [0.21.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.20.0...barmark-v0.21.0
766
851
  [0.20.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.1...barmark-v0.20.0
@@ -1,7 +1,9 @@
1
- import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot, Words } from "./types.js";
1
+ import type { Cell, ChartDiagnostic, Line, Meter, Repeat, SimpleSlot, Slot, Words } from "./types.js";
2
2
  type BarsLine = Extract<Line, {
3
3
  kind: "bars";
4
4
  }>;
5
+ /** Each simple slot of these cells, a group's members each. */
6
+ export declare const simpleSlots: (cells: Cell[]) => SimpleSlot[];
5
7
  /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
6
8
  export declare const isBar: (c: Cell) => c is {
7
9
  kind: "slots";
@@ -28,8 +30,10 @@ export declare function repeatTail(text: string, boundary: boolean): {
28
30
  export declare function misplacedRepeat(token: string): string | null;
29
31
  /**
30
32
  * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
31
- * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
32
- * `written` still says how many bars it writes.
33
+ * marks and an `x N` tail. An error in its structure drops the whole line
34
+ * (`bars` is null); `written` still says how many bars it writes. A slot
35
+ * that can't be read is an error too, but keeps its place as unknown
36
+ * harmony with its text (grammar principle 4).
33
37
  */
34
38
  export declare function parseBarLine(text: string, line: number): {
35
39
  bars: BarsLine | null;
@@ -5,6 +5,8 @@ import { isDirectionWord, readDirection } from "./direction.js";
5
5
  import { parseMeter } from "./directives.js";
6
6
  import { readSyllable, splitSyllable } from "./syllable.js";
7
7
  const FERMATA = new Set(["...", "…"]);
8
+ /** Each simple slot of these cells, a group's members each. */
9
+ export const simpleSlots = (cells) => cells.flatMap((c) => c.kind === "slots" ? c.slots.flatMap((s) => (s.kind === "group" ? s.members : [s])) : []);
8
10
  /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
9
11
  export const isBar = (c) => c.kind === "slots" || c.kind === "simile";
10
12
  const QUOTES = new Set(['"', "“", "”", "„"]);
@@ -435,72 +437,30 @@ function rehearsalCell(bare, meter, words) {
435
437
  suggestion: `| ${mark} | ${others} |`,
436
438
  };
437
439
  }
440
+ /** An unreadable slot (grammar principle 4): unknown harmony keeping what the author wrote. */
441
+ const unreadable = (text, dotted) => ({
442
+ kind: "unknown",
443
+ text,
444
+ ...(dotted ? { dotted: true } : {}),
445
+ });
446
+ /** A sung member's text without its rhythm's dot: `{H}.:la` is `{H}:la`. */
447
+ const undotted = ({ note, syllable }) => `${note.slice(0, -1)}${syllable === null ? "" : `:${syllable}`}`;
438
448
  /**
439
- * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
440
- * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
441
- * `written` still says how many bars it writes.
449
+ * The reader of one slot token: a simple slot or a `_` group of them. A
450
+ * slot it can't read is an error and becomes unknown harmony with its
451
+ * text (`unread`), a misplaced or bad dot included; a misplaced `%`,
452
+ * `...`, direction or `x N`, or an empty member is an error in the bar
453
+ * line's structure (`error`).
442
454
  */
443
- export function parseBarLine(text, line) {
444
- const diagnostics = [];
445
- let listed = 0;
446
- const add = (d) => {
447
- listed++;
448
- if (listed <= MAX_LINE_DIAGNOSTICS)
449
- diagnostics.push(d);
450
- else if (listed === MAX_LINE_DIAGNOSTICS + 1)
451
- diagnostics.push({
452
- line,
453
- severity: "error",
454
- message: "further problems on this line are not listed",
455
- token: "",
456
- });
457
- };
458
- const error = (message, token, suggestion) => {
459
- add({ line, severity: "error", message, token, ...(suggestion ? { suggestion } : {}) });
460
- return null;
461
- };
462
- const warn = (message, token) => add({ line, severity: "warning", message, token });
463
- let body = text.trim();
464
- let repeat = null;
465
- const lastPipe = body.lastIndexOf("|");
466
- const tail = repeatTail(body.slice(lastPipe + 1), true);
467
- if (tail) {
468
- body = body.slice(0, lastPipe + 1) + tail.rest;
469
- repeat = readRepeat(tail.count, line, diagnostics);
470
- }
471
- const leading = readEnding(body);
472
- body = leading.body;
473
- const ending = leading.ending;
474
- if (leading.bad)
475
- error(ENDING_FORM, leading.bad);
476
- const opens = body.startsWith("|:");
477
- if (opens)
478
- body = `|${body.slice(2)}`;
479
- const closes = body.endsWith(":|");
480
- if (closes)
481
- body = `${body.slice(0, -2)}|`;
482
- const written = barsWritten(body);
483
- const stray = strayEnding(body);
484
- if (stray)
485
- error(...stray);
486
- if (body.includes(":|") || body.includes("|:"))
487
- error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
488
- // A misplaced mark makes the cells unreadable: report it once, not again as chords.
489
- if (diagnostics.some((d) => d.severity === "error"))
490
- return { bars: null, written, diagnostics };
491
- const parts = body.split("|").slice(1);
492
- if (parts.at(-1)?.trim() === "")
493
- parts.pop();
494
- else
495
- warn("missing trailing |", parts.at(-1)?.trim() ?? "");
496
- const report = (p) => error(p.problem, p.token, p.suggestion);
455
+ function slotReader({ error, unread, warn, broken }) {
456
+ const report = (p) => unread(p.problem, p.token, p.suggestion);
497
457
  const simple = (token) => {
498
458
  if (token === "/")
499
459
  return { kind: "hold" };
500
460
  if (SILENCE.has(token))
501
461
  return { kind: "silence" };
502
462
  if (token === "-")
503
- return error("a lone - is not a slot; silence is --", token, "--");
463
+ return unread("a lone - is not a slot; silence is --", token, "--");
504
464
  if (token === "?") {
505
465
  warn("unknown harmony", token);
506
466
  return { kind: "unknown" };
@@ -524,14 +484,14 @@ export function parseBarLine(text, line) {
524
484
  return report(v);
525
485
  for (const r of v.warnings)
526
486
  for (const w of r.ok ? r.warnings : [])
527
- warn(w.message, w.token);
487
+ warn(w.message, w.token, w.suggestion);
528
488
  return { kind: "chord", chord: v.chord, voicing: v.voicing };
529
489
  }
530
490
  const r = brace === 0 ? parseNoteSet(token) : parseChord(token);
531
491
  if (!r.ok)
532
- return error(r.error.message, token, r.error.suggestion);
492
+ return unread(r.error.message, token, r.error.suggestion);
533
493
  for (const w of r.warnings)
534
- warn(w.message, w.token);
494
+ warn(w.message, w.token, w.suggestion);
535
495
  return { kind: "chord", chord: r.value };
536
496
  };
537
497
  /** A slot with its push and articulation, if written. */
@@ -563,35 +523,110 @@ export function parseBarLine(text, line) {
563
523
  const withSyllable = ({ note, syllable }, read) => {
564
524
  const written = `${note}:${syllable}`;
565
525
  if (syllable !== null && !note)
566
- return error(NOT_A_NOTE_SET, written);
526
+ return unread(NOT_A_NOTE_SET, written);
567
527
  const slot = read(note);
568
528
  if (syllable === null || !slot)
569
529
  return slot;
570
530
  const sung = sungOn(slot, syllable);
571
- return "problem" in sung ? error(sung.problem, written) : sung;
531
+ return "problem" in sung ? unread(sung.problem, written) : sung;
572
532
  };
573
- /** One slot token: a simple slot, or a `_` group of them. */
574
- const slotOf = (token) => {
575
- const members = groupMembers(token).map(splitSyllable);
576
- const dots = members.filter((m) => isDotted(m.note)).length;
577
- if (dots && (members.length !== 2 || dots > 1))
578
- return error(DOT_PLACE, token);
579
- const [only] = members;
580
- if (only && members.length === 1)
581
- return withSyllable(only, (n) => markedSlot(n, false));
582
- return groupOf(members, token);
533
+ /** A member as read, or as written when it can't be; null once the structure has broken. */
534
+ const keep = (split, read, written) => {
535
+ const slot = withSyllable(split, read);
536
+ if (slot || broken())
537
+ return slot;
538
+ return isDotted(split.note) ? unreadable(undotted(split), true) : unreadable(written, false);
583
539
  };
584
540
  const groupOf = (members, token) => {
585
541
  const out = [];
586
542
  for (const m of members) {
587
543
  const s = m.note || m.syllable !== null
588
- ? withSyllable(m, memberOf)
544
+ ? keep(m, memberOf, m.syllable === null ? m.note : `${m.note}:${m.syllable}`)
589
545
  : error("an empty member in a group", token);
590
546
  if (s)
591
547
  out.push(s);
592
548
  }
593
549
  return { kind: "group", members: out };
594
550
  };
551
+ return (token) => {
552
+ const members = groupMembers(token).map(splitSyllable);
553
+ const dots = members.filter((m) => isDotted(m.note)).length;
554
+ // A dot never changes the bar count: a misplaced one is the slot's error (Kevin, 2026-11-10).
555
+ if (dots && (members.length !== 2 || dots > 1))
556
+ return unread(DOT_PLACE, token) ?? unreadable(token, false);
557
+ const [only] = members;
558
+ if (only && members.length === 1)
559
+ return keep(only, (n) => markedSlot(n, false), token);
560
+ return groupOf(members, token);
561
+ };
562
+ }
563
+ /**
564
+ * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
565
+ * marks and an `x N` tail. An error in its structure drops the whole line
566
+ * (`bars` is null); `written` still says how many bars it writes. A slot
567
+ * that can't be read is an error too, but keeps its place as unknown
568
+ * harmony with its text (grammar principle 4).
569
+ */
570
+ export function parseBarLine(text, line) {
571
+ const diagnostics = [];
572
+ let listed = 0;
573
+ let broken = false;
574
+ const add = (d) => {
575
+ listed++;
576
+ if (listed <= MAX_LINE_DIAGNOSTICS)
577
+ diagnostics.push(d);
578
+ else if (listed === MAX_LINE_DIAGNOSTICS + 1)
579
+ diagnostics.push({
580
+ line,
581
+ severity: "error",
582
+ message: "further problems on this line are not listed",
583
+ token: "",
584
+ });
585
+ };
586
+ const unread = (message, token, suggestion) => {
587
+ add({ line, severity: "error", message, token, ...(suggestion ? { suggestion } : {}) });
588
+ return null;
589
+ };
590
+ const error = (message, token, suggestion) => {
591
+ broken = true;
592
+ return unread(message, token, suggestion);
593
+ };
594
+ const warn = (message, token, suggestion) => add({ line, severity: "warning", message, token, ...(suggestion ? { suggestion } : {}) });
595
+ let body = text.trim();
596
+ let repeat = null;
597
+ const lastPipe = body.lastIndexOf("|");
598
+ const tail = repeatTail(body.slice(lastPipe + 1), true);
599
+ if (tail) {
600
+ body = body.slice(0, lastPipe + 1) + tail.rest;
601
+ repeat = readRepeat(tail.count, line, diagnostics);
602
+ }
603
+ const leading = readEnding(body);
604
+ body = leading.body;
605
+ const ending = leading.ending;
606
+ if (leading.bad)
607
+ error(ENDING_FORM, leading.bad);
608
+ const opens = body.startsWith("|:");
609
+ if (opens)
610
+ body = `|${body.slice(2)}`;
611
+ const closes = body.endsWith(":|");
612
+ if (closes)
613
+ body = `${body.slice(0, -2)}|`;
614
+ const written = barsWritten(body);
615
+ const stray = strayEnding(body);
616
+ if (stray)
617
+ error(...stray);
618
+ if (body.includes(":|") || body.includes("|:"))
619
+ error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
620
+ // A misplaced mark makes the cells unreadable: report it once, not again as chords.
621
+ if (diagnostics.some((d) => d.severity === "error"))
622
+ return { bars: null, written, diagnostics };
623
+ const parts = body.split("|").slice(1);
624
+ if (parts.at(-1)?.trim() === "")
625
+ parts.pop();
626
+ else
627
+ warn("missing trailing |", parts.at(-1)?.trim() ?? "");
628
+ const report = (p) => error(p.problem, p.token, p.suggestion);
629
+ const slotOf = slotReader({ error, unread, warn, broken: () => broken });
595
630
  const readCell = (raw) => {
596
631
  const rest = raw.trim();
597
632
  if (!rest)
@@ -620,9 +655,8 @@ export function parseBarLine(text, line) {
620
655
  if (parts.length === 0)
621
656
  error("a bar line needs at least one cell", text.trim());
622
657
  const cells = parts.map(readCell).filter((c) => c !== null);
623
- const failed = diagnostics.some((d) => d.severity === "error");
624
658
  return {
625
- bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
659
+ bars: broken ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
626
660
  written,
627
661
  diagnostics,
628
662
  };
@@ -2,6 +2,7 @@ import { parseChord } from "../chords/parse.js";
2
2
  import { misplacedRepeat, parseBarLine, readRepeat, repeatTail } from "./barLine.js";
3
3
  import { creditsOf, nearCredit, readCredit } from "./credits.js";
4
4
  import { parseDirectiveLine } from "./directives.js";
5
+ import { continueEndings } from "./endingLines.js";
5
6
  import { checkLines } from "./lines.js";
6
7
  import { attachLyrics, readLyricRow } from "./lyricRows.js";
7
8
  import { readPart } from "./partLine.js";
@@ -363,14 +364,15 @@ export function readDocument(text) {
363
364
  const read = checkParts(lines, diagnostics);
364
365
  const grouped = groupParts(lines, read);
365
366
  const lyrics = attachLyrics(grouped.lines);
366
- diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics);
367
+ const ended = continueEndings(lyrics.lines);
368
+ diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics, ...ended.diagnostics);
367
369
  const { parts } = grouped;
368
370
  return {
369
371
  title,
370
372
  part: parts.length === 1 ? (parts[0] ?? null) : null,
371
373
  parts,
372
374
  credits: creditsOf(lines),
373
- lines: lyrics.lines,
375
+ lines: ended.lines,
374
376
  diagnostics,
375
377
  };
376
378
  }
@@ -0,0 +1,13 @@
1
+ import type { ChartDiagnostic, Line } from "./types.js";
2
+ /** Lines that may sit between endings, and between an ending's lines (grammar 5.1): they mean nothing to the timeline. */
3
+ export declare const BETWEEN_ENDINGS: Set<"bars" | "break" | "credit" | "directive" | "invalid" | "lyrics" | "part" | "section" | "text" | "title">;
4
+ /**
5
+ * Mark the plain bar lines that continue an ending onto further lines
6
+ * (grammar 5.1, Kevin's decision 2026-11-10): each gets the ending's
7
+ * passes as `continues`. Only an ending of a paired repeat continues, so
8
+ * an ending with no `|:` before it leaves a stray `:|` stray. Never throws.
9
+ */
10
+ export declare function continueEndings(lines: Line[]): {
11
+ lines: Line[];
12
+ diagnostics: ChartDiagnostic[];
13
+ };
@@ -0,0 +1,136 @@
1
+ /** Lines that may sit between endings, and between an ending's lines (grammar 5.1): they mean nothing to the timeline. */
2
+ export const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
3
+ const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
4
+ const systemOf = (l) => (l.kind === "bars" || l.kind === "invalid" ? l.system : undefined);
5
+ /** The chart's lines as units: each system's lines read as one, by its first line that reads and agrees. */
6
+ function unitsOf(lines) {
7
+ const units = [];
8
+ for (const l of lines) {
9
+ const last = units.at(-1);
10
+ const first = last?.lines[0];
11
+ if (last && first && inSystem(l) && systemOf(first) === systemOf(l))
12
+ last.lines.push(l);
13
+ else
14
+ units.push({ lines: [l], ref: l });
15
+ }
16
+ for (const u of units)
17
+ u.ref = u.lines.find((l) => l.kind === "bars" && !l.dropped) ?? u.lines[0];
18
+ return units;
19
+ }
20
+ const bars = (l) => (l.kind === "bars" ? l : null);
21
+ /** A bar line with no repeat start and no ending: one an ending can continue onto. */
22
+ const plain = (l) => l.kind === "bars" && !l.opens && !l.ending;
23
+ const startsEnding = (l) => l?.kind === "bars" && l.ending !== null;
24
+ /** The same lines, and directive lines too: what an ending would continue past if directives could sit in it. */
25
+ const PAST_DIRECTIVES = new Set([...BETWEEN_ENDINGS, "directive"]);
26
+ /** The first unit from `from` whose kind isn't one of `past`; reads only up to it. */
27
+ function nextHeard(units, from, past) {
28
+ let k = from;
29
+ while (k < units.length && past.has(units[k].ref.kind))
30
+ k++;
31
+ return units[k]?.ref;
32
+ }
33
+ /**
34
+ * The units an unclosed ending at `at` continues onto: the plain bar lines
35
+ * after it, up to its `:|` or the next ending, when another ending follows
36
+ * (grammar 5.1). The last ending has none, so it ends at its own line.
37
+ * `past` are the lines that may sit among them.
38
+ */
39
+ function continuation(units, at, past = BETWEEN_ENDINGS) {
40
+ const run = [];
41
+ for (let k = at + 1; k < units.length; k++) {
42
+ const ref = units[k].ref;
43
+ if (past.has(ref.kind))
44
+ continue;
45
+ if (startsEnding(ref))
46
+ return run;
47
+ if (!plain(ref))
48
+ return [];
49
+ run.push(k);
50
+ if (bars(ref)?.closes)
51
+ return startsEnding(nextHeard(units, k + 1, past)) ? run : [];
52
+ }
53
+ return [];
54
+ }
55
+ /** A directive line's own name, as its token: `time:`, `tempo:`. */
56
+ function directiveName(set) {
57
+ const first = Object.keys(set)[0] ?? "key";
58
+ const name = { tempoChange: "tempo", swingPercent: "feel" }[first] ?? first;
59
+ return `${name}:`;
60
+ }
61
+ /**
62
+ * The directive line that stopped an ending continuing, when without it
63
+ * the ending would have continued: named, beside the errors that follow
64
+ * (grammar 5.1). Null when nothing would have continued anyway.
65
+ */
66
+ function directiveInside(units, at, head) {
67
+ if (continuation(units, at).length || !continuation(units, at, PAST_DIRECTIVES).length)
68
+ return null;
69
+ for (let k = at + 1; k < units.length; k++) {
70
+ const ref = units[k].ref;
71
+ if (startsEnding(ref))
72
+ break;
73
+ if (ref.kind === "directive")
74
+ return {
75
+ line: ref.line,
76
+ severity: "error",
77
+ message: `a directive line ends the ending |${head.ending?.join(",")} above it; an ending's lines can't hold one`,
78
+ token: directiveName(ref.set),
79
+ };
80
+ }
81
+ return null;
82
+ }
83
+ /** Whether a `|:` is waiting for its `:|` after `l`: a heading or a `:|` ends it, a `|:` opens one. */
84
+ function stillOpen(open, l) {
85
+ if (l.kind === "section")
86
+ return false;
87
+ if (l.kind !== "bars")
88
+ return open;
89
+ return !l.closes && (open || l.opens);
90
+ }
91
+ /** Whether `l` is an ending of a paired repeat, moving the pairing past it. */
92
+ function paired(p, l) {
93
+ if (l.kind === "bars" && l.ending) {
94
+ p.endings = p.open || p.endings;
95
+ p.open = false;
96
+ return p.endings;
97
+ }
98
+ if (!(p.endings && BETWEEN_ENDINGS.has(l.kind))) {
99
+ p.endings = false;
100
+ p.open = stillOpen(p.open, l);
101
+ }
102
+ return false;
103
+ }
104
+ /**
105
+ * Mark the plain bar lines that continue an ending onto further lines
106
+ * (grammar 5.1, Kevin's decision 2026-11-10): each gets the ending's
107
+ * passes as `continues`. Only an ending of a paired repeat continues, so
108
+ * an ending with no `|:` before it leaves a stray `:|` stray. Never throws.
109
+ */
110
+ export function continueEndings(lines) {
111
+ const units = unitsOf(lines);
112
+ const marked = new Map();
113
+ const diagnostics = [];
114
+ const pairing = { open: false, endings: false };
115
+ for (let i = 0; i < units.length; i++) {
116
+ const ref = units[i].ref;
117
+ if (!paired(pairing, ref) || ref.kind !== "bars" || !ref.ending || ref.closes)
118
+ continue;
119
+ const run = continuation(units, i);
120
+ for (const k of run)
121
+ for (const l of units[k].lines)
122
+ marked.set(l, ref.ending);
123
+ const inside = directiveInside(units, i, ref);
124
+ if (inside)
125
+ diagnostics.push(inside);
126
+ // The lines it continues onto belong to the ending: the pairing goes on after them.
127
+ i = run.at(-1) ?? i;
128
+ }
129
+ if (!marked.size)
130
+ return { lines, diagnostics };
131
+ const out = lines.map((l) => {
132
+ const passes = marked.get(l);
133
+ return passes && l.kind === "bars" ? { ...l, continues: passes } : l;
134
+ });
135
+ return { lines: out, diagnostics };
136
+ }
@@ -32,12 +32,6 @@ export declare const MAX_EXPANDED_BARS = 10000;
32
32
  export declare const workFor: (share: number) => number;
33
33
  /** Every played bar in order, with an open repeat's pass included once. */
34
34
  export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
35
- /**
36
- * Turn the written chart into the bars in play order: sections and their
37
- * replays, repeats, directive changes, `%` and elision. Its bars count
38
- * `written` from 1, a pickup included; `parseChart` and `extractPart`
39
- * renumber a pickup to 0 (grammar 2.4).
40
- */
41
35
  /**
42
36
  * `label` names the part a projected chart is (grammar 7.4), for its
43
37
  * messages; `share` is how many parts split the expansion budget.
@@ -115,6 +115,8 @@ function removeLastBar(events) {
115
115
  * `written` from 1, a pickup included; `parseChart` and `extractPart`
116
116
  * renumber a pickup to 0 (grammar 2.4).
117
117
  */
118
+ /** The lines of a repeat's ending for `pass` (grammar 5.1), or none. */
119
+ const endingOn = (it, pass) => it.endings.find((x) => x.passes.includes(pass))?.entries ?? [];
118
120
  /**
119
121
  * `label` names the part a projected chart is (grammar 7.4), for its
120
122
  * messages; `share` is how many parts split the expansion budget.
@@ -505,9 +507,8 @@ sing) {
505
507
  where.pass = phase === "main" ? pass : 1;
506
508
  for (const e of it.entries)
507
509
  playLine(e, out);
508
- const ending = it.endings.find((x) => x.passes.includes(pass));
509
- if (ending)
510
- playLine(ending.entry, out);
510
+ for (const e of endingOn(it, pass))
511
+ playLine(e, out);
511
512
  }
512
513
  Object.assign(where, { pass: outer.pass, passes: outer.passes });
513
514
  };
@@ -12,7 +12,7 @@ export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
14
  export { opensWithPickup } from "./pickup.js";
15
- export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
16
16
  export { memberShares } from "./shares.js";
17
17
  export { streamKey } from "./systems.js";
18
18
  export { type TransposeBy, transposeChart } from "./transpose.js";
@@ -12,7 +12,7 @@ export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
14
  export { opensWithPickup } from "./pickup.js";
15
- export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
16
16
  export { memberShares } from "./shares.js";
17
17
  export { streamKey } from "./systems.js";
18
18
  export { transposeChart } from "./transpose.js";
@@ -7,7 +7,8 @@ const slotsOf = (l) => l.cells.flatMap((c) => (c.kind === "slots" ? c.slots.flat
7
7
  function notesOnlyProblem(l) {
8
8
  const slots = slotsOf(l);
9
9
  const harmony = slots.some((s) => s.kind === "nc" ||
10
- s.kind === "unknown" ||
10
+ // An unreadable slot is already an error of its own, not harmony written here.
11
+ (s.kind === "unknown" && s.text === undefined) ||
11
12
  (s.kind === "chord" && (s.chord.kind !== "notes" || s.voicing !== undefined)));
12
13
  if (harmony)
13
14
  return "chord symbols go on the part's first line; write a note set here, or a voicing on the first line";
@@ -1,4 +1,4 @@
1
- import type { Cell, ChartParse, Line, Slot } from "./types.js";
1
+ import type { Cell, ChartParse, Line, SimpleSlot, Slot } from "./types.js";
2
2
  /**
3
3
  * The fewest slots with the same timeline: `G / D /` is `G D`, `-- --` is `--`.
4
4
  * Only a slot with no attack of its own merges (`/`, a repeated `--` or
@@ -30,6 +30,16 @@ export declare function printChart(text: string): string;
30
30
  * text isn't read twice. `edit`, if given, changes each line before it prints.
31
31
  */
32
32
  export declare function printParsed(text: string, parsed: ChartParse, edit?: (l: Line) => Line): string;
33
+ /** The unreadable slots of a bar line, or of any cells (grammar 2.3): unknown harmony that keeps its text. */
34
+ export declare const unreadSlots: (l: {
35
+ cells: Cell[];
36
+ }) => SimpleSlot[];
37
+ /**
38
+ * The lines that print as written (spec §8): every line with an error,
39
+ * except a bar line whose only errors are its unreadable slots, one each,
40
+ * which prints in canonical form with each slot's text as written.
41
+ */
42
+ export declare function printedAsWritten(parsed: ChartParse): Set<number>;
33
43
  /**
34
44
  * One part of a chart in canonical form, as a single-part chart (grammar
35
45
  * 7.4): its `part:` line, the tutti lines, its own lines, and `N.C.` bars
@@ -1,9 +1,10 @@
1
- import { isBar } from "./barLine.js";
1
+ import { isBar, simpleSlots } from "./barLine.js";
2
2
  import { printDirection } from "./direction.js";
3
3
  import { beatsOf } from "./directives.js";
4
4
  import { readDocument } from "./document.js";
5
5
  import { printKey } from "./keys.js";
6
6
  import { extractPart, parseChart } from "./parse.js";
7
+ import { splitSyllable } from "./syllable.js";
7
8
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
8
9
  function continues(sounding, s) {
9
10
  if (s.kind === "hold")
@@ -62,7 +63,16 @@ const printLyricSlot = (s) => {
62
63
  return printSyllable(s.syllable);
63
64
  return s.kind === "hold" ? "/" : "--";
64
65
  };
66
+ /** An unreadable slot as written: a dotted member's dot goes back before its syllable. */
67
+ function printUnread(text, dotted) {
68
+ if (!dotted)
69
+ return text;
70
+ const { note, syllable } = splitSyllable(text);
71
+ return `${note}.${syllable === null ? "" : `:${syllable}`}`;
72
+ }
65
73
  function printSimple(s) {
74
+ if (s.kind === "unknown" && s.text !== undefined)
75
+ return printUnread(s.text, Boolean(s.dotted));
66
76
  const body = s.kind === "chord" ? s.chord.canonical + (s.voicing?.canonical ?? "") : SYMBOLS[s.kind];
67
77
  const sung = s.kind === "chord" && s.syllable ? `:${printSyllable(s.syllable)}` : "";
68
78
  return printMarks(s) + body + (s.dotted ? "." : "") + sung;
@@ -386,8 +396,25 @@ function beatsOfLines(parsed) {
386
396
  export function printParsed(text, parsed, edit = (l) => l) {
387
397
  return printLines(text, parsed, edit, new Set());
388
398
  }
399
+ /** The unreadable slots of a bar line, or of any cells (grammar 2.3): unknown harmony that keeps its text. */
400
+ export const unreadSlots = (l) => simpleSlots(l.cells).filter((s) => s.kind === "unknown" && s.text !== undefined);
401
+ /**
402
+ * The lines that print as written (spec §8): every line with an error,
403
+ * except a bar line whose only errors are its unreadable slots, one each,
404
+ * which prints in canonical form with each slot's text as written.
405
+ */
406
+ export function printedAsWritten(parsed) {
407
+ const errors = new Map();
408
+ for (const d of parsed.diagnostics)
409
+ if (d.severity === "error")
410
+ errors.set(d.line, (errors.get(d.line) ?? 0) + 1);
411
+ for (const l of parsed.lines)
412
+ if (l.kind === "bars" && errors.get(l.line) === unreadSlots(l).length)
413
+ errors.delete(l.line);
414
+ return new Set(errors.keys());
415
+ }
389
416
  function linePrinter(parsed, edit) {
390
- const errored = new Set(parsed.diagnostics.filter((d) => d.severity === "error").map((d) => d.line));
417
+ const errored = printedAsWritten(parsed);
391
418
  const beatsFor = beatsOfLines(parsed);
392
419
  const systems = systemTexts(parsed, errored, beatsFor, edit);
393
420
  return (raw, l) => {
@@ -4,10 +4,10 @@ export type Entry = {
4
4
  line: Line;
5
5
  repeat: Repeat;
6
6
  };
7
- /** One ending: the passes it plays on and its bar line. */
7
+ /** One ending: the passes it plays on and its bar lines (grammar 5.1). */
8
8
  export type Ending = {
9
9
  passes: number[];
10
- entry: Entry;
10
+ entries: Entry[];
11
11
  };
12
12
  /** A line, or a `|: … :|` repeat; one with endings plays `repeat` passes, each taking its ending. */
13
13
  export type Item = ({
@@ -1,3 +1,4 @@
1
+ import { BETWEEN_ENDINGS } from "./endingLines.js";
1
2
  const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
2
3
  const asLine = (line) => ({ kind: "line", line, repeat: null });
3
4
  const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
@@ -16,40 +17,44 @@ function passProblems(endings, last) {
16
17
  problems.push([last, `the last ending must be the one for pass ${highest}`]);
17
18
  return problems;
18
19
  }
19
- /** Every ending but the last goes back with `:|`; the last plays on. */
20
+ /** Every ending but the last goes back with `:|` on its last line; the last plays on. */
20
21
  function closeProblems(endings, last) {
21
- return endings.flatMap((b) => {
22
+ return endings.flatMap(({ head: b, lines }) => {
23
+ const closes = lines.at(-1)?.closes ?? false;
22
24
  if (b === last)
23
- return b.closes ? [[b, "the last ending plays on, so it doesn't close with :|"]] : [];
24
- return b.closes ? [] : [[b, "an ending before the last goes back with :|"]];
25
+ return closes ? [[b, "the last ending plays on, so it doesn't close with :|"]] : [];
26
+ return closes ? [] : [[b, "an ending before the last goes back with :|"]];
25
27
  });
26
28
  }
27
29
  /** A repeat with its endings, or, if they have problems, each line played once. */
28
30
  function closeEndings(e, error) {
29
- const last = e.endings.at(-1);
31
+ const heads = e.endings.map((x) => x.head);
32
+ const last = heads.at(-1);
30
33
  if (!last)
31
34
  return [];
32
- const problems = [...passProblems(e.endings, last), ...closeProblems(e.endings, last)];
35
+ const problems = [...passProblems(heads, last), ...closeProblems(e.endings, last)];
33
36
  for (const [b, message] of problems)
34
37
  error(b.line, message, passesToken(b));
35
38
  const between = e.between.map((x) => asLine(x.line));
39
+ const written = e.endings.flatMap((x) => x.lines);
36
40
  if (problems.length)
37
- return [...e.entries.map((x) => asLine(x.line)), ...e.endings.map(asLine), ...between];
38
- const endings = e.endings.map((b) => ({
39
- passes: b.ending ?? [],
40
- entry: { line: b, repeat: null },
41
+ return [...e.entries.map((x) => asLine(x.line)), ...written.map(asLine), ...between];
42
+ const endings = e.endings.map((x) => ({
43
+ passes: x.head.ending ?? [],
44
+ entries: x.lines.map((line) => ({ line, repeat: null })),
41
45
  }));
42
- const repeat = highestPass(e.endings);
46
+ const repeat = highestPass(heads);
43
47
  return [{ kind: "bracket", line: e.line, entries: e.entries, repeat, endings }, ...between];
44
48
  }
45
49
  /** An ending line starts the endings of the open repeat, or continues them. */
46
50
  function takeEnding(st, bars, error) {
47
51
  if (bars.repeat !== null)
48
52
  error(bars.line, "x N on an ending: the endings give the count", passesToken(bars));
53
+ const ending = { head: bars, lines: [bars] };
49
54
  if (st.open)
50
- st.endings = { ...st.open, endings: [bars], between: [] };
55
+ st.endings = { ...st.open, endings: [ending], between: [] };
51
56
  else if (st.endings)
52
- st.endings.endings.push(bars);
57
+ st.endings.endings.push(ending);
53
58
  else {
54
59
  error(bars.line, "an ending follows the bars of a |: … :| repeat", passesToken(bars));
55
60
  st.items.push(asLine(bars));
@@ -91,8 +96,13 @@ function addEntry(st, entry) {
91
96
  else
92
97
  st.items.push({ kind: "line", ...entry });
93
98
  }
94
- /** Lines that may sit between endings (grammar 5.1): they mean nothing to the timeline. */
95
- const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
99
+ const repeatToken = (r) => (r === "open" ? "x ..." : `x${r}`);
100
+ /** A line an ending continues onto (grammar 5.1) joins it; its own `x N` is an error, as on the ending's first line. */
101
+ function continueEnding(e, bars, error) {
102
+ if (bars.repeat !== null)
103
+ error(bars.line, "x N on an ending: the endings give the count", repeatToken(bars.repeat));
104
+ e.endings.at(-1)?.lines.push(bars);
105
+ }
96
106
  /**
97
107
  * Pair `|:` and `:|` within one section's lines, with the endings that
98
108
  * follow a repeat (grammar 5.1). Problems are reported, and what cannot
@@ -108,6 +118,8 @@ export function pairRepeats(lines, error) {
108
118
  for (const l of lines) {
109
119
  if (l.kind === "bars" && l.ending)
110
120
  takeEnding(st, l, error);
121
+ else if (l.kind === "bars" && l.continues && st.endings)
122
+ continueEnding(st.endings, l, error);
111
123
  else if (st.endings && BETWEEN_ENDINGS.has(l.kind))
112
124
  st.endings.between.push({ line: l, repeat: null });
113
125
  else {
@@ -9,7 +9,9 @@ export type TransposeBy = {
9
9
  * The chart in another key, as canonical text (spec §8). Chord roots, slash
10
10
  * basses, note sets and every `key:` line move; text never does. Spelling
11
11
  * follows the interval from the chart's first key, so every chord keeps its
12
- * place in the key. Lines with errors stay as written, with a warning; a
12
+ * place in the key. A slot that can't be read stays as written, with a
13
+ * warning, and its line's other chords move; a line excluded for an error
14
+ * stays as written, with a warning; a
13
15
  * target that isn't a key, or a target key for a chart with none, returns
14
16
  * the text unchanged with an error. Never throws.
15
17
  */
@@ -5,7 +5,7 @@ import { printChord } from "../chords/print.js";
5
5
  import { parseDirectiveLine } from "./directives.js";
6
6
  import { alterOf, conventionalKey, plain, SHARPS, spellPitch } from "./keys.js";
7
7
  import { parseChart } from "./parse.js";
8
- import { printParsed } from "./print.js";
8
+ import { printedAsWritten, printParsed, unreadSlots } from "./print.js";
9
9
  const mod = (n, m) => ((n % m) + m) % m;
10
10
  /** The key `semitones` away, spelled with the fewest accidentals; sharps win a tie (F# over Gb). */
11
11
  function nearestKey(key, semitones) {
@@ -90,11 +90,23 @@ function moveLine(l, move, warn) {
90
90
  return { ...l, set: { ...l.set, key: { ...l.set.key, tonic: move.spell(l.set.key.tonic) } } };
91
91
  return l;
92
92
  }
93
+ /** A warning for an unreadable slot (grammar 2.3), which transposing leaves as written. */
94
+ const unmoved = (line, slot) => {
95
+ const token = slot.kind === "unknown" ? (slot.text ?? "?") : "";
96
+ return {
97
+ line,
98
+ severity: "warning",
99
+ message: `${token} can't move: it can't be read, so it stays as written`,
100
+ token,
101
+ };
102
+ };
93
103
  /**
94
104
  * The chart in another key, as canonical text (spec §8). Chord roots, slash
95
105
  * basses, note sets and every `key:` line move; text never does. Spelling
96
106
  * follows the interval from the chart's first key, so every chord keeps its
97
- * place in the key. Lines with errors stay as written, with a warning; a
107
+ * place in the key. A slot that can't be read stays as written, with a
108
+ * warning, and its line's other chords move; a line excluded for an error
109
+ * stays as written, with a warning; a
98
110
  * target that isn't a key, or a target key for a chart with none, returns
99
111
  * the text unchanged with an error. Never throws.
100
112
  */
@@ -106,13 +118,18 @@ export function transposeChart(text, by) {
106
118
  return { text, diagnostics: [move] };
107
119
  const physical = text.replace(/^/, "").split(/\r?\n/);
108
120
  const diagnostics = [];
109
- for (const line of new Set(parsed.diagnostics.filter((d) => d.severity === "error").map((d) => d.line)))
121
+ const asWritten = printedAsWritten(parsed);
122
+ for (const line of asWritten)
110
123
  diagnostics.push({
111
124
  line,
112
125
  severity: "warning",
113
126
  message: "not transposed: this line has an error",
114
127
  token: physical[line - 1]?.trim() ?? "",
115
128
  });
129
+ for (const l of parsed.lines)
130
+ if (l.kind === "bars" && !asWritten.has(l.line))
131
+ for (const s of unreadSlots(l))
132
+ diagnostics.push(unmoved(l.line, s));
116
133
  const warn = (line, token) => diagnostics.push({
117
134
  line,
118
135
  severity: "warning",
@@ -106,8 +106,14 @@ export type SimpleSlot = ({
106
106
  } | {
107
107
  kind: "silence";
108
108
  push?: Push;
109
- } | {
109
+ }
110
+ /**
111
+ * Unknown harmony: a written `?`, or a slot that can't be read (an error,
112
+ * grammar principle 4), which keeps the author's `text` as written.
113
+ */
114
+ | {
110
115
  kind: "unknown";
116
+ text?: string;
111
117
  }) & {
112
118
  /** A dotted member of a two-member group (grammar 2.2): three quarters of its slot. */
113
119
  dotted?: true;
@@ -199,6 +205,11 @@ export type Line = {
199
205
  repeat: Repeat;
200
206
  /** The passes an ending plays on (grammar 5.1), in order; null for any other bar line. */
201
207
  ending: number[] | null;
208
+ /**
209
+ * On a plain bar line that continues an ending onto another line
210
+ * (grammar 5.1): that ending's passes. Absent on every other line.
211
+ */
212
+ continues?: number[];
202
213
  /** The declared label of the part whose line this is (grammar 7.4); absent on a tutti line and in a single-part chart. */
203
214
  part?: string;
204
215
  /** The part's line this is (`RH` in `Pno.RH`, grammar 7.6), as first spelled; absent on a part's bare line. */
@@ -1,7 +1,7 @@
1
- import { isBar } from "./barLine.js";
1
+ import { isBar, simpleSlots as slotsIn } from "./barLine.js";
2
2
  import { perWritten, slotTimes } from "./shares.js";
3
3
  /** Each simple slot of a bar line's cells. */
4
- const simpleSlots = (l) => l.cells.flatMap((c) => c.kind === "slots" ? c.slots.flatMap((s) => (s.kind === "group" ? s.members : [s])) : []);
4
+ const simpleSlots = (l) => slotsIn(l.cells);
5
5
  const isNote = (s) => s.kind === "chord" && s.chord.kind === "notes";
6
6
  const hasSyllables = (l) => simpleSlots(l).some((s) => s.kind === "chord" && s.syllable);
7
7
  const hasNotes = (l) => simpleSlots(l).some(isNote);
@@ -1,6 +1,7 @@
1
1
  import { toHarte } from "./harte.js";
2
2
  import { noteSemitone, transpose } from "./intervals.js";
3
3
  import { canonicalParts, printChord } from "./print.js";
4
+ import { alteredFifth, bareScan, intoGroup, pullBare, separate, stackedWarning, } from "./stacked.js";
4
5
  import { ALIASES, chordIntervals, EXTENSIONS, isOmission, OMISSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
5
6
  const ROOT = /^[A-G][#b]?/;
6
7
  const INLINE_ALTERATION = /^(b5|#5|b9|#9|#11|b13)/;
@@ -71,6 +72,14 @@ function toneProblem(tone, before) {
71
72
  }
72
73
  return TONES.includes(tone) ? null : `"${tone}" is not a tone a parenthesis can add`;
73
74
  }
75
+ /** The parts a normalized symbol is spelled from, valid together, or why not. */
76
+ function readParts(text, symbol) {
77
+ const read = tokenize(text);
78
+ if (typeof read === "string")
79
+ return { message: `${symbol}: ${read}`, token: symbol };
80
+ const parts = powerChord(read);
81
+ return validateParts(parts, symbol) ?? parts;
82
+ }
74
83
  const ORDINAL = { 3: "3rd", 5: "5th" };
75
84
  /**
76
85
  * The intervals once `no3`/`no5` leave out a tone, or why they can't: the
@@ -113,14 +122,19 @@ function logicGroups(rest) {
113
122
  const others = tones.filter((t) => t !== "5");
114
123
  return `5${others.length ? `(${others.join(",")})` : ""}${joined.slice(group[0].length)}`;
115
124
  }
116
- /** Appendix A.5 and A.6: Unicode, rejections, then aliases into canonical vocabulary. */
117
- function normalizeSymbol(symbol) {
118
- const text = symbol.replace(/♯/g, "#").replace(/♭/g, "b");
125
+ const BARE_ADD = bareScan("add(?:2|4|9|11)");
126
+ /** The text a symbol is read from: ♯ and ♭ as # and b (Appendix A.5). */
127
+ const ascii = (symbol) => symbol.replace(/♯/g, "#").replace(/♭/g, "b");
128
+ /** Appendix A.5 and A.6: rejections, then aliases into canonical vocabulary. */
129
+ function normalizeSymbol(text) {
119
130
  const rejected = rejection(text, noteSemitone);
120
131
  if (rejected)
121
132
  return rejected;
122
133
  const root = ROOT.exec(text)?.[0] ?? "";
123
134
  let rest = text.slice(root.length);
135
+ // Stacked spellings first, on the name as written; the aliases then read what is left.
136
+ const separated = separate(rest);
137
+ rest = separated.text;
124
138
  for (const [pattern, replacement] of ALIASES)
125
139
  rest = rest.replace(pattern, replacement);
126
140
  rest = logicGroups(rest);
@@ -129,33 +143,42 @@ function normalizeSymbol(symbol) {
129
143
  // `(add9)` is `(9)`: inside a group, `add` before a tone it may add is dropped.
130
144
  rest = rest.replace(/(?<=[(,]\s*)add(2|4|9|11)(?=\s*[,)])/g, "$1");
131
145
  // A bare `add9` outside any group; what is left inside one is the tokenizer's to name.
132
- const bare = /add(2|4|9|11)(?![^(]*\))/g;
133
- const added = [...rest.matchAll(bare)].map((m) => m[1] ?? "");
134
- if (added.length) {
135
- rest = rest.replace(bare, "");
136
- const close = rest.indexOf(")");
137
- if (close >= 0)
138
- rest = `${rest.slice(0, close)},${added.join(",")}${rest.slice(close)}`;
139
- else {
140
- const slash = /\/[A-G][#b]?$/.exec(rest);
141
- const at = slash ? slash.index : rest.length;
142
- rest = `${rest.slice(0, at)}(${added.join(",")})${rest.slice(at)}`;
143
- }
144
- }
145
- return { text: root + rest };
146
+ const bare = pullBare(rest, BARE_ADD);
147
+ rest = intoGroup(bare.text, bare.taken.map((a) => a.slice(3)));
148
+ return { text: root + rest, separated };
149
+ }
150
+ /**
151
+ * The warning a stacked spelling reads with (grammar 3): its suggestion is
152
+ * the symbol with its items separated, or the canonical spelling when that
153
+ * would not read as the same chord.
154
+ */
155
+ function stacked(symbol, text, normal, canonical) {
156
+ const { runTogether, bareOmission } = normal.separated;
157
+ if (!runTogether && !bareOmission)
158
+ return null;
159
+ const root = ROOT.exec(text)?.[0] ?? "";
160
+ const written = root + separate(text.slice(root.length)).text;
161
+ const check = parseChord(written);
162
+ const same = check.ok && check.value.canonical === canonical;
163
+ return stackedWarning(symbol, normal.separated, same ? written : canonical);
146
164
  }
147
165
  export function parseChord(symbol) {
148
- const normal = normalizeSymbol(symbol);
166
+ const text = ascii(symbol);
167
+ const normal = normalizeSymbol(text);
149
168
  if (!("text" in normal))
150
169
  return { ok: false, error: normal };
151
- const read = tokenize(normal.text);
152
- if (typeof read === "string") {
153
- return { ok: false, error: { message: `${symbol}: ${read}`, token: symbol } };
170
+ const r = readChord(symbol, normal.text);
171
+ if (!r.ok) {
172
+ return { ok: false, error: alteredFifth(symbol, text, r.error, (s) => parseChord(s).ok) };
154
173
  }
155
- const parts = powerChord(read);
156
- const invalid = validateParts(parts, symbol);
157
- if (invalid)
158
- return { ok: false, error: invalid };
174
+ const warning = stacked(symbol, text, normal, r.value.canonical);
175
+ return warning ? { ...r, warnings: [warning, ...r.warnings] } : r;
176
+ }
177
+ /** The chord a normalized symbol names. */
178
+ function readChord(symbol, text) {
179
+ const parts = readParts(text, symbol);
180
+ if ("message" in parts)
181
+ return { ok: false, error: parts };
159
182
  const added = chordIntervals({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) }, symbol);
160
183
  const { warnings, alteredOpen } = added;
161
184
  const intervals = omit(added.intervals, parts, symbol);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stacked spellings (grammar 3, Appendix A.5): notation programs print a
3
+ * chord's alterations one after another with no separator ("D6 add9
4
+ * omit5"), so a chart arrives as `D6(omit5add9)` or `Gadd9omit3`. These
5
+ * read as their comma-separated form. Every scan here is one pass over the
6
+ * text, so a long symbol costs its length.
7
+ */
8
+ import type { Diagnostic } from "./types.js";
9
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
10
+ export declare const bareScan: (bare: string) => RegExp;
11
+ /**
12
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
13
+ * taken out (and each group's items passed through `group`), and what was
14
+ * taken.
15
+ */
16
+ export declare function pullBare(rest: string, scan: RegExp, group?: (inner: string) => string): {
17
+ text: string;
18
+ taken: string[];
19
+ };
20
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
21
+ export declare function intoGroup(rest: string, items: string[]): string;
22
+ export type Separated = {
23
+ text: string;
24
+ runTogether: boolean;
25
+ bareOmission: boolean;
26
+ };
27
+ /**
28
+ * The text after a root with items run together in a parenthesis separated
29
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
30
+ * quality however it is spelled, before any parenthesis or slash bass)
31
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
32
+ * `add9(omit3)`.
33
+ */
34
+ export declare function separate(rest: string): Separated;
35
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
36
+ export declare function stackedWarning(symbol: string, separated: Separated, suggestion: string): Diagnostic | null;
37
+ /**
38
+ * The error for a symbol that can't be read, with a suggestion when it
39
+ * writes an altered fifth before the parenthesis on a chord with no
40
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
41
+ * whether a suggestion reads. Where the root's own accidental could be the
42
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
43
+ * suggestion; only when that fifth reading would itself read.
44
+ */
45
+ export declare function alteredFifth(symbol: string, text: string, error: Diagnostic, reads: (symbol: string) => boolean): Diagnostic;
@@ -0,0 +1,122 @@
1
+ /** The shape of one parenthesis item; the tokenizer judges what it names. */
2
+ const ITEM = /^(?:add\d+|(?:omit\s*|no)\d+|[b#]?\d+)$/;
3
+ /** Where an item run together with the one before it starts. */
4
+ const ITEM_START = /(?=add|omit|no|[b#])/;
5
+ /** A slash bass at the end of the text after the root. */
6
+ const BASS = /\/[A-G][#b]?$/;
7
+ /** Where the chord's name ends: its first parenthesis or slash bass. */
8
+ const NAME_END = /\(|\/[A-G]/;
9
+ /** The items run together in one parenthesis item, or the item alone when it isn't a run of valid items. */
10
+ function splitItem(item) {
11
+ const pieces = item.split(ITEM_START).map((p) => p.trim());
12
+ return pieces.length > 1 && pieces.every((p) => ITEM.test(p)) ? pieces : [item];
13
+ }
14
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
15
+ export const bareScan = (bare) => new RegExp(String.raw `\((?<inner>[^()]*)\)|${bare}`, "g");
16
+ /**
17
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
18
+ * taken out (and each group's items passed through `group`), and what was
19
+ * taken.
20
+ */
21
+ export function pullBare(rest, scan, group = (inner) => inner) {
22
+ const taken = [];
23
+ const text = rest.replace(scan, (match, ...args) => {
24
+ const { inner } = args.at(-1);
25
+ if (inner !== undefined)
26
+ return `(${group(inner)})`;
27
+ taken.push(match);
28
+ return "";
29
+ });
30
+ return { text, taken };
31
+ }
32
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
33
+ export function intoGroup(rest, items) {
34
+ if (!items.length)
35
+ return rest;
36
+ const close = rest.lastIndexOf(")");
37
+ if (close >= 0)
38
+ return `${rest.slice(0, close)},${items.join(",")}${rest.slice(close)}`;
39
+ const at = BASS.exec(rest)?.index ?? rest.length;
40
+ return `${rest.slice(0, at)}(${items.join(",")})${rest.slice(at)}`;
41
+ }
42
+ /** A parenthesis and its items. */
43
+ const GROUP = /\((?<inner>[^()]*)\)/g;
44
+ /** A bare `omit`/`no` ending the chord's name. */
45
+ const TRAILING_OMISSION = /(?:omit\s*|no)\d+$/;
46
+ /**
47
+ * The text after a root with items run together in a parenthesis separated
48
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
49
+ * quality however it is spelled, before any parenthesis or slash bass)
50
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
51
+ * `add9(omit3)`.
52
+ */
53
+ export function separate(rest) {
54
+ let runTogether = false;
55
+ const split = (inner) => {
56
+ const items = inner.split(",");
57
+ const out = items.flatMap(splitItem);
58
+ if (out.length > items.length)
59
+ runTogether = true;
60
+ return out.join(",");
61
+ };
62
+ const text = rest.replace(GROUP, (_, inner) => `(${split(inner)})`);
63
+ // The chord's name: what comes before the first parenthesis or slash bass
64
+ // (a slash before a letter; `6/9` is an extension), whatever follows it.
65
+ const end = NAME_END.exec(text)?.index ?? text.length;
66
+ const name = text.slice(0, end);
67
+ const bare = TRAILING_OMISSION.exec(name);
68
+ if (!bare)
69
+ return { text, runTogether, bareOmission: false };
70
+ const moved = intoGroup(name.slice(0, bare.index) + text.slice(end), [bare[0]]);
71
+ return { text: moved, runTogether, bareOmission: true };
72
+ }
73
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
74
+ export function stackedWarning(symbol, separated, suggestion) {
75
+ const why = [
76
+ ...(separated.runTogether ? ["items in a parenthesis are separated by commas"] : []),
77
+ ...(separated.bareOmission ? ["an omission goes in parentheses"] : []),
78
+ ];
79
+ if (!why.length)
80
+ return null;
81
+ return { message: `${symbol}: ${why.join("; ")}`, token: symbol, suggestion };
82
+ }
83
+ /** An altered fifth straight after the root (and `m`), with no extension: `F#b5(omit3)`. */
84
+ const ALTERED_FIFTH = /^([A-G][#b]?)(m?)([b#]5)(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
85
+ /** A root whose accidental a following `5` could be read with: `Gb5`, `G#5`. */
86
+ const SWALLOWED = /^([A-G])([#b])5(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
87
+ /**
88
+ * The error for a symbol that can't be read, with a suggestion when it
89
+ * writes an altered fifth before the parenthesis on a chord with no
90
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
91
+ * whether a suggestion reads. Where the root's own accidental could be the
92
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
93
+ * suggestion; only when that fifth reading would itself read.
94
+ */
95
+ export function alteredFifth(symbol, text, error, reads) {
96
+ const s = SWALLOWED.exec(text);
97
+ if (s) {
98
+ const [, letter = "", accidental = "", inner, bass = ""] = s;
99
+ const items = inner?.trim() ? `,${inner}` : "";
100
+ const fifth = letter + separate(`(${accidental}5${items})${bass}`).text;
101
+ if (!reads(fifth))
102
+ return error;
103
+ const power = `${letter}${accidental}5`;
104
+ return {
105
+ ...error,
106
+ message: `${error.message}; ambiguous: ${power} is always the ${letter}${accidental} power chord (grammar 3); a ${letter} chord with a ${accidental}5 writes it in the parentheses`,
107
+ };
108
+ }
109
+ const m = ALTERED_FIFTH.exec(text);
110
+ if (!m)
111
+ return error;
112
+ const [, root = "", minor = "", fifth = "", inner, bass = ""] = m;
113
+ const items = inner?.trim() ? `,${inner}` : "";
114
+ const suggestion = root + separate(`${minor}(${fifth}${items})${bass}`).text;
115
+ if (!reads(suggestion))
116
+ return error;
117
+ return {
118
+ message: `${symbol}: an altered 5th goes in the parentheses unless it follows an extension (grammar 3)`,
119
+ token: symbol,
120
+ suggestion,
121
+ };
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {