barmark 0.10.0 → 0.12.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,76 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.12.0] - 2026-11-03
13
+
14
+ Rehearsal marks and words on a bar, issue #70 (grammar 2.5 and 2.6);
15
+ omissions, voicings, accents, hits and push marks (grammar 2.7, 2.8, 3
16
+ and 4.2).
17
+
18
+ ### Added
19
+
20
+ - **Rehearsal marks:** `@` and a label of letters and digits, alone in a
21
+ cell (`| @B | D | A |`), marks the bar after it. A mark is not a bar
22
+ and takes no time; a repeat or replay plays it with its bar. Cells
23
+ gain `kind: "rehearsal"`, and played bars `rehearsal`, the label.
24
+ - **Words on a bar:** quoted words in a cell (`| "solo" D |`,
25
+ `| D "rit." G |`) sit before the slot they precede, or at the bar's
26
+ end after the last. Curly quotes are accepted. They carry no musical
27
+ meaning. Cells and played bars gain `words` (`{ text, at }`), present
28
+ only when written.
29
+ - **Omissions:** `no3` and `no5` in a chord's parentheses leave out its
30
+ third or fifth (`C7(no3)`, `C7(b9,no5)`). `(omit3)` and `(omit 3)`
31
+ are accepted and print as `(no3)`; `C(no3)` prints as `C5`. Harte
32
+ labels mark them with `*` (`C:7(*3)`).
33
+ - **Voicings:** a chord name followed by a note set gives the chord and
34
+ its exact notes (`Cmaj7{E3 G3 B3 C4}`). Every note must be in the
35
+ chord. Chord slots gain `voicing`, and it transposes with the chord.
36
+ - **Accents and hits:** `>D` accents a chord or note set and `^D` makes
37
+ it a hit, short and accented. Chord slots gain `articulation`
38
+ (`"accent"` or `"hit"`).
39
+ - **Push marks:** `<D` arrives an eighth early and `<<D` a sixteenth,
40
+ taking the time from the slot played just before it in play order,
41
+ so a pushed downbeat works inside repeats, replays and jumps. Chord,
42
+ `N.C.` and `--` slots gain `push` (`"eighth"` or `"sixteenth"`).
43
+ - **Errors with line numbers** for an omission the chord can't make, a
44
+ voicing note not in its chord, an accent on anything but a chord or
45
+ note set, a push with nothing before it or longer than the slot it
46
+ borrows from, a push on `/`, `%`, `?` or inside a group, and `^<D`
47
+ (with the fix `<^D`); and for a mark that shares its cell (with
48
+ the fix), a bad label, a mark with no bar after it, two marks on one
49
+ bar, an unclosed quote, empty quotes and words with no bar.
50
+
51
+ ### Fixed
52
+
53
+ - **A bar line dropped for an error no longer counts its directions as
54
+ bars** in the written numbers of the bars after it.
55
+
56
+ ## [0.11.0] - 2026-11-03
57
+
58
+ Endings and directions, issue #70 (grammar 5.1 and 5.2).
59
+
60
+ ### Added
61
+
62
+ - **First and second endings:** an ending is a bar line of its own,
63
+ `|1 G | G7 :|` then `|2 G | C |`, also `|1-3` and `|1,3`. Endings
64
+ follow a `|: … :|` repeat, and each pass plays its own ending. Bar
65
+ lines carry `ending`, the passes it plays on.
66
+ - **Directions:** `Segno`, `Coda`, `To Coda`, `Fine`, and one jump per
67
+ chart, `D.C.` or `D.S.`, alone or `al Fine` / `al Coda`. A direction
68
+ is a cell of its own (`kind: "direction"`), a place between bars, not
69
+ a bar. Play order follows the jump; after it, every repeat plays
70
+ once and takes its last ending.
71
+ - **Errors with line numbers** for endings that don't add up (a pass with
72
+ no ending or two, a last ending that goes back) and for directions
73
+ the jump can't use (no Segno before `D.S.`, `al Coda` with no
74
+ `To Coda`, a mark no jump uses, a second jump).
75
+ - **`printPasses` and `printDirection`**, the canonical spellings.
76
+
77
+ ### Changed
78
+
79
+ - **`|1` was reserved and is now an ending;** a chart that wrote it had an
80
+ error before, so no valid chart changes meaning.
81
+
12
82
  ## [0.10.0] - 2026-11-03
13
83
 
14
84
  Written bar numbers on played bars, issue #70. No chart changes meaning.
@@ -234,7 +304,9 @@ The first working release: the reference parser and printer for the
234
304
 
235
305
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
236
306
 
237
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.10.0...HEAD
307
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.12.0...HEAD
308
+ [0.12.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.11.0...barmark-v0.12.0
309
+ [0.11.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.10.0...barmark-v0.11.0
238
310
  [0.10.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.9.0...barmark-v0.10.0
239
311
  [0.9.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.8.0...barmark-v0.9.0
240
312
  [0.8.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.7.0...barmark-v0.8.0
@@ -1,7 +1,17 @@
1
- import type { ChartDiagnostic, Line, Repeat } from "./types.js";
1
+ import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot, Words } from "./types.js";
2
2
  type BarsLine = Extract<Line, {
3
3
  kind: "bars";
4
4
  }>;
5
+ /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
6
+ export declare const isBar: (c: Cell) => c is {
7
+ kind: "slots";
8
+ meter: Meter | null;
9
+ slots: Slot[];
10
+ words?: Words[];
11
+ } | {
12
+ kind: "simile";
13
+ words?: Words[];
14
+ };
5
15
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
6
16
  export declare function readRepeat(count: string, line: number, diagnostics: ChartDiagnostic[]): Repeat;
7
17
  /**
@@ -1,7 +1,13 @@
1
+ import { noteSemitone } from "../chords/intervals.js";
1
2
  import { parseNoteSet } from "../chords/noteSet.js";
2
3
  import { parseChord } from "../chords/parse.js";
4
+ import { isDirectionWord, readDirection } from "./direction.js";
3
5
  import { parseMeter } from "./directives.js";
4
6
  const FERMATA = new Set(["...", "…"]);
7
+ /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
8
+ export const isBar = (c) => c.kind === "slots" || c.kind === "simile";
9
+ const QUOTES = new Set(['"', "“", "”", "„"]);
10
+ const LABEL = /^@[A-Za-z0-9]+$/;
5
11
  const SILENCE = new Set(["--", "–", "—"]);
6
12
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
7
13
  export function readRepeat(count, line, diagnostics) {
@@ -98,12 +104,227 @@ function tokens(text) {
98
104
  out.push(current);
99
105
  return out;
100
106
  }
107
+ /** `3` or `1-3` as its passes; null when it reads as none. */
108
+ function passRange(part) {
109
+ const m = /^([1-9]\d{0,2})(?:-([1-9]\d{0,2}))?$/.exec(part);
110
+ if (!m)
111
+ return null;
112
+ const from = Number(m[1]);
113
+ const to = Number(m[2] ?? from);
114
+ if (m[2] !== undefined && to <= from)
115
+ return null;
116
+ return Array.from({ length: to - from + 1 }, (_, i) => from + i);
117
+ }
118
+ /** `1`, `1-3` or `1,3`: the passes an ending plays on, in order; null when they read as none. */
119
+ function readPasses(text) {
120
+ const ranges = text.split(",").map(passRange);
121
+ const passes = ranges.flatMap((r) => r ?? []).sort((a, b) => a - b);
122
+ const repeated = new Set(passes).size !== passes.length;
123
+ return ranges.includes(null) || repeated ? null : passes;
124
+ }
125
+ const ENDING_FORM = "an ending is |1, |2, |1-3 or |1,3, then a space";
126
+ /** A leading ending mark: the line without it, its passes, and the mark if it doesn't read. */
127
+ function readEnding(body) {
128
+ const mark = /^\|(\d[\d,-]*)(?=\s)/.exec(body);
129
+ if (!mark)
130
+ return { body, ending: null, bad: null };
131
+ const ending = readPasses(mark[1] ?? "");
132
+ return { body: `|${body.slice(mark[0].length)}`, ending, bad: ending ? null : mark[0] };
133
+ }
134
+ /** An ending mark left in the line, and what to say about it. */
135
+ function strayEnding(body) {
136
+ const m = /\|\d+\S*/.exec(body);
137
+ if (!m)
138
+ return null;
139
+ return [m.index === 0 ? ENDING_FORM : "an ending starts its own bar line", m[0]];
140
+ }
141
+ /** Why a token can't share its cell: `%`, `...` and the words of a direction stand alone. */
142
+ function mustStandAlone(token) {
143
+ if (token === "%" || FERMATA.has(token))
144
+ return `${token} must be alone in a cell`;
145
+ if (isDirectionWord(token))
146
+ return `${token} is part of a direction, which must be alone in its cell`;
147
+ return null;
148
+ }
149
+ /** A cell that is a direction, or what is wrong with one; null when the cell isn't one. */
150
+ function directionCell(rest, meter) {
151
+ const named = readDirection(rest);
152
+ if (!named)
153
+ return null;
154
+ if ("direction" in named)
155
+ return meter
156
+ ? { problem: "a one-bar meter cannot go on a direction" }
157
+ : { cell: { kind: "direction", direction: named.direction } };
158
+ // Only words a chord never uses make a near miss: `| D C |` is two chords, not D.C.
159
+ if (!rest.includes(".") && !tokens(rest).some(isDirectionWord))
160
+ return null;
161
+ return { problem: `not a direction; write ${named.suggestion}`, suggestion: named.suggestion };
162
+ }
101
163
  /** The bars a bar line writes, read from its pipes alone (fermatas not counted), so a line dropped for an error still counts. */
102
164
  const barsWritten = (body) => body
103
165
  .split("|")
104
166
  .slice(1)
105
167
  .map((p) => p.trim())
106
- .filter((p) => p !== "" && !FERMATA.has(p)).length;
168
+ .filter((p) => p !== "" && !FERMATA.has(p) && !LABEL.test(p) && !isDirectionCell(p)).length;
169
+ const isDirectionCell = (p) => {
170
+ const d = readDirection(p);
171
+ return !!d && "direction" in d;
172
+ };
173
+ /**
174
+ * Quoted words out of a cell (grammar 2.6): the cell with each one blanked,
175
+ * and where each goes, before the slot it precedes.
176
+ */
177
+ function readWords(cell) {
178
+ const words = [];
179
+ let bare = "";
180
+ let open = null;
181
+ for (const [i, ch] of [...cell].entries()) {
182
+ if (!QUOTES.has(ch)) {
183
+ if (open === null)
184
+ bare += ch;
185
+ continue;
186
+ }
187
+ if (open === null) {
188
+ open = i;
189
+ continue;
190
+ }
191
+ const text = [...cell]
192
+ .slice(open + 1, i)
193
+ .join("")
194
+ .trim();
195
+ if (!text)
196
+ return { problem: "empty words between quotes", token: '""' };
197
+ words.push({ text, at: tokens(bare).length });
198
+ bare += " ";
199
+ open = null;
200
+ }
201
+ if (open !== null)
202
+ return { problem: "words need a closing quote", token: [...cell].slice(open).join("") };
203
+ return { bare, words };
204
+ }
205
+ /** A leading `[n/d]` and the rest of the cell; `bad` is a bracket that is no time signature. */
206
+ function readMeter(cell) {
207
+ const bracket = /^\[([^\]]*)\]/.exec(cell);
208
+ if (!bracket)
209
+ return { meter: null, after: cell, bad: null };
210
+ const meter = parseMeter(bracket[1] ?? "");
211
+ return { meter, after: cell.slice(bracket[0].length).trim(), bad: meter ? null : bracket[0] };
212
+ }
213
+ const emptyCell = (words) => words.length ? "words go on a bar; this cell has no slot" : "a cell needs at least one slot";
214
+ /** `%` or `...` alone in a cell, or what is wrong with it; null when the cell is neither. */
215
+ function symbolCell(bare, meter, words) {
216
+ const only = tokens(bare);
217
+ const t = only[0] ?? "";
218
+ if (only.length !== 1 || (t !== "%" && !FERMATA.has(t)))
219
+ return null;
220
+ if (meter)
221
+ return { problem: "a one-bar meter cannot go on % or ...", token: t };
222
+ if (t !== "%")
223
+ return words.length
224
+ ? { problem: "words go on a bar, not on ...", token: t }
225
+ : { cell: { kind: "fermata" } };
226
+ // Words on `%` go on the whole bar.
227
+ const onBar = words.map((w) => ({ ...w, at: 0 }));
228
+ return { cell: words.length ? { kind: "simile", words: onBar } : { kind: "simile" } };
229
+ }
230
+ /** A direction alone in a cell, or what is wrong with it; null when the cell isn't one. */
231
+ function directionWithWords(bare, meter, words) {
232
+ const token = bare.trim();
233
+ const d = directionCell(token, meter);
234
+ if (!d)
235
+ return null;
236
+ if (!("cell" in d))
237
+ return { problem: d.problem, token, ...(d.suggestion ? { suggestion: d.suggestion } : {}) };
238
+ return words.length ? { problem: "words go on a bar, not on a direction", token } : d;
239
+ }
240
+ const ARTICULATION = { ">": "accent", "^": "hit" };
241
+ const PUSH = { 1: "eighth", 2: "sixteenth" };
242
+ /** A slot's leading marks (grammar 2.7, 2.8): a push, then an articulation, then the slot itself. */
243
+ function readMarks(token) {
244
+ const pushes = /^<*/.exec(token)?.[0].length ?? 0;
245
+ const push = PUSH[pushes];
246
+ if (pushes && !push)
247
+ return { problem: "a push is < (an eighth) or << (a sixteenth)", token };
248
+ const marked = readArticulation(token.slice(pushes), token);
249
+ return "problem" in marked ? marked : { ...(push ? { push } : {}), ...marked };
250
+ }
251
+ /** A leading `>` or `^`, and the slot after it; a push after it is written in the wrong order. */
252
+ function readArticulation(text, token) {
253
+ const articulation = ARTICULATION[text[0] ?? ""];
254
+ if (!articulation)
255
+ return { rest: text };
256
+ const rest = text.slice(1);
257
+ if (!rest.startsWith("<"))
258
+ return { articulation, rest };
259
+ const suggestion = rest.replace(/^(<+)/, `$1${text[0]}`);
260
+ return { problem: "a push and an accent: write the push first", token, suggestion };
261
+ }
262
+ const UNPUSHABLE = new Set(["/", "?", "%", "...", "…"]);
263
+ /** Why these marks can't go on this slot; null when they can. */
264
+ function marksProblem(marks, inGroup, token) {
265
+ if (marks.push && inGroup)
266
+ return { problem: "a push goes on a whole slot, not inside a group", token };
267
+ if (marks.push && UNPUSHABLE.has(marks.rest))
268
+ return { problem: "a push goes on a chord, a note set, N.C. or --", token };
269
+ const plain = UNPUSHABLE.has(marks.rest) || SILENCE.has(marks.rest) || /^n\.?c\.?$/i.test(marks.rest);
270
+ if (marks.articulation && plain)
271
+ return { problem: "an accent or a hit goes on a chord or a note set", token };
272
+ return null;
273
+ }
274
+ /** Whether a voicing's note is one of the chord's, by pitch class. */
275
+ const inChord = (note, chord) => {
276
+ const pc = (n) => (noteSemitone(n.replace(/\d|!/g, "")) + 12) % 12;
277
+ return chord.pitches.some((p) => pc(p) === pc(note));
278
+ };
279
+ /** `Cmaj7{E3 G3 B3}`: the chord, and the notes it is voiced with, each one of its own (grammar 4.2). */
280
+ function parseVoiced(token, brace) {
281
+ const chord = parseChord(token.slice(0, brace));
282
+ if (!chord.ok)
283
+ return {
284
+ problem: chord.error.message,
285
+ token,
286
+ ...(chord.error.suggestion ? { suggestion: chord.error.suggestion } : {}),
287
+ };
288
+ const voicing = parseNoteSet(token.slice(brace));
289
+ if (!voicing.ok)
290
+ return { problem: voicing.error.message, token: voicing.error.token };
291
+ const stray = voicing.value.pitches.find((n) => !inChord(n, chord.value));
292
+ if (stray)
293
+ return {
294
+ problem: `${stray.replace(/\d/g, "")} is not in ${chord.value.canonical}`,
295
+ token: stray,
296
+ };
297
+ return { chord: chord.value, voicing: voicing.value, warnings: [chord, voicing] };
298
+ }
299
+ /** A cell that is one thing alone (a mark, a direction, `%` or `...`), or what is wrong with it. */
300
+ const standalone = (bare, meter, words) => rehearsalCell(bare, meter, words) ??
301
+ directionWithWords(bare, meter, words) ??
302
+ symbolCell(bare, meter, words);
303
+ /** A `@B` cell, or what is wrong with one; null when the cell has no mark. */
304
+ function rehearsalCell(bare, meter, words) {
305
+ const list = tokens(bare);
306
+ const at = list.findIndex((t) => t.startsWith("@"));
307
+ const mark = list[at];
308
+ if (mark === undefined)
309
+ return null;
310
+ if (!LABEL.test(mark))
311
+ return {
312
+ problem: "a rehearsal mark is @ and a label of letters and digits, like @B or @17",
313
+ token: mark,
314
+ };
315
+ if (words.length)
316
+ return { problem: "words go on a bar, not on a rehearsal mark", token: mark };
317
+ if (meter)
318
+ return { problem: "a one-bar meter cannot go on a rehearsal mark", token: mark };
319
+ if (list.length === 1)
320
+ return { cell: { kind: "rehearsal", label: mark.slice(1) } };
321
+ const others = list.filter((_, i) => i !== at).join(" ");
322
+ return {
323
+ problem: "a rehearsal mark is a cell of its own",
324
+ token: mark,
325
+ suggestion: `| ${mark} | ${others} |`,
326
+ };
327
+ }
107
328
  /**
108
329
  * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
109
330
  * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
@@ -137,6 +358,11 @@ export function parseBarLine(text, line) {
137
358
  body = body.slice(0, lastPipe + 1) + tail.rest;
138
359
  repeat = readRepeat(tail.count, line, diagnostics);
139
360
  }
361
+ const leading = readEnding(body);
362
+ body = leading.body;
363
+ const ending = leading.ending;
364
+ if (leading.bad)
365
+ error(ENDING_FORM, leading.bad);
140
366
  const opens = body.startsWith("|:");
141
367
  if (opens)
142
368
  body = `|${body.slice(2)}`;
@@ -144,8 +370,9 @@ export function parseBarLine(text, line) {
144
370
  if (closes)
145
371
  body = `${body.slice(0, -2)}|`;
146
372
  const written = barsWritten(body);
147
- if (/\|\d/.test(body))
148
- error("endings are not supported in v0.1", /\|\d+/.exec(body)?.[0] ?? "|");
373
+ const stray = strayEnding(body);
374
+ if (stray)
375
+ error(...stray);
149
376
  if (body.includes(":|") || body.includes("|:"))
150
377
  error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
151
378
  // A misplaced mark makes the cells unreadable: report it once, not again as chords.
@@ -156,6 +383,7 @@ export function parseBarLine(text, line) {
156
383
  parts.pop();
157
384
  else
158
385
  warn("missing trailing |", parts.at(-1)?.trim() ?? "");
386
+ const report = (p) => error(p.problem, p.token, p.suggestion);
159
387
  const simple = (token) => {
160
388
  if (token === "/")
161
389
  return { kind: "hold" };
@@ -172,79 +400,91 @@ export function parseBarLine(text, line) {
172
400
  const misplaced = misplacedRepeat(token);
173
401
  if (misplaced)
174
402
  return error("a repeat is written x N after the final |", token, misplaced);
175
- if (token === "%" || FERMATA.has(token))
176
- return error(`${token} must be alone in a cell`, token);
177
- const r = token.startsWith("{") ? parseNoteSet(token) : parseChord(token);
403
+ const alone = mustStandAlone(token);
404
+ if (alone)
405
+ return error(alone, token);
406
+ return chordSlot(token);
407
+ };
408
+ /** A chord, a note set, or a chord with its voicing. */
409
+ const chordSlot = (token) => {
410
+ const brace = token.indexOf("{");
411
+ if (brace > 0) {
412
+ const v = parseVoiced(token, brace);
413
+ if ("problem" in v)
414
+ return report(v);
415
+ for (const r of v.warnings)
416
+ for (const w of r.ok ? r.warnings : [])
417
+ warn(w.message, w.token);
418
+ return { kind: "chord", chord: v.chord, voicing: v.voicing };
419
+ }
420
+ const r = brace === 0 ? parseNoteSet(token) : parseChord(token);
178
421
  if (!r.ok)
179
422
  return error(r.error.message, token, r.error.suggestion);
180
423
  for (const w of r.warnings)
181
424
  warn(w.message, w.token);
182
425
  return { kind: "chord", chord: r.value };
183
426
  };
427
+ /** A slot with its push and articulation, if written. */
428
+ const markedSlot = (token, inGroup) => {
429
+ const marks = readMarks(token);
430
+ if ("problem" in marks)
431
+ return report(marks);
432
+ const problem = marksProblem(marks, inGroup, token);
433
+ if (problem)
434
+ return report(problem);
435
+ const base = simple(marks.rest);
436
+ const { push, articulation } = marks;
437
+ return (base &&
438
+ {
439
+ ...base,
440
+ ...(push ? { push } : {}),
441
+ ...(articulation ? { articulation } : {}),
442
+ });
443
+ };
444
+ /** One slot token: a simple slot, or a `_` group of them. */
445
+ const slotOf = (token) => {
446
+ const members = groupMembers(token);
447
+ if (members.length === 1)
448
+ return markedSlot(token, false);
449
+ const out = [];
450
+ for (const m of members) {
451
+ const s = m ? markedSlot(m, true) : error("an empty member in a group", token);
452
+ if (s)
453
+ out.push(s);
454
+ }
455
+ return { kind: "group", members: out };
456
+ };
457
+ const readCell = (raw) => {
458
+ const rest = raw.trim();
459
+ if (!rest)
460
+ return error("an empty cell; use / to hold or % to repeat", "| |");
461
+ const { meter, after, bad } = readMeter(rest);
462
+ if (bad)
463
+ error("not a time signature", bad);
464
+ const read = readWords(after);
465
+ if ("problem" in read)
466
+ return report(read);
467
+ const { bare, words } = read;
468
+ if (bare.includes("["))
469
+ return error("a [n/d] meter must start its cell", rest);
470
+ const alone = standalone(bare, meter, words);
471
+ if (alone)
472
+ return "cell" in alone ? alone.cell : report(alone);
473
+ return slotsCell(bare, meter, words, raw.trim());
474
+ };
475
+ const slotsCell = (bare, meter, words, raw) => {
476
+ const slots = tokens(bare).map(slotOf);
477
+ if (!slots.length)
478
+ return error(emptyCell(words), raw);
479
+ const kept = slots.filter((x) => x !== null);
480
+ return { kind: "slots", meter, slots: kept, ...(words.length ? { words } : {}) };
481
+ };
184
482
  if (parts.length === 0)
185
483
  error("a bar line needs at least one cell", text.trim());
186
- const cells = [];
187
- for (const raw of parts) {
188
- let rest = raw.trim();
189
- if (!rest) {
190
- error("an empty cell; use / to hold or % to repeat", "| |");
191
- continue;
192
- }
193
- let meter = null;
194
- const bracket = /^\[([^\]]*)\]/.exec(rest);
195
- if (bracket) {
196
- meter = parseMeter(bracket[1] ?? "");
197
- if (!meter)
198
- error("not a time signature", bracket[0]);
199
- rest = rest.slice(bracket[0].length).trim();
200
- }
201
- if (rest.includes("[")) {
202
- error("a [n/d] meter must start its cell", rest);
203
- continue;
204
- }
205
- const list = tokens(rest);
206
- if (list.length === 0) {
207
- error("a cell needs at least one slot", raw.trim());
208
- continue;
209
- }
210
- if (list.length === 1 && meter && (list[0] === "%" || FERMATA.has(list[0] ?? ""))) {
211
- error("a one-bar meter cannot go on % or ...", rest);
212
- continue;
213
- }
214
- if (list.length === 1 && !meter && list[0] === "%") {
215
- cells.push({ kind: "simile" });
216
- continue;
217
- }
218
- if (list.length === 1 && !meter && FERMATA.has(list[0] ?? "")) {
219
- cells.push({ kind: "fermata" });
220
- continue;
221
- }
222
- const slots = [];
223
- for (const token of list) {
224
- const parts = groupMembers(token);
225
- if (parts.length === 1) {
226
- const s = simple(token);
227
- if (s)
228
- slots.push(s);
229
- continue;
230
- }
231
- const members = [];
232
- for (const m of parts) {
233
- if (!m)
234
- error("an empty member in a group", token);
235
- else {
236
- const s = simple(m);
237
- if (s)
238
- members.push(s);
239
- }
240
- }
241
- slots.push({ kind: "group", members });
242
- }
243
- cells.push({ kind: "slots", meter, slots });
244
- }
484
+ const cells = parts.map(readCell).filter((c) => c !== null);
245
485
  const failed = diagnostics.some((d) => d.severity === "error");
246
486
  return {
247
- bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat },
487
+ bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
248
488
  written,
249
489
  diagnostics,
250
490
  };
@@ -0,0 +1,23 @@
1
+ import type { Direction, Line } from "./types.js";
2
+ /** A cell's text as a direction, the spelling it nearly is, or neither. */
3
+ export declare function readDirection(cell: string): {
4
+ direction: Direction;
5
+ } | {
6
+ suggestion: string;
7
+ } | null;
8
+ /** A slot token that belongs to a direction, which must have its cell to itself. */
9
+ export declare const isDirectionWord: (token: string) => boolean;
10
+ /** A direction in its canonical spelling. */
11
+ export declare function printDirection(d: Direction): string;
12
+ type Report = (line: number, message: string, token: string) => void;
13
+ /** Where the one jump goes back to and where it ends. */
14
+ export type JumpPlan = {
15
+ to: "start" | "segno";
16
+ al: "fine" | "coda" | null;
17
+ };
18
+ /**
19
+ * Check a chart's directions (grammar 5.2) and say where its jump goes.
20
+ * A chart with a problem in its directions plays without the jump.
21
+ */
22
+ export declare function planJump(lines: Line[], error: Report): JumpPlan | null;
23
+ export {};
@@ -0,0 +1,99 @@
1
+ /** Every direction in its canonical spelling (grammar 5.2). */
2
+ const SPELLINGS = [
3
+ ["Segno", { kind: "segno" }],
4
+ ["Coda", { kind: "coda" }],
5
+ ["To Coda", { kind: "to coda" }],
6
+ ["Fine", { kind: "fine" }],
7
+ ["D.C.", { kind: "jump", to: "start", al: null }],
8
+ ["D.C. al Fine", { kind: "jump", to: "start", al: "fine" }],
9
+ ["D.C. al Coda", { kind: "jump", to: "start", al: "coda" }],
10
+ ["D.S.", { kind: "jump", to: "segno", al: null }],
11
+ ["D.S. al Fine", { kind: "jump", to: "segno", al: "fine" }],
12
+ ["D.S. al Coda", { kind: "jump", to: "segno", al: "coda" }],
13
+ ];
14
+ /** The score's own signs, accepted on input. */
15
+ const SYMBOLS = new Map([
16
+ ["𝄋", "Segno"],
17
+ ["𝄌", "Coda"],
18
+ ]);
19
+ const exact = (text) => text.toLowerCase().replace(/\s+/g, " ").trim();
20
+ /** Dots and spaces dropped: what a near miss still shares with the spelling. */
21
+ const loose = (text) => exact(text).replace(/[.\s]/g, "");
22
+ /** The words directions are made of, which a chord never is. */
23
+ const WORDS = new Set(["segno", "coda", "to", "fine", "dc", "ds", "al", "𝄋", "𝄌"]);
24
+ /** A cell's text as a direction, the spelling it nearly is, or neither. */
25
+ export function readDirection(cell) {
26
+ const text = SYMBOLS.get(cell.trim()) ?? cell;
27
+ const hit = SPELLINGS.find(([s]) => exact(s) === exact(text));
28
+ if (hit)
29
+ return { direction: hit[1] };
30
+ const near = SPELLINGS.find(([s]) => loose(s) === loose(text));
31
+ return near ? { suggestion: near[0] } : null;
32
+ }
33
+ /** A slot token that belongs to a direction, which must have its cell to itself. */
34
+ export const isDirectionWord = (token) => WORDS.has(loose(token));
35
+ /** A direction in its canonical spelling. */
36
+ export function printDirection(d) {
37
+ const hit = SPELLINGS.find(([, s]) => s.kind === d.kind &&
38
+ (s.kind !== "jump" || (d.kind === "jump" && s.to === d.to && s.al === d.al)));
39
+ return hit?.[0] ?? "";
40
+ }
41
+ /** Whether `a` and `b` are both written, `a` first. */
42
+ const inOrder = (a, b) => !!a && !!b && (a.line < b.line || (a.line === b.line && a.cell < b.cell));
43
+ /** Every direction in the chart, in written order. */
44
+ function marksOf(lines) {
45
+ return lines.flatMap((l) => l.kind === "bars"
46
+ ? l.cells.flatMap((c, cell) => c.kind === "direction" ? [{ line: l.line, cell, direction: c.direction }] : [])
47
+ : []);
48
+ }
49
+ /** What the jump needs and the chart lacks. */
50
+ function missingMarks(jump, plan, first) {
51
+ const toCoda = first.get("to coda");
52
+ const wants = [
53
+ [plan.to === "segno" && !inOrder(first.get("segno"), jump), "no Segno before it"],
54
+ [plan.al === "fine" && !first.has("fine"), "no Fine"],
55
+ [plan.al === "coda" && !toCoda, "no To Coda"],
56
+ [
57
+ plan.al === "coda" && !!toCoda && !inOrder(toCoda, first.get("coda")),
58
+ "no Coda after its To Coda",
59
+ ],
60
+ ];
61
+ const name = printDirection(jump.direction);
62
+ return wants.filter(([missing]) => missing).map(([, what]) => `${name} has ${what}`);
63
+ }
64
+ /** The marks no jump uses: each is an error. */
65
+ function unusedMarks(plan, first) {
66
+ const used = {
67
+ segno: plan?.to === "segno",
68
+ fine: plan?.al === "fine",
69
+ "to coda": plan?.al === "coda",
70
+ coda: plan?.al === "coda",
71
+ };
72
+ return [...first.values()].filter((m) => m.direction.kind !== "jump" && !used[m.direction.kind]);
73
+ }
74
+ /**
75
+ * Check a chart's directions (grammar 5.2) and say where its jump goes.
76
+ * A chart with a problem in its directions plays without the jump.
77
+ */
78
+ export function planJump(lines, error) {
79
+ const problems = [];
80
+ const first = new Map();
81
+ for (const m of marksOf(lines)) {
82
+ const kind = m.direction.kind;
83
+ if (!first.has(kind))
84
+ first.set(kind, m);
85
+ else if (kind === "jump")
86
+ problems.push([m, "a chart has one D.C. or D.S.; this is a second"]);
87
+ else
88
+ problems.push([m, `a second ${printDirection(m.direction)}; a chart has one`]);
89
+ }
90
+ const jump = first.get("jump");
91
+ const plan = jump?.direction.kind === "jump" ? jump.direction : null;
92
+ if (jump && plan)
93
+ problems.push(...missingMarks(jump, plan, first).map((m) => [jump, m]));
94
+ for (const m of unusedMarks(plan, first))
95
+ problems.push([m, `${printDirection(m.direction)}: no jump uses it`]);
96
+ for (const [m, message] of problems)
97
+ error(m.line, message, printDirection(m.direction));
98
+ return !problems.length && plan ? { to: plan.to, al: plan.al } : null;
99
+ }