barmark 0.10.0 → 0.11.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,32 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.11.0] - 2026-11-03
13
+
14
+ Endings and directions, issue #70 (grammar 5.1 and 5.2).
15
+
16
+ ### Added
17
+
18
+ - **First and second endings:** an ending is a bar line of its own,
19
+ `|1 G | G7 :|` then `|2 G | C |`, also `|1-3` and `|1,3`. Endings
20
+ follow a `|: … :|` repeat, and each pass plays its own ending. Bar
21
+ lines carry `ending`, the passes it plays on.
22
+ - **Directions:** `Segno`, `Coda`, `To Coda`, `Fine`, and one jump per
23
+ chart, `D.C.` or `D.S.`, alone or `al Fine` / `al Coda`. A direction
24
+ is a cell of its own (`kind: "direction"`), a place between bars, not
25
+ a bar. Play order follows the jump; after it, every repeat plays
26
+ once and takes its last ending.
27
+ - **Errors with line numbers** for endings that don't add up (a pass with
28
+ no ending or two, a last ending that goes back) and for directions
29
+ the jump can't use (no Segno before `D.S.`, `al Coda` with no
30
+ `To Coda`, a mark no jump uses, a second jump).
31
+ - **`printPasses` and `printDirection`**, the canonical spellings.
32
+
33
+ ### Changed
34
+
35
+ - **`|1` was reserved and is now an ending;** a chart that wrote it had an
36
+ error before, so no valid chart changes meaning.
37
+
12
38
  ## [0.10.0] - 2026-11-03
13
39
 
14
40
  Written bar numbers on played bars, issue #70. No chart changes meaning.
@@ -234,7 +260,8 @@ The first working release: the reference parser and printer for the
234
260
 
235
261
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
236
262
 
237
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.10.0...HEAD
263
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.11.0...HEAD
264
+ [0.11.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.10.0...barmark-v0.11.0
238
265
  [0.10.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.9.0...barmark-v0.10.0
239
266
  [0.9.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.8.0...barmark-v0.9.0
240
267
  [0.8.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.7.0...barmark-v0.8.0
@@ -1,7 +1,15 @@
1
- import type { ChartDiagnostic, Line, Repeat } from "./types.js";
1
+ import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot } from "./types.js";
2
2
  type BarsLine = Extract<Line, {
3
3
  kind: "bars";
4
4
  }>;
5
+ /** Whether a cell is a bar: `...` and a direction 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
+ } | {
11
+ kind: "simile";
12
+ };
5
13
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
6
14
  export declare function readRepeat(count: string, line: number, diagnostics: ChartDiagnostic[]): Repeat;
7
15
  /**
@@ -1,7 +1,10 @@
1
1
  import { parseNoteSet } from "../chords/noteSet.js";
2
2
  import { parseChord } from "../chords/parse.js";
3
+ import { isDirectionWord, readDirection } from "./direction.js";
3
4
  import { parseMeter } from "./directives.js";
4
5
  const FERMATA = new Set(["...", "…"]);
6
+ /** Whether a cell is a bar: `...` and a direction mark a place between bars. */
7
+ export const isBar = (c) => c.kind !== "fermata" && c.kind !== "direction";
5
8
  const SILENCE = new Set(["--", "–", "—"]);
6
9
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
7
10
  export function readRepeat(count, line, diagnostics) {
@@ -98,6 +101,62 @@ function tokens(text) {
98
101
  out.push(current);
99
102
  return out;
100
103
  }
104
+ /** `3` or `1-3` as its passes; null when it reads as none. */
105
+ function passRange(part) {
106
+ const m = /^([1-9]\d{0,2})(?:-([1-9]\d{0,2}))?$/.exec(part);
107
+ if (!m)
108
+ return null;
109
+ const from = Number(m[1]);
110
+ const to = Number(m[2] ?? from);
111
+ if (m[2] !== undefined && to <= from)
112
+ return null;
113
+ return Array.from({ length: to - from + 1 }, (_, i) => from + i);
114
+ }
115
+ /** `1`, `1-3` or `1,3`: the passes an ending plays on, in order; null when they read as none. */
116
+ function readPasses(text) {
117
+ const ranges = text.split(",").map(passRange);
118
+ const passes = ranges.flatMap((r) => r ?? []).sort((a, b) => a - b);
119
+ const repeated = new Set(passes).size !== passes.length;
120
+ return ranges.includes(null) || repeated ? null : passes;
121
+ }
122
+ const ENDING_FORM = "an ending is |1, |2, |1-3 or |1,3, then a space";
123
+ /** A leading ending mark: the line without it, its passes, and the mark if it doesn't read. */
124
+ function readEnding(body) {
125
+ const mark = /^\|(\d[\d,-]*)(?=\s)/.exec(body);
126
+ if (!mark)
127
+ return { body, ending: null, bad: null };
128
+ const ending = readPasses(mark[1] ?? "");
129
+ return { body: `|${body.slice(mark[0].length)}`, ending, bad: ending ? null : mark[0] };
130
+ }
131
+ /** An ending mark left in the line, and what to say about it. */
132
+ function strayEnding(body) {
133
+ const m = /\|\d+\S*/.exec(body);
134
+ if (!m)
135
+ return null;
136
+ return [m.index === 0 ? ENDING_FORM : "an ending starts its own bar line", m[0]];
137
+ }
138
+ /** Why a token can't share its cell: `%`, `...` and the words of a direction stand alone. */
139
+ function mustStandAlone(token) {
140
+ if (token === "%" || FERMATA.has(token))
141
+ return `${token} must be alone in a cell`;
142
+ if (isDirectionWord(token))
143
+ return `${token} is part of a direction, which must be alone in its cell`;
144
+ return null;
145
+ }
146
+ /** A cell that is a direction, or what is wrong with one; null when the cell isn't one. */
147
+ function directionCell(rest, meter) {
148
+ const named = readDirection(rest);
149
+ if (!named)
150
+ return null;
151
+ if ("direction" in named)
152
+ return meter
153
+ ? { problem: "a one-bar meter cannot go on a direction" }
154
+ : { cell: { kind: "direction", direction: named.direction } };
155
+ // Only words a chord never uses make a near miss: `| D C |` is two chords, not D.C.
156
+ if (!rest.includes(".") && !tokens(rest).some(isDirectionWord))
157
+ return null;
158
+ return { problem: `not a direction; write ${named.suggestion}`, suggestion: named.suggestion };
159
+ }
101
160
  /** The bars a bar line writes, read from its pipes alone (fermatas not counted), so a line dropped for an error still counts. */
102
161
  const barsWritten = (body) => body
103
162
  .split("|")
@@ -137,6 +196,11 @@ export function parseBarLine(text, line) {
137
196
  body = body.slice(0, lastPipe + 1) + tail.rest;
138
197
  repeat = readRepeat(tail.count, line, diagnostics);
139
198
  }
199
+ const leading = readEnding(body);
200
+ body = leading.body;
201
+ const ending = leading.ending;
202
+ if (leading.bad)
203
+ error(ENDING_FORM, leading.bad);
140
204
  const opens = body.startsWith("|:");
141
205
  if (opens)
142
206
  body = `|${body.slice(2)}`;
@@ -144,8 +208,9 @@ export function parseBarLine(text, line) {
144
208
  if (closes)
145
209
  body = `${body.slice(0, -2)}|`;
146
210
  const written = barsWritten(body);
147
- if (/\|\d/.test(body))
148
- error("endings are not supported in v0.1", /\|\d+/.exec(body)?.[0] ?? "|");
211
+ const stray = strayEnding(body);
212
+ if (stray)
213
+ error(...stray);
149
214
  if (body.includes(":|") || body.includes("|:"))
150
215
  error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
151
216
  // A misplaced mark makes the cells unreadable: report it once, not again as chords.
@@ -172,8 +237,9 @@ export function parseBarLine(text, line) {
172
237
  const misplaced = misplacedRepeat(token);
173
238
  if (misplaced)
174
239
  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);
240
+ const alone = mustStandAlone(token);
241
+ if (alone)
242
+ return error(alone, token);
177
243
  const r = token.startsWith("{") ? parseNoteSet(token) : parseChord(token);
178
244
  if (!r.ok)
179
245
  return error(r.error.message, token, r.error.suggestion);
@@ -202,6 +268,13 @@ export function parseBarLine(text, line) {
202
268
  error("a [n/d] meter must start its cell", rest);
203
269
  continue;
204
270
  }
271
+ const direction = directionCell(rest, meter);
272
+ if (direction && "cell" in direction)
273
+ cells.push(direction.cell);
274
+ else if (direction)
275
+ error(direction.problem, rest, direction.suggestion);
276
+ if (direction)
277
+ continue;
205
278
  const list = tokens(rest);
206
279
  if (list.length === 0) {
207
280
  error("a cell needs at least one slot", raw.trim());
@@ -244,7 +317,7 @@ export function parseBarLine(text, line) {
244
317
  }
245
318
  const failed = diagnostics.some((d) => d.severity === "error");
246
319
  return {
247
- bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat },
320
+ bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
248
321
  written,
249
322
  diagnostics,
250
323
  };
@@ -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
+ }
@@ -1,8 +1,32 @@
1
+ import { planJump } from "./direction.js";
1
2
  import { beatsOf } from "./directives.js";
3
+ import { pairRepeats } from "./repeats.js";
2
4
  /** Nested repeats multiply; expansion stops here rather than run away. */
3
5
  export const MAX_EXPANDED_BARS = 10_000;
4
6
  /** Repeats of bodies that play no bars (fermatas only) are bounded too. */
5
7
  const MAX_WORK = MAX_EXPANDED_BARS * 10;
8
+ /**
9
+ * How each mark moves play along. A mark the jump does not use is an error
10
+ * that drops the jump, so with a jump planned every mark here applies.
11
+ */
12
+ const NEXT = {
13
+ main: { jump: "jumped" },
14
+ "seek segno": { segno: "return" },
15
+ "seek coda": { coda: "return" },
16
+ return: { fine: "done", "to coda": "seek coda" },
17
+ };
18
+ /** The warning for a cell whose slots divide its beats unevenly (grammar 2.1). */
19
+ function uneven(slots, meter, line) {
20
+ const b = beatsOf(meter);
21
+ if (b % slots === 0 || slots % b === 0)
22
+ return null;
23
+ return {
24
+ line,
25
+ severity: "warning",
26
+ message: `${slots} slots divide ${b} beats unevenly`,
27
+ token: `${slots}`,
28
+ };
29
+ }
6
30
  const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
7
31
  const isWritten = (s) => s.lines.some((l) => l.kind === "bars" || l.kind === "invalid");
8
32
  /** Grammar §6: an empty section that matches nothing, and how to fix it. */
@@ -40,7 +64,16 @@ function removeLastBar(events) {
40
64
  */
41
65
  export function expand(lines) {
42
66
  const diagnostics = [];
43
- const error = (line, message, token) => diagnostics.push({ line, severity: "error", message, token });
67
+ // The return after a jump plays sections again: it reports only what the first pass did not.
68
+ const reported = new Set();
69
+ let again = false;
70
+ const error = (line, message, token) => {
71
+ const key = `${line}\u0000${message}`;
72
+ if (again && reported.has(key))
73
+ return;
74
+ reported.add(key);
75
+ diagnostics.push({ line, severity: "error", message, token });
76
+ };
44
77
  const sections = [{ heading: null, lines: [] }];
45
78
  for (const l of lines) {
46
79
  if (l.kind === "section")
@@ -61,6 +94,8 @@ export function expand(lines) {
61
94
  for (const c of l.cells) {
62
95
  if (c.kind === "fermata")
63
96
  cells.push({ kind: "fermata" });
97
+ else if (c.kind === "direction")
98
+ cells.push(c);
64
99
  else if (c.kind === "simile") {
65
100
  if (!previous)
66
101
  error(l.line, "% has no bar before it to repeat", "%");
@@ -83,55 +118,18 @@ export function expand(lines) {
83
118
  }
84
119
  resolved.set(l, cells);
85
120
  }
86
- // Pair |: and :| within each section.
87
- const itemsOf = new Map();
88
- for (const s of sections) {
89
- const items = [];
90
- let open = null;
91
- for (const l of s.lines) {
92
- const bars = l.kind === "bars" ? l : null;
93
- if (bars?.opens) {
94
- if (open)
95
- error(bars.line, "|: inside another |:", "|:");
96
- else
97
- open = { line: bars.line, entries: [] };
98
- }
99
- if (bars?.closes) {
100
- if (!open) {
101
- error(bars.line, ":| has no |: before it in this section", ":|");
102
- items.push({ kind: "line", line: bars, repeat: null });
103
- continue;
104
- }
105
- open.entries.push({ line: bars, repeat: null });
106
- items.push({
107
- kind: "bracket",
108
- line: open.line,
109
- entries: open.entries,
110
- repeat: bars.repeat ?? 2,
111
- });
112
- open = null;
113
- continue;
114
- }
115
- const entry = { line: l, repeat: bars?.repeat ?? null };
116
- if (open)
117
- open.entries.push(entry);
118
- else
119
- items.push({ kind: "line", ...entry });
120
- }
121
- if (open) {
122
- error(open.line, "|: is never closed in this section", "|:");
123
- items.push(...open.entries.map((e) => ({ kind: "line", ...e })));
124
- }
125
- itemsOf.set(s, items);
126
- }
127
- const state = {
121
+ // Pair |: and :| within each section, with any endings.
122
+ const itemsOf = new Map(sections.map((s) => [s, pairRepeats(s.lines, error)]));
123
+ const plan = planJump(lines, error);
124
+ const start = () => ({
128
125
  key: null,
129
126
  time: { n: 4, d: 4 },
130
127
  tempo: null,
131
128
  change: null,
132
129
  feel: "straight",
133
130
  swingPercent: undefined,
134
- };
131
+ });
132
+ const state = start();
135
133
  const warned = new Set();
136
134
  const warn = (line, message, token) => {
137
135
  if (warned.has(line))
@@ -180,48 +178,54 @@ export function expand(lines) {
180
178
  error(line, `expansion stopped at ${MAX_EXPANDED_BARS} bars`, "x");
181
179
  };
182
180
  let sectionName = null;
181
+ let phase = "main";
182
+ const stopped = () => capped || phase === "jumped" || phase === "done";
183
+ const jumped = () => phase === "jumped";
184
+ const seeking = () => phase === "seek segno" || phase === "seek coda";
185
+ /** The jump is taken once; after it, `To Coda` and `Fine` take effect. */
186
+ const direct = (d) => {
187
+ if (plan)
188
+ phase = NEXT[phase]?.[d.kind] ?? phase;
189
+ };
190
+ /** A bar as played now; its slot count is checked the first time a written bar plays. */
191
+ const barOf = (p, line) => {
192
+ const meter = p.meter ?? state.time;
193
+ if (p.own && !checked.has(p)) {
194
+ checked.add(p);
195
+ const warning = uneven(p.slots.length, meter, line);
196
+ if (warning)
197
+ diagnostics.push(warning);
198
+ }
199
+ const { key, tempo, change: tempoChange, feel, swingPercent } = state;
200
+ return {
201
+ index: 0,
202
+ written: p.written,
203
+ line,
204
+ section: sectionName,
205
+ meter,
206
+ key,
207
+ tempo,
208
+ tempoChange,
209
+ feel,
210
+ ...(swingPercent === undefined ? {} : { swingPercent }),
211
+ slots: p.slots,
212
+ };
213
+ };
183
214
  const emit = (p, line, out) => {
184
- if (capped)
215
+ if (stopped())
216
+ return;
217
+ if (p.kind === "direction")
218
+ return direct(p.direction);
219
+ if (seeking())
185
220
  return;
186
221
  if (++work > MAX_WORK)
187
222
  return stop(line);
188
- if (p.kind === "fermata") {
189
- out.push({ kind: "fermata", line });
190
- return;
191
- }
223
+ if (p.kind === "fermata")
224
+ return void out.push({ kind: "fermata", line });
192
225
  if (count >= MAX_EXPANDED_BARS)
193
226
  return stop(line);
194
227
  count++;
195
- const meter = p.meter ?? state.time;
196
- if (p.own && !checked.has(p)) {
197
- checked.add(p);
198
- const k = p.slots.length;
199
- const b = beatsOf(meter);
200
- if (b % k !== 0 && k % b !== 0)
201
- diagnostics.push({
202
- line,
203
- severity: "warning",
204
- message: `${k} slots divide ${b} beats unevenly`,
205
- token: `${k}`,
206
- });
207
- }
208
- const { key, tempo, change: tempoChange, feel, swingPercent } = state;
209
- out.push({
210
- kind: "bar",
211
- bar: {
212
- index: 0,
213
- written: p.written,
214
- line,
215
- section: sectionName,
216
- meter,
217
- key,
218
- tempo,
219
- tempoChange,
220
- feel,
221
- ...(swingPercent === undefined ? {} : { swingPercent }),
222
- slots: p.slots,
223
- },
224
- });
228
+ out.push({ kind: "bar", bar: barOf(p, line) });
225
229
  };
226
230
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
227
231
  const times = (repeat, line, out, body) => {
@@ -240,13 +244,17 @@ export function expand(lines) {
240
244
  out.push({ kind: "open", line, events: inner });
241
245
  return;
242
246
  }
243
- for (let i = 0; i < (repeat ?? 1) && !capped; i++) {
247
+ // After the jump every repeat plays once.
248
+ const passes = phase === "main" ? (repeat ?? 1) : 1;
249
+ for (let i = 0; i < passes && !stopped(); i++) {
244
250
  if (++work > MAX_WORK)
245
251
  return stop(line);
246
252
  body(out);
247
253
  }
248
254
  };
249
255
  const playLine = ({ line: l, repeat }, out) => {
256
+ if (stopped())
257
+ return;
250
258
  if (l.kind === "directive")
251
259
  apply(l.set, l.line);
252
260
  if (l.kind !== "bars")
@@ -260,6 +268,8 @@ export function expand(lines) {
260
268
  for (const it of items) {
261
269
  if (it.kind === "line")
262
270
  playLine(it, out);
271
+ else if (it.endings.length)
272
+ playEndings(it, out);
263
273
  else
264
274
  times(it.repeat, it.line, out, (into) => {
265
275
  for (const e of it.entries)
@@ -267,49 +277,87 @@ export function expand(lines) {
267
277
  });
268
278
  }
269
279
  };
280
+ /** Each pass plays the body, then its ending; after the jump, only the last pass. */
281
+ const playEndings = (it, out) => {
282
+ const highest = typeof it.repeat === "number" ? it.repeat : 1;
283
+ const first = phase === "main" ? 1 : highest;
284
+ for (let pass = first; pass <= highest && !stopped(); pass++) {
285
+ if (++work > MAX_WORK)
286
+ return stop(it.line);
287
+ for (const e of it.entries)
288
+ playLine(e, out);
289
+ const ending = it.endings.find((x) => x.passes.includes(pass));
290
+ if (ending)
291
+ playLine(ending.entry, out);
292
+ }
293
+ };
270
294
  const events = [];
271
295
  const occurrences = [];
272
296
  const definitions = new Map();
273
- for (const s of sections) {
274
- const h = s.heading;
275
- const items = itemsOf.get(s) ?? [];
276
- if (!h) {
277
- sectionName = null;
278
- playItems(items, events);
279
- continue;
280
- }
281
- sectionName = h.name;
282
- const out = [];
283
- const isDefinition = isWritten(s);
284
- let replayOf = null;
285
- if (isDefinition) {
286
- definitions.set(normalize(h.name), s);
287
- if (h.elided)
288
- error(h.line, "-> is only for a replay; leave the bar out instead", "->");
289
- times(h.repeat, h.line, out, (into) => playItems(items, into));
297
+ /** Headings already played, so a written section played again by the jump is a replay. */
298
+ const heard = new Set();
299
+ const playSections = () => {
300
+ for (const s of sections) {
301
+ if (stopped())
302
+ return;
303
+ playSection(s);
290
304
  }
291
- else {
292
- // A nameless heading is already an error; it has nothing to replay.
293
- if (!h.name)
294
- continue;
295
- const source = definitions.get(normalize(h.name));
296
- if (!source?.heading) {
297
- error(h.line, unmatchedReplay(h, sections), h.name);
298
- continue;
299
- }
300
- replayOf = source.heading.line;
301
- const body = itemsOf.get(source) ?? [];
302
- times(h.repeat, h.line, out, (into) => playItems(body, into));
305
+ };
306
+ /** A written section's bars into `out`. */
307
+ const playWritten = (s, h, out) => {
308
+ definitions.set(normalize(h.name), s);
309
+ if (h.elided)
310
+ error(h.line, "-> is only for a replay; leave the bar out instead", "->");
311
+ times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(s) ?? [], into));
312
+ return { replayOf: null, elided: false };
313
+ };
314
+ /** A replay's bars into `out`, then its own lines; null when it replays nothing. */
315
+ const playReplay = (s, h, out) => {
316
+ // A nameless heading is already an error; it has nothing to replay.
317
+ if (!h.name)
318
+ return null;
319
+ const source = definitions.get(normalize(h.name));
320
+ if (!source?.heading) {
321
+ error(h.line, unmatchedReplay(h, sections), h.name);
322
+ return null;
303
323
  }
304
- const elided = !isDefinition && h.elided && removeLastBar(out);
324
+ times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
325
+ const elided = h.elided && removeLastBar(out);
305
326
  // A replay heading stands for its bars: its own lines (directives) come after them.
306
- if (!isDefinition)
307
- playItems(items, out);
308
- events.push(...out);
327
+ playItems(itemsOf.get(s) ?? [], out);
328
+ return { replayOf: source.heading.line, elided };
329
+ };
330
+ /** A section occurrence; one the jump plays again is a replay of itself. */
331
+ const record = (h, out, replayOf, elided) => {
332
+ // Sections the return passes over while seeking play nothing and are not occurrences.
333
+ if (phase !== "main" && phase !== "jumped" && !out.length)
334
+ return;
335
+ const of = replayOf ?? (heard.has(h.line) ? h.line : null);
336
+ heard.add(h.line);
309
337
  occurrences.push([
310
- { name: h.name, line: h.line, replayOf, firstBar: null, lastBar: null, elided },
338
+ { name: h.name, line: h.line, replayOf: of, firstBar: null, lastBar: null, elided },
311
339
  out,
312
340
  ]);
341
+ };
342
+ const playSection = (s) => {
343
+ const h = s.heading;
344
+ sectionName = h?.name ?? null;
345
+ if (!h)
346
+ return playItems(itemsOf.get(s) ?? [], events);
347
+ const out = [];
348
+ const played = isWritten(s) ? playWritten(s, h, out) : playReplay(s, h, out);
349
+ if (!played)
350
+ return;
351
+ events.push(...out);
352
+ record(h, out, played.replayOf, played.elided);
353
+ };
354
+ playSections();
355
+ if (jumped() && plan) {
356
+ // The return reads the chart again from the top, so the directives in force are the written ones.
357
+ Object.assign(state, start());
358
+ again = true;
359
+ phase = plan.to === "start" ? "return" : "seek segno";
360
+ playSections();
313
361
  }
314
362
  flattenBars(events).forEach((b, i) => {
315
363
  b.index = i + 1;
@@ -1,9 +1,10 @@
1
1
  export { parseBarLine } from "./barLine.js";
2
2
  export { degreeOf } from "./degree.js";
3
+ export { printDirection } from "./direction.js";
3
4
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
4
5
  export { readDocument } from "./document.js";
5
6
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
6
7
  export { parseChart } from "./parse.js";
7
- export { printCell, printChart, printLine, printParsed, printSlot, reduceSlots } from "./print.js";
8
+ export { printCell, printChart, printLine, printParsed, printPasses, printSlot, reduceSlots, } from "./print.js";
8
9
  export { type TransposeBy, transposeChart } from "./transpose.js";
9
10
  export type * from "./types.js";
@@ -1,8 +1,9 @@
1
1
  export { parseBarLine } from "./barLine.js";
2
2
  export { degreeOf } from "./degree.js";
3
+ export { printDirection } from "./direction.js";
3
4
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
4
5
  export { readDocument } from "./document.js";
5
6
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
6
7
  export { parseChart } from "./parse.js";
7
- export { printCell, printChart, printLine, printParsed, printSlot, reduceSlots } from "./print.js";
8
+ export { printCell, printChart, printLine, printParsed, printPasses, printSlot, reduceSlots, } from "./print.js";
8
9
  export { transposeChart } from "./transpose.js";
@@ -12,6 +12,8 @@ export declare function reduceSlots(slots: Slot[], beats?: number): Slot[];
12
12
  export declare function printSlot(s: Slot): string;
13
13
  /** A cell in canonical form: `%`, `...`, or an optional `[n/d]` and the fewest slots. */
14
14
  export declare function printCell(c: Cell, beats?: number): string;
15
+ /** An ending's passes as printed after its `|`: in order, runs of three or more as a range (`1-3`, `1,2`, `1,3-5`). */
16
+ export declare function printPasses(passes: number[]): string;
15
17
  /**
16
18
  * One parsed line in canonical form. Text and invalid lines print as stored.
17
19
  * `beats` gives each cell's beat count where known, so reduction adds no warning.
@@ -1,3 +1,5 @@
1
+ import { isBar } from "./barLine.js";
2
+ import { printDirection } from "./direction.js";
1
3
  import { beatsOf } from "./directives.js";
2
4
  import { parseChart } from "./parse.js";
3
5
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
@@ -52,9 +54,23 @@ export function printCell(c, beats) {
52
54
  return "%";
53
55
  if (c.kind === "fermata")
54
56
  return "...";
57
+ if (c.kind === "direction")
58
+ return printDirection(c.direction);
55
59
  const meter = c.meter ? `[${c.meter.n}/${c.meter.d}] ` : "";
56
60
  return meter + reduceSlots(c.slots, beats).map(printSlot).join(" ");
57
61
  }
62
+ /** An ending's passes as printed after its `|`: in order, runs of three or more as a range (`1-3`, `1,2`, `1,3-5`). */
63
+ export function printPasses(passes) {
64
+ const runs = [];
65
+ for (const p of passes) {
66
+ const run = runs.at(-1);
67
+ if (run && run.at(-1) === p - 1)
68
+ run.push(p);
69
+ else
70
+ runs.push([p]);
71
+ }
72
+ return runs.flatMap((r) => (r.length >= 3 ? [`${r[0]}-${r.at(-1)}`] : r.map(String))).join(",");
73
+ }
58
74
  const printRepeat = (r) => (r === null ? "" : r === "open" ? " x ..." : ` x${r}`);
59
75
  function printKey(k) {
60
76
  if (k.mode === "major")
@@ -95,7 +111,7 @@ export function printLine(l, beats = []) {
95
111
  case "directive":
96
112
  return printDirectives(l.set);
97
113
  case "bars":
98
- return `${l.opens ? "|:" : "|"} ${l.cells.map((c, i) => printCell(c, beats[i])).join(" | ")} ${l.closes ? ":|" : "|"}${printRepeat(l.repeat)}`;
114
+ return `${l.opens ? "|:" : l.ending ? `|${printPasses(l.ending)}` : "|"} ${l.cells.map((c, i) => printCell(c, beats[i])).join(" | ")} ${l.closes ? ":|" : "|"}${printRepeat(l.repeat)}`;
99
115
  default:
100
116
  return l.text;
101
117
  }
@@ -120,7 +136,7 @@ export function printParsed(text, parsed, edit = (l) => l) {
120
136
  for (const b of parsed.bars) {
121
137
  const l = byLine.get(b.line);
122
138
  const meters = firstPlay.get(b.line) ?? [];
123
- const cells = l?.kind === "bars" ? l.cells.filter((c) => c.kind !== "fermata").length : 0;
139
+ const cells = l?.kind === "bars" ? l.cells.filter(isBar).length : 0;
124
140
  if (meters.length < cells)
125
141
  firstPlay.set(b.line, [...meters, beatsOf(b.meter)]);
126
142
  }
@@ -129,7 +145,7 @@ export function printParsed(text, parsed, edit = (l) => l) {
129
145
  return [];
130
146
  const meters = firstPlay.get(l.line) ?? [];
131
147
  let next = 0;
132
- return l.cells.map((c) => (c.kind === "fermata" ? undefined : meters[next++]));
148
+ return l.cells.map((c) => (isBar(c) ? meters[next++] : undefined));
133
149
  };
134
150
  const out = [];
135
151
  let lastWasHeading = false;
@@ -0,0 +1,28 @@
1
+ import type { Line, Repeat } from "./types.js";
2
+ type Report = (line: number, message: string, token: string) => void;
3
+ export type Entry = {
4
+ line: Line;
5
+ repeat: Repeat;
6
+ };
7
+ /** One ending: the passes it plays on and its bar line. */
8
+ export type Ending = {
9
+ passes: number[];
10
+ entry: Entry;
11
+ };
12
+ /** A line, or a `|: … :|` repeat; one with endings plays `repeat` passes, each taking its ending. */
13
+ export type Item = ({
14
+ kind: "line";
15
+ } & Entry) | {
16
+ kind: "bracket";
17
+ line: number;
18
+ entries: Entry[];
19
+ repeat: Repeat;
20
+ endings: Ending[];
21
+ };
22
+ /**
23
+ * Pair `|:` and `:|` within one section's lines, with the endings that
24
+ * follow a repeat (grammar 5.1). Problems are reported, and what cannot
25
+ * pair plays once.
26
+ */
27
+ export declare function pairRepeats(lines: Line[], error: Report): Item[];
28
+ export {};
@@ -0,0 +1,122 @@
1
+ const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
2
+ const asLine = (line) => ({ kind: "line", line, repeat: null });
3
+ const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
4
+ /** Every pass from 1 to the highest has exactly one ending, and the highest is at least 2. */
5
+ function passProblems(endings, last) {
6
+ const highest = highestPass(endings);
7
+ if (highest < 2)
8
+ return [[last, "a repeat with endings plays at least two passes"]];
9
+ const problems = [];
10
+ for (let p = 1; p < highest + 1; p++) {
11
+ const n = endings.filter((b) => b.ending?.includes(p)).length;
12
+ if (n !== 1)
13
+ problems.push([last, `pass ${p} has ${n ? "two endings" : "no ending"}`]);
14
+ }
15
+ if (!last.ending?.includes(highest))
16
+ problems.push([last, `the last ending must be the one for pass ${highest}`]);
17
+ return problems;
18
+ }
19
+ /** Every ending but the last goes back with `:|`; the last plays on. */
20
+ function closeProblems(endings, last) {
21
+ return endings.flatMap((b) => {
22
+ 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
+ });
26
+ }
27
+ /** A repeat with its endings, or, if they have problems, each line played once. */
28
+ function closeEndings(e, error) {
29
+ const last = e.endings.at(-1);
30
+ if (!last)
31
+ return [];
32
+ const problems = [...passProblems(e.endings, last), ...closeProblems(e.endings, last)];
33
+ for (const [b, message] of problems)
34
+ error(b.line, message, passesToken(b));
35
+ const between = e.between.map((x) => asLine(x.line));
36
+ 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
+ }));
42
+ const repeat = highestPass(e.endings);
43
+ return [{ kind: "bracket", line: e.line, entries: e.entries, repeat, endings }, ...between];
44
+ }
45
+ /** An ending line starts the endings of the open repeat, or continues them. */
46
+ function takeEnding(st, bars, error) {
47
+ if (bars.repeat !== null)
48
+ error(bars.line, "x N on an ending: the endings give the count", passesToken(bars));
49
+ if (st.open)
50
+ st.endings = { ...st.open, endings: [bars], between: [] };
51
+ else if (st.endings)
52
+ st.endings.endings.push(bars);
53
+ else {
54
+ error(bars.line, "an ending follows the bars of a |: … :| repeat", passesToken(bars));
55
+ st.items.push(asLine(bars));
56
+ }
57
+ st.open = null;
58
+ }
59
+ /** `|:` opens a repeat, unless one is open already. */
60
+ function openRepeat(st, bars, error) {
61
+ if (st.open)
62
+ error(bars.line, "|: inside another |:", "|:");
63
+ else
64
+ st.open = { line: bars.line, entries: [] };
65
+ }
66
+ /** `:|` closes the open repeat; with none open it is an error, and its line plays once. */
67
+ function closeRepeat(st, bars, error) {
68
+ if (!st.open) {
69
+ error(bars.line, ":| has no |: before it in this section", ":|");
70
+ st.items.push(asLine(bars));
71
+ return;
72
+ }
73
+ const { line, entries } = st.open;
74
+ entries.push({ line: bars, repeat: null });
75
+ st.items.push({ kind: "bracket", line, entries, repeat: bars.repeat ?? 2, endings: [] });
76
+ st.open = null;
77
+ }
78
+ /** Any other line: it opens or closes a repeat, or belongs to the open one, or stands alone. */
79
+ function takeLine(st, l, error) {
80
+ if (l.kind === "bars" && l.opens)
81
+ openRepeat(st, l, error);
82
+ if (l.kind === "bars" && l.closes)
83
+ closeRepeat(st, l, error);
84
+ else
85
+ addEntry(st, { line: l, repeat: l.kind === "bars" ? l.repeat : null });
86
+ }
87
+ /** A line inside the open repeat belongs to it; any other stands alone. */
88
+ function addEntry(st, entry) {
89
+ if (st.open)
90
+ st.open.entries.push(entry);
91
+ else
92
+ st.items.push({ kind: "line", ...entry });
93
+ }
94
+ /**
95
+ * Pair `|:` and `:|` within one section's lines, with the endings that
96
+ * follow a repeat (grammar 5.1). Problems are reported, and what cannot
97
+ * pair plays once.
98
+ */
99
+ export function pairRepeats(lines, error) {
100
+ const st = { items: [], open: null, endings: null };
101
+ const finish = () => {
102
+ if (st.endings)
103
+ st.items.push(...closeEndings(st.endings, error));
104
+ st.endings = null;
105
+ };
106
+ for (const l of lines) {
107
+ if (l.kind === "bars" && l.ending)
108
+ takeEnding(st, l, error);
109
+ else if (st.endings && l.kind === "text")
110
+ st.endings.between.push({ line: l, repeat: null });
111
+ else {
112
+ finish();
113
+ takeLine(st, l, error);
114
+ }
115
+ }
116
+ finish();
117
+ if (st.open) {
118
+ error(st.open.line, "|: is never closed in this section", "|:");
119
+ st.items.push(...st.open.entries.map((e) => ({ kind: "line", ...e })));
120
+ }
121
+ return st.items;
122
+ }
@@ -56,7 +56,25 @@ export type Slot = SimpleSlot | {
56
56
  kind: "group";
57
57
  members: SimpleSlot[];
58
58
  };
59
- /** `meter` is a one-bar `[n/d]` override. */
59
+ /**
60
+ * A mark between bars (grammar 5.2). A jump goes back to the chart's first
61
+ * bar (`D.C.`) or to the segno (`D.S.`), then plays to the end, to `Fine`
62
+ * (`al Fine`) or to `To Coda` (`al Coda`).
63
+ */
64
+ export type Direction = {
65
+ kind: "segno";
66
+ } | {
67
+ kind: "coda";
68
+ } | {
69
+ kind: "to coda";
70
+ } | {
71
+ kind: "fine";
72
+ } | {
73
+ kind: "jump";
74
+ to: "start" | "segno";
75
+ al: "fine" | "coda" | null;
76
+ };
77
+ /** `meter` is a one-bar `[n/d]` override. `...` and a direction are not bars. */
60
78
  export type Cell = {
61
79
  kind: "slots";
62
80
  meter: Meter | null;
@@ -65,6 +83,9 @@ export type Cell = {
65
83
  kind: "simile";
66
84
  } | {
67
85
  kind: "fermata";
86
+ } | {
87
+ kind: "direction";
88
+ direction: Direction;
68
89
  };
69
90
  export type Repeat = number | "open" | null;
70
91
  export type Line = {
@@ -88,6 +109,8 @@ export type Line = {
88
109
  closes: boolean;
89
110
  cells: Cell[];
90
111
  repeat: Repeat;
112
+ /** The passes an ending plays on (grammar 5.1), in order; null for any other bar line. */
113
+ ending: number[] | null;
91
114
  } | {
92
115
  kind: "text";
93
116
  line: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.10.0",
3
+ "version": "0.11.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": {