barmark 0.21.0 → 0.22.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,110 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.22.0] - 2026-11-09
13
+
14
+ A grammar change: a chart's pickup is bar 0 (2.4), which now defines a
15
+ pickup. Charts without a pickup read and number as before. Implements the
16
+ [grammar v0.1 draft](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md).
17
+
18
+ ### Added
19
+
20
+ - **`ChartParse.pickup`**: true when the chart's first written bar is a
21
+ pickup (grammar 2.4: in a one-bar meter shorter, by value, than the
22
+ meter in force at the next written bar, and that bar not short itself).
23
+ **`opensWithPickup(bars)`** gives the same answer from played bars
24
+ alone. The grammar now defines a pickup.
25
+
26
+ ### Changed
27
+
28
+ - **A pickup is bar 0** (grammar 2.4): in a chart that opens with one,
29
+ every played bar's `written` is one less than before, so bar 1 is the
30
+ first full bar, as notation and the MusicXML export number it; a repeat,
31
+ replay or D.C. that plays the pickup again shows 0 too. Charts without
32
+ a pickup are numbered as before. `index`, the play position, does not
33
+ change, so times keyed by it stay valid.
34
+
35
+ - **A line's passes that sing nothing are one warning.** "pass 3 of this
36
+ repeat sings nothing: its bars have verses 1 and 2" stays as it was for
37
+ one pass; several are now listed together, a run of three or more as a
38
+ range ("passes 1 and 3–9 of this repeat sing nothing: …"), and a list
39
+ past five items shows four and counts the rest ("verses 1, 2, 3, 4 and
40
+ 2496 more"). 2,500 verses over a bar played 10,000 times gave 7,500
41
+ warnings of about 14 KB each (105 million characters, which the site
42
+ rendered as one list); now one of 92 characters.
43
+
44
+ - **The npm homepage is https://www.barmark.dev**, not the package's
45
+ folder on GitHub.
46
+
47
+ ### Fixed
48
+
49
+ - **A bar played many times no longer costs its size on every play.** A
50
+ shared chart of one bar with thousands of lyric syllables, notes or
51
+ slots, repeated thousands of times, made the parse copy every syllable
52
+ for every play (lyrics) and walk every slot of every play twice (the
53
+ pedal warnings, through a matrix of every slot of every played bar):
54
+ seconds to minutes and over a gigabyte from a few kilobytes. A played
55
+ bar now shares its written bar's data: two plays of one bar return the
56
+ same `slots`, `words` and `lyrics[].syllables` arrays (and the same
57
+ `PlayedLyrics` object), which a caller must not mutate; each written
58
+ bar's syllables, pushes and pedal effect are read once per meter it
59
+ plays in. The parse costs the written chart plus the played bars, never
60
+ their product. The parse's data is otherwise unchanged; `pedalStates`
61
+ still builds its matrix for callers that want it, but `parseChart`
62
+ doesn't call it.
63
+ - **A chart of many parts parses in time near linear in its size, not
64
+ cubic.** Each part's projection scanned the whole system for its own
65
+ line at every line it projected, and rebuilt the systems by copying;
66
+ choosing a system's reference line compared every line with every
67
+ other; reading a labelled line re-listed the declared parts; finding
68
+ who sings read every bar line once per part, and gathered the lyric
69
+ rows by copying their list for each row; folding a bar looked for each
70
+ part's streams among all of them. 600 one-bar parts in one system
71
+ (19 KB) took about 9 s; at 50 KB, 1,500 such parts took minutes (now
72
+ 0.9 s), 1,383 parts under 1,383 verses 18 s (now 1.3 s). And each part
73
+ read every line of the chart although it may play only its share of
74
+ the bars: 3,227 parts resting through 2,000 systems one part writes
75
+ took 19 s, 2,113 parts under 6,339 tutti lines 27 s (now 1.1 s each).
76
+ A part of a chart of several now reads at most ten times its share of
77
+ the bars in lines; one that stops there says so ("expansion stopped
78
+ after 0 bars: each of 1000 parts reads at most 100 lines"). Real charts
79
+ read every line: four parts may each read 25,000.
80
+ A third review, and an audit of every loop over parts, voices, lines,
81
+ systems, rows and played bars, found more of the same: each part's
82
+ voice was looked for among every voice and every stream (1,979 parts
83
+ each singing, 50 KB: 59 s, now 0.3 s); a part's own line was looked up
84
+ again at every line of its system, and every part walked every line of
85
+ the chart (800 parts of four lines: 3.3 s, now 0.7 s; 777 parts of two
86
+ lines in two systems: 1.9 s, now 0.6 s), and the parts' score order
87
+ read every system once per part; a lyric row under a replay heading
88
+ was copied onto every part's line of the replayed system (1,354 parts
89
+ and 1,354 replays, each with its own row: 3.8 s, now 0.3 s), and so was
90
+ each row's list of covered lines. Printing a 10,000-bar line counted
91
+ its bars again for every bar (2.2 s, now 0.5 s). A test now parses each
92
+ of these shapes at eight times the parts and fails if it takes twenty
93
+ times as long.
94
+ - **The verses a bar sings count toward the expansion's budget.** Outside
95
+ a repeat a bar sings every verse written over it, so 1,560 verses under
96
+ one bar replayed 5,000 times (55 KB) made 7.8 million verse references
97
+ (1.3 s, 61 MB). Each verse a written bar sings when it plays again now
98
+ counts as work (its first play's are as many as are written), and a
99
+ chart past the budget stops with an error that says so ("expansion
100
+ stopped after 64 bars: the bars played again sing too many verses
101
+ (98,280)"; both numbers count only the bars output, so a bar a
102
+ replay's `->` cuts is not counted, and a bar the budget stops is
103
+ neither sung nor checked): now 0.1 s and 2 MB. Once play stops at any
104
+ limit, the stop is the only report of what it cut short: no "the parts
105
+ fall out of step" for a part that stopped early, and no "verse N is
106
+ never sung" for verses the stop left unsung: a row play never reached,
107
+ or reached in a repeat with passes enough for its verse. A verse its
108
+ repeat can never reach is still reported (`lyrics 3:` under `x2`), stop
109
+ or not. A part whose play ended at `Fine`, after the jump, reports no
110
+ stop for the lines past its share, which it would never have played. Repeats that play too much with no
111
+ bars to count (fermatas) now say "expansion stopped after N bars: its
112
+ repeats play too many times", not the bar cap's "expansion stopped at
113
+ 10000 bars", which is kept for the bar cap itself. Real charts use a tiny share of it: the examples
114
+ and fixtures at most 153 of 100,000.
115
+
12
116
  ## [0.21.0] - 2026-11-08
13
117
 
14
118
  ### Added
@@ -656,7 +760,8 @@ The first working release: the reference parser and printer for the
656
760
 
657
761
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
658
762
 
659
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.21.0...HEAD
763
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.22.0...HEAD
764
+ [0.22.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.21.0...barmark-v0.22.0
660
765
  [0.21.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.20.0...barmark-v0.21.0
661
766
  [0.20.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.1...barmark-v0.20.0
662
767
  [0.19.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.0...barmark-v0.19.1
package/README.md CHANGED
@@ -58,6 +58,7 @@ chart.title; // "Example Song"
58
58
  chart.parts; // [{ label: "Gtr", name: "Electric Guitar 1" }] from part: Gtr = Electric Guitar 1, in score order
59
59
  chart.credits; // { composer: ["Kevin Peckham"], lyricist: [], arranger: [], copyright: [] } from composer: Kevin Peckham
60
60
  chart.bars; // every bar in play order: its number as written, slots, section, key, meter (and in a one-bar meter the time: meter, whose beat tempo counts), tempo, feel (and swingPercent)
61
+ chart.pickup; // true when the first written bar is a pickup (time: 4/4 then | [1/4] G | C |): it is bar 0
61
62
  chart.sections; // each section as played, with its first and last bar
62
63
  chart.diagnostics; // errors and warnings, each with a line number
63
64
 
@@ -195,9 +196,11 @@ an object. It has two kinds of field:
195
196
  - `events` is play order with fermatas and an open repeat kept as
196
197
  events.
197
198
  - `bars` is the same flattened to one `PlayedBar` per measure played,
198
- repeats, endings, jumps and replays spelled out. A bar's `index` counts
199
- in play order; `written` is the number a band reads on the page, the
200
- same on every pass. Each bar carries its slots, section, key, meter,
199
+ repeats, endings, jumps and replays spelled out. A bar's `index` is
200
+ its position in play order, not a bar number; `written` is the number
201
+ a band reads on the page, the same on every pass. A pickup (grammar
202
+ 2.4: a short first bar before a full one) is bar 0, and `pickup` says
203
+ the chart has one; otherwise bars count from 1. Each bar carries its slots, section, key, meter,
201
204
  tempo, feel and, when sung, each verse's syllables (`lyrics`).
202
205
  - `sections` is each section as played, with its first and last bar and
203
206
  `form` (which distinct section it is; replays share their section's
@@ -220,7 +223,8 @@ package's minor versions: 0.17.0, for example, added the `break` and
220
223
  diagnostics with `severity: "error"`; store `printChart(text)` to keep
221
224
  one spelling of each chart.
222
225
  - **Times in a recording** belong beside the chart, not in it: key them
223
- by `PlayedBar.index`, which names the same bar however the chart is
226
+ by `PlayedBar.index`, the play position (not the bar number, which
227
+ is `written`), which names the same bar however the chart is
224
228
  reformatted or its repeats are spelled (`|: :|` or `x2`), until the
225
229
  music itself changes. An open repeat (`x ...`) plays its bars once in
226
230
  `bars`, so its later passes have no index of their own.
@@ -24,6 +24,8 @@ function checkParts(lines, diagnostics) {
24
24
  return declared.map(partOf);
25
25
  const seen = new Map();
26
26
  const parts = [];
27
+ // Where each declaration is, found once: finding it again for every bad one costs the lines times the bad ones.
28
+ let at;
27
29
  for (const l of declared) {
28
30
  const problem = partProblem(l, seen);
29
31
  if (!problem) {
@@ -32,7 +34,10 @@ function checkParts(lines, diagnostics) {
32
34
  }
33
35
  const text = l.label ? `part: ${l.label} = ${l.name}` : `part: ${l.name}`;
34
36
  diagnostics.push({ line: l.line, severity: "error", token: text, ...problem });
35
- lines[lines.indexOf(l)] = { kind: "text", line: l.line, text };
37
+ at ??= new Map(lines.map((m, i) => [m, i]));
38
+ const i = at.get(l);
39
+ if (i !== undefined)
40
+ lines[i] = { kind: "text", line: l.line, text };
36
41
  }
37
42
  return parts;
38
43
  }
@@ -94,7 +99,7 @@ function readHeading(text, line, diagnostics) {
94
99
  }
95
100
  /** A declared label written before a bar line, exactly, or a part's label, a dot and a line's name (grammar 7.6). */
96
101
  function findLabel(word, declared) {
97
- const match = (w) => declared.find((p) => p.label?.toLowerCase() === w.toLowerCase())?.label;
102
+ const match = (w) => declared.get(w.toLowerCase());
98
103
  const exact = match(word);
99
104
  if (exact)
100
105
  return { part: exact };
@@ -234,6 +239,9 @@ export function readDocument(text) {
234
239
  const lines = [];
235
240
  const diagnostics = [];
236
241
  let title = null;
242
+ /** The parts declared so far, by lowercased label (the first of a label), and whether a bar line has been read. */
243
+ const labels = new Map();
244
+ let barred = false;
237
245
  /** The line kept as text, with why it isn't what it looks like. */
238
246
  const asText = (t, line, severity, message) => {
239
247
  diagnostics.push({ line, severity, message, token: t });
@@ -249,8 +257,11 @@ export function readDocument(text) {
249
257
  const partLine = (read, t, line) => {
250
258
  if (typeof read === "string")
251
259
  return asText(t, line, "error", read);
252
- if (lines.some((l) => l.kind === "bars" || l.kind === "invalid"))
260
+ if (barred)
253
261
  return asText(t, line, "error", "part: names the whole chart; put it before the first bar");
262
+ const label = read.label?.toLowerCase();
263
+ if (label !== undefined && !labels.has(label))
264
+ labels.set(label, read.label ?? "");
254
265
  return { kind: "part", line, ...read };
255
266
  };
256
267
  const otherLine = (t, line) => {
@@ -275,7 +286,6 @@ export function readDocument(text) {
275
286
  diagnostics.push(...r.diagnostics);
276
287
  return r.bars ?? { kind: "invalid", line, text: t, written: r.written };
277
288
  };
278
- const declaredParts = () => lines.filter((l) => l.kind === "part");
279
289
  /** A labelled line that can't be read: no space before its pipe, or a bad line name. */
280
290
  const badLabel = (t, line, word, rest, owner) => {
281
291
  const space = t.length > word.length + rest.length;
@@ -291,7 +301,7 @@ export function readDocument(text) {
291
301
  /** A declared part's bar line, or one of its lines (`Pno.RH`, grammar 7.6). */
292
302
  const labelledLine = (t, line) => {
293
303
  const split = splitLabel(t);
294
- const owner = split && findLabel(split.word, declaredParts());
304
+ const owner = split && findLabel(split.word, labels);
295
305
  if (!split || !owner)
296
306
  return null;
297
307
  const { word, space, rest } = split;
@@ -340,8 +350,12 @@ export function readDocument(text) {
340
350
  .split(/\r?\n/)
341
351
  .forEach((raw, i) => {
342
352
  const t = raw.trim();
343
- if (t && !t.startsWith("```"))
344
- lines.push(classify(t, i + 1));
353
+ if (!t || t.startsWith("```"))
354
+ return;
355
+ const l = classify(t, i + 1);
356
+ if (l.kind === "bars" || l.kind === "invalid")
357
+ barred = true;
358
+ lines.push(l);
345
359
  });
346
360
  const empty = noBarLines(lines);
347
361
  if (empty)
@@ -3,23 +3,40 @@ import type { ChartDiagnostic, ChartEvent, Line, PlayedBar, SectionOccurrence }
3
3
  * Where a played bar comes from, for its words (grammar 7.7): its bar
4
4
  * line, its place among that line's bars (from 0), the pass of the repeat
5
5
  * it plays in (null outside one, and in an open repeat, whose passes are
6
- * unknown), and the line of the replay heading it plays under, if any.
6
+ * unknown) and how many passes that repeat plays here, and the line of
7
+ * the replay heading it plays under, if any.
7
8
  */
8
9
  export type BarSource = {
9
10
  line: number;
10
11
  bar: number;
11
12
  pass: number | null;
13
+ passes: number | null;
12
14
  replay: number | null;
13
15
  };
14
- /** The words a played bar sings, given where it comes from; undefined when none. */
15
- export type Sing = (bar: PlayedBar, from: BarSource) => PlayedBar["lyrics"];
16
+ /**
17
+ * The words a played bar sings, given where it comes from; undefined when
18
+ * none. `verses` says how many it would sing, with no other effect, so the
19
+ * budget is checked before a bar is sung.
20
+ */
21
+ export type Sing = {
22
+ (bar: PlayedBar, from: BarSource): PlayedBar["lyrics"];
23
+ verses(bar: PlayedBar, from: BarSource): number;
24
+ };
16
25
  /** Nested repeats multiply; expansion stops here rather than run away. */
17
26
  export declare const MAX_EXPANDED_BARS = 10000;
27
+ /**
28
+ * The work one of `share` parts may do: ten times its bars. A part of a
29
+ * chart of several also reads at most this many lines, so the parts
30
+ * times the lines never multiply.
31
+ */
32
+ export declare const workFor: (share: number) => number;
18
33
  /** Every played bar in order, with an open repeat's pass included once. */
19
34
  export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
20
35
  /**
21
36
  * Turn the written chart into the bars in play order: sections and their
22
- * replays, repeats, directive changes, `%` and elision.
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).
23
40
  */
24
41
  /**
25
42
  * `label` names the part a projected chart is (grammar 7.4), for its
@@ -33,4 +50,6 @@ sing?: Sing): {
33
50
  events: ChartEvent[];
34
51
  sections: SectionOccurrence[];
35
52
  diagnostics: ChartDiagnostic[];
53
+ /** Whether play stopped at a limit: what follows from that alone goes unreported. */
54
+ stopped: boolean;
36
55
  };
@@ -2,9 +2,26 @@ import { planJump } from "./direction.js";
2
2
  import { beatsOf } from "./directives.js";
3
3
  import { pedalWarnings } from "./pedal.js";
4
4
  import { pairRepeats } from "./repeats.js";
5
- import { slotTimes } from "./shares.js";
5
+ import { perWritten, slotTimes } from "./shares.js";
6
6
  /** Nested repeats multiply; expansion stops here rather than run away. */
7
7
  export const MAX_EXPANDED_BARS = 10_000;
8
+ /** The bars one of `share` parts may play: its share of the cap. */
9
+ const barsFor = (share) => Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
10
+ /**
11
+ * The work one of `share` parts may do: ten times its bars. A part of a
12
+ * chart of several also reads at most this many lines, so the parts
13
+ * times the lines never multiply.
14
+ */
15
+ export const workFor = (share) => barsFor(share) * 10;
16
+ /**
17
+ * The lines one of several parts reads: its share of the work, since the
18
+ * parts times the lines would otherwise multiply; and the first it
19
+ * doesn't read, if any. A chart of one part reads every line.
20
+ */
21
+ function shareOf(lines, share, most) {
22
+ const unread = share > 1 ? lines[most] : undefined;
23
+ return unread ? { readable: lines.slice(0, most), unread } : { readable: lines };
24
+ }
8
25
  /** A slot without its syllable: `%` copies a bar's notes, not its words (grammar 4.3). */
9
26
  const unsungSimple = (s) => {
10
27
  if (s.kind !== "chord" || !s.syllable)
@@ -45,6 +62,21 @@ function pushProblem(push, before) {
45
62
  ? `${push === "eighth" ? "an eighth" : "a sixteenth"} push is longer than the slot before it`
46
63
  : null;
47
64
  }
65
+ function pushesIn(slots, meter) {
66
+ const timed = slotTimes(slots, meter);
67
+ const inner = new Map();
68
+ timed.forEach(({ slot }, i) => {
69
+ const prior = timed[i - 1];
70
+ const problem = prior && slot.push && pushProblem(slot.push, prior.length);
71
+ if (problem && slot.push && !inner.has(problem))
72
+ inner.set(problem, slot.push);
73
+ });
74
+ return {
75
+ first: timed[0]?.slot ?? null,
76
+ inner: [...inner].map(([problem, push]) => [push, problem]),
77
+ last: timed.at(-1)?.length ?? null,
78
+ };
79
+ }
48
80
  const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
49
81
  const isWritten = (s) => s.lines.some((l) => l.kind === "bars" || l.kind === "invalid");
50
82
  /** Grammar §6: an empty section that matches nothing, and how to fix it. */
@@ -63,22 +95,25 @@ function unmatchedReplay(heading, sections) {
63
95
  export function flattenBars(events) {
64
96
  return events.flatMap((e) => e.kind === "bar" ? [e.bar] : e.kind === "open" ? flattenBars(e.events) : []);
65
97
  }
66
- /** Remove the last bar, looking inside a final open pass and past a final fermata. */
98
+ /** Remove the last bar, looking inside a final open pass and past a final fermata; the bar removed, or null. */
67
99
  function removeLastBar(events) {
68
100
  for (let i = events.length - 1; i >= 0; i--) {
69
101
  const e = events[i];
70
102
  if (e?.kind === "bar") {
71
103
  events.splice(i, 1);
72
- return true;
104
+ return e.bar;
73
105
  }
74
- if (e?.kind === "open" && removeLastBar(e.events))
75
- return true;
106
+ const inner = e?.kind === "open" ? removeLastBar(e.events) : null;
107
+ if (inner)
108
+ return inner;
76
109
  }
77
- return false;
110
+ return null;
78
111
  }
79
112
  /**
80
113
  * Turn the written chart into the bars in play order: sections and their
81
- * replays, repeats, directive changes, `%` and elision.
114
+ * replays, repeats, directive changes, `%` and elision. Its bars count
115
+ * `written` from 1, a pickup included; `parseChart` and `extractPart`
116
+ * renumber a pickup to 0 (grammar 2.4).
82
117
  */
83
118
  /**
84
119
  * `label` names the part a projected chart is (grammar 7.4), for its
@@ -90,9 +125,10 @@ pedal = true,
90
125
  /** The words each bar sings, for the line that sings them (grammar 7.7). */
91
126
  sing) {
92
127
  const diagnostics = [];
93
- const maxBars = Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
128
+ const maxBars = barsFor(share);
94
129
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
95
- const maxWork = maxBars * 10;
130
+ const maxWork = workFor(share);
131
+ const { readable, unread } = shareOf(lines, share, maxWork);
96
132
  // The return after a jump plays sections again: it reports only what the first pass did not.
97
133
  const reported = new Set();
98
134
  let again = false;
@@ -104,7 +140,7 @@ sing) {
104
140
  diagnostics.push({ line, severity: "error", message, token });
105
141
  };
106
142
  const sections = [{ heading: null, lines: [] }];
107
- for (const l of lines) {
143
+ for (const l of readable) {
108
144
  if (l.kind === "section")
109
145
  sections.push({ heading: l, lines: [] });
110
146
  else if (l.kind !== "title")
@@ -192,7 +228,7 @@ sing) {
192
228
  error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
193
229
  // Pair |: and :| within each section, with any endings.
194
230
  const itemsOf = new Map(sections.map((s) => [s, pairRepeats(s.lines, error)]));
195
- const plan = planJump(lines, error);
231
+ const plan = planJump(readable, error);
196
232
  const start = () => ({
197
233
  key: null,
198
234
  time: { n: 4, d: 4 },
@@ -245,13 +281,38 @@ sing) {
245
281
  let openDepth = 0;
246
282
  const nestedOpen = new Set();
247
283
  const checked = new Set();
248
- const stop = (line) => {
284
+ /** Verses sung by bars playing again: work, counted for the message. */
285
+ let againSung = 0;
286
+ /** Bars a replay's `->` cut after they played: `count` counts them, the output doesn't. */
287
+ let cutBars = 0;
288
+ /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, or a part's lines. */
289
+ const stop = (line, why = "work") => {
249
290
  capped = true;
250
- error(line, `expansion stopped at ${maxBars} bars`, "x");
291
+ const what = () => {
292
+ if (why === "bars")
293
+ return `expansion stopped at ${maxBars} bars`;
294
+ const after = `expansion stopped after ${count - cutBars} bars`;
295
+ if (why === "verses")
296
+ return `${after}: the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`;
297
+ if (why === "lines")
298
+ return `${after}: each of ${share} parts reads at most ${maxWork} lines`;
299
+ return `${after}: its repeats play too many times`;
300
+ };
301
+ error(line, what(), "x");
302
+ };
303
+ /** A part that stopped reading its lines before play stopped says so. */
304
+ const readAll = (next) => {
305
+ // Play that ended (at Fine, after the jump) never reaches the lines past the share.
306
+ if (next && !capped && phase !== "done")
307
+ stop(next.line, "lines");
251
308
  };
252
309
  let sectionName = null;
253
310
  /** The pass of the repeat being played, and the replay heading being played, for the words (grammar 7.7). */
254
- const where = { pass: null, replay: null };
311
+ const where = {
312
+ pass: null,
313
+ passes: null,
314
+ replay: null,
315
+ };
255
316
  let phase = "main";
256
317
  const stopped = () => capped || phase === "jumped" || phase === "done";
257
318
  const jumped = () => phase === "jumped";
@@ -273,7 +334,6 @@ sing) {
273
334
  /** A bar as played now; in a one-bar meter it also carries the `time:` in force (grammar 2.4). */
274
335
  const barOf = (p, line) => {
275
336
  const meter = p.meter ?? state.time;
276
- checkSlots(p, meter, line);
277
337
  const { key, tempo, change: tempoChange, feel, swingPercent } = state;
278
338
  return {
279
339
  index: 0,
@@ -293,26 +353,63 @@ sing) {
293
353
  ...(p.tacet && { tacet: p.tacet }),
294
354
  };
295
355
  };
356
+ /** Where a played bar comes from, for its words (grammar 7.7). */
357
+ const sourceOf = (p, line) => ({
358
+ line,
359
+ bar: p.bar,
360
+ ...where,
361
+ });
296
362
  /** The bar with the words it sings here, if any (grammar 7.7). */
297
363
  const sung = (bar, p, line) => {
298
- const lyrics = sing?.(bar, { line, bar: p.bar, ...where });
364
+ const lyrics = sing?.(bar, sourceOf(p, line));
299
365
  return lyrics ? { ...bar, lyrics } : bar;
300
366
  };
301
367
  /** How long the slot played just before is, in whole notes; null after a fermata or at the start. */
302
368
  const before = { length: null };
303
369
  const pushReported = new Set();
370
+ const report = (line, problem, push) => {
371
+ const key = `${line}\u0000${problem}`;
372
+ if (!problem || pushReported.has(key))
373
+ return;
374
+ pushReported.add(key);
375
+ error(line, problem, PUSH_MARKS[push ?? "eighth"]);
376
+ };
377
+ const pushesOf = perWritten(pushesIn);
304
378
  /** Each push takes its time from the slot played just before it (grammar 2.8). */
305
379
  const checkPushes = (bar) => {
306
- const timed = slotTimes(bar.slots, bar.meter);
307
- for (const { slot, length } of timed) {
308
- const problem = slot.push && pushProblem(slot.push, before.length);
309
- const key = `${bar.line}\u0000${problem}`;
310
- if (problem && !pushReported.has(key)) {
311
- pushReported.add(key);
312
- error(bar.line, problem, PUSH_MARKS[slot.push ?? "eighth"]);
313
- }
314
- before.length = length;
315
- }
380
+ const { first, inner, last } = pushesOf(bar.slots, bar.meter);
381
+ if (first?.push)
382
+ report(bar.line, pushProblem(first.push, before.length), first.push);
383
+ for (const [push, problem] of inner)
384
+ report(bar.line, problem, push);
385
+ if (last !== null)
386
+ before.length = last;
387
+ };
388
+ /**
389
+ * The verses a written bar would sing playing again here: work, since
390
+ * many verses replayed many times would otherwise multiply. Its first
391
+ * play's are as many as are written, so they cost nothing more. Asked
392
+ * before the bar is sung, so a bar the budget stops sings nothing.
393
+ */
394
+ const sungBefore = new Set();
395
+ const replayedVerses = (p, bar, line) => sungBefore.has(p) ? (sing?.verses(bar, sourceOf(p, line)) ?? 0) : 0;
396
+ /** Each output bar's charge for its verses, so a bar `->` cuts gives its charge back to the message. */
397
+ const charged = new WeakMap();
398
+ /** A bar as played and sung: its checks and its words, once the budget has room for it. */
399
+ const playBar = (p, line) => {
400
+ const bar = barOf(p, line);
401
+ const again = replayedVerses(p, bar, line);
402
+ if (work + again > maxWork)
403
+ return null;
404
+ work += again;
405
+ againSung += again;
406
+ sungBefore.add(p);
407
+ checkSlots(p, bar.meter, line);
408
+ checkPushes(bar);
409
+ const played = sung(bar, p, line);
410
+ if (again)
411
+ charged.set(played, again);
412
+ return played;
316
413
  };
317
414
  const emit = (p, line, out) => {
318
415
  if (stopped())
@@ -328,11 +425,12 @@ sing) {
328
425
  return void out.push({ kind: "fermata", line });
329
426
  }
330
427
  if (count >= maxBars)
331
- return stop(line);
428
+ return stop(line, "bars");
429
+ const played = playBar(p, line);
430
+ if (!played)
431
+ return stop(line, "verses");
332
432
  count++;
333
- const bar = barOf(p, line);
334
- checkPushes(bar);
335
- out.push({ kind: "bar", bar: sung(bar, p, line) });
433
+ out.push({ kind: "bar", bar: played });
336
434
  };
337
435
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
338
436
  const times = (repeat, line, out, body) => {
@@ -356,7 +454,9 @@ sing) {
356
454
  };
357
455
  /** Play `n` passes; a repeat's are numbered for the words (grammar 7.7), a plain line's are not. */
358
456
  const passes = (n, counted, line, play) => {
359
- const outer = where.pass;
457
+ const outer = { ...where };
458
+ if (counted)
459
+ where.passes = n;
360
460
  for (let i = 0; i < n && !stopped(); i++) {
361
461
  if (++work > maxWork)
362
462
  return stop(line);
@@ -364,7 +464,7 @@ sing) {
364
464
  where.pass = i + 1;
365
465
  play();
366
466
  }
367
- where.pass = outer;
467
+ Object.assign(where, { pass: outer.pass, passes: outer.passes });
368
468
  };
369
469
  const playLine = ({ line: l, repeat }, out) => {
370
470
  if (stopped())
@@ -395,7 +495,9 @@ sing) {
395
495
  const playEndings = (it, out) => {
396
496
  const highest = typeof it.repeat === "number" ? it.repeat : 1;
397
497
  const first = phase === "main" ? 1 : highest;
398
- const outer = where.pass;
498
+ const outer = { ...where };
499
+ // After the jump only the last pass plays.
500
+ where.passes = highest - first + 1;
399
501
  for (let pass = first; pass <= highest && !stopped(); pass++) {
400
502
  if (++work > maxWork)
401
503
  return stop(it.line);
@@ -407,7 +509,7 @@ sing) {
407
509
  if (ending)
408
510
  playLine(ending.entry, out);
409
511
  }
410
- where.pass = outer;
512
+ Object.assign(where, { pass: outer.pass, passes: outer.passes });
411
513
  };
412
514
  const events = [];
413
515
  const occurrences = [];
@@ -449,7 +551,13 @@ sing) {
449
551
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
450
552
  where.replay = null;
451
553
  // It cuts the last bar as written; play stopped before it (a Fine, a To Coda) never reaches it.
452
- const elided = h.elided && reachesEnd(source, out) && removeLastBar(out);
554
+ const cut = h.elided && reachesEnd(source, out) ? removeLastBar(out) : null;
555
+ if (cut) {
556
+ // The message counts what is output: the cut bar and its verses are not.
557
+ cutBars++;
558
+ againSung -= charged.get(cut) ?? 0;
559
+ }
560
+ const elided = cut !== null;
453
561
  // A replay heading stands for its bars: its own lines (directives) come after them.
454
562
  playItems(itemsOf.get(s) ?? [], out);
455
563
  return { replayOf: source.heading.line, elided };
@@ -486,6 +594,7 @@ sing) {
486
594
  phase = plan.to === "start" ? "return" : "seek segno";
487
595
  playSections();
488
596
  }
597
+ readAll(unread);
489
598
  flattenBars(events).forEach((b, i) => {
490
599
  b.index = i + 1;
491
600
  });
@@ -504,5 +613,5 @@ sing) {
504
613
  });
505
614
  if (pedal)
506
615
  diagnostics.push(...pedalWarnings(flattenBars(events)));
507
- return { events, sections: sectionsOut, diagnostics };
616
+ return { events, sections: sectionsOut, diagnostics, stopped: capped };
508
617
  }
@@ -11,6 +11,7 @@ export { MAX_LINES } from "./lines.js";
11
11
  export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
+ export { opensWithPickup } from "./pickup.js";
14
15
  export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
16
  export { memberShares } from "./shares.js";
16
17
  export { streamKey } from "./systems.js";
@@ -11,6 +11,7 @@ export { MAX_LINES } from "./lines.js";
11
11
  export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
+ export { opensWithPickup } from "./pickup.js";
14
15
  export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
16
  export { memberShares } from "./shares.js";
16
17
  export { streamKey } from "./systems.js";