barmark 0.25.1 → 0.26.1

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,82 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.26.1] - 2026-11-30
13
+
14
+ ### Fixed
15
+
16
+ - **Directive lines applied too many times stop the expansion.** Every
17
+ repetition of a section (a replay, `## A x N`, `|: … :| x N`, the
18
+ return after a jump) applies each of its directive lines again, and
19
+ applying one charged no work, so N repetitions of N `key:` lines took
20
+ time quadratic in N: 8,000 replays of 8,000 lines about 2 s, 100 kB
21
+ (10,000 replays of 7,100 lines) 1.3 to 2 s, 1 MB 62 to 108 s when the
22
+ section plays a bar and 309 to 507 s when its only bar line is `| |`;
23
+ and `## A x ...` replays of such a section met no limit at all (1.8 MB:
24
+ 98 s). Play now applies at most ten times its work budget in directive
25
+ lines: 1,000,000 for one stream, and its share for each of several (a
26
+ stream is a part, or one line of a part that writes lines; `extractPart`
27
+ of a two-line part shares it between them, and of a part without lines,
28
+ or of one named line, has it all). A chart past it stops with an error
29
+ on the directive line it reached
30
+ ("expansion stopped after 278 bars: its directive lines are applied too
31
+ many times (1,000,000)"), which, as at every other limit, is then the
32
+ only report of what it cut short: each of those shapes now takes under
33
+ 0.4 s. The budget is far above real charts, not only above slow ones:
34
+ the examples and fixtures apply at most 10 of 1,000,000, the owner's
35
+ songs at most 2, while a chart that applies just over 1,000,000 took
36
+ under 0.1 s (2,000 replays of 2,000 `key: D` lines, 24 kB, now stops
37
+ after 501 bars). A chart under the budget reads exactly as before.
38
+ - **The parser no longer throws on a long chart.** It passed some of its
39
+ lists to a call one argument per element (`events.push(...out)`, and
40
+ the same for diagnostics, repeats' lines and `Math.max`), and an engine
41
+ takes only so many, so `parseChart` threw a `RangeError` on charts as
42
+ small as a few kilobytes of a particular shape: `## A x 355` over 355
43
+ lines of `| @A | x ...` (4.6 kB) under Node, `## A x 800` (10.4 kB)
44
+ under Bun; and under Node a directive line of 150,000 settings
45
+ (900 kB), an unclosed `|:` before 150,000 lines (1 MB), or a section of
46
+ 99,000 fermatas on a small stack. Each list is now appended to one
47
+ element at a time, with the same result in the same order; a test
48
+ parses those charts under Node and Bun, and another keeps the pattern
49
+ out of the parser's source.
50
+ - **A pass of an open repeat counts toward the expansion's work.** A
51
+ counted pass (`x 3`, a section's pass) cost one unit of the work budget
52
+ and a pass of `x ...` cost nothing, so a bar line with its own `x ...`
53
+ that plays no bar and no fermata (`| @A | x ...`, `| Segno | x ...`)
54
+ could be repeated without limit: N replays of N such lines took time
55
+ and memory quadratic in N (36 kB: 1.5 s, 4 million events, 1.8 GB;
56
+ 72 kB: 5 to 7 s, 16 million, 6.8 GB; `## A x ...` replays at 768 kB:
57
+ 52 to 85 s). Each open pass now costs one unit, as a counted one does,
58
+ so such a chart stops with "expansion stopped after N bars: its repeats
59
+ play too many times", as repeats of fermatas do: each of those shapes
60
+ now takes under 0.3 s and 200 MB, and no chart makes more than 100,000
61
+ open events. A chart whose work stays within the budget reads exactly
62
+ as before.
63
+ - **A replay with `->` no longer walks its section's lines again.**
64
+ Whether `->` cuts a bar looked for the section's last written bar on
65
+ every replay, walking each of its lines, so N `->` replays of a section
66
+ of N lines of any kind took time quadratic in N (4,000 of 4,000 text
67
+ lines took 9 to 12 times as long as 1,000 of 1,000). The bar is now
68
+ found once per section, and nothing in the parse changes.
69
+
70
+ ## [0.26.0] - 2026-11-29
71
+
72
+ ### Added
73
+
74
+ - **Each bar line's first written bar number** (Kevin, 2026-11-28; grammar
75
+ A.7 and decisions log): a bar line in `lines`, and a bar line excluded for
76
+ an error, carries `firstWritten`, the written number of its first bar (0 for
77
+ the pickup), as `PlayedBar.written` counts, whether or not any pass plays
78
+ it. Every line of a system that has one has the same. It is absent on a
79
+ line that writes no bar, and on a line of a system whose bars the
80
+ numbering does not count (a one-line system whose line is dropped, a
81
+ system whose reference line writes none, a system with no reference line
82
+ whose counted line is a dropped bar line), and on a line past a part's
83
+ share of the lines in a chart of many parts. So a host can number and
84
+ pair every written bar, played or not, without recounting from the
85
+ lines. `extractPart` gives its lines the numbers its bars are played
86
+ with. No chart changes meaning, and nothing else in the parse changes.
87
+
12
88
  ## [0.25.1] - 2026-11-29
13
89
 
14
90
  ### Fixed
@@ -958,7 +1034,9 @@ The first working release: the reference parser and printer for the
958
1034
 
959
1035
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
960
1036
 
961
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.1...HEAD
1037
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.1...HEAD
1038
+ [0.26.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.26.0...barmark-v0.26.1
1039
+ [0.26.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.1...barmark-v0.26.0
962
1040
  [0.25.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.25.0...barmark-v0.25.1
963
1041
  [0.25.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.24.0...barmark-v0.25.0
964
1042
  [0.24.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.23.1...barmark-v0.24.0
package/README.md CHANGED
@@ -191,7 +191,14 @@ an object. It has two kinds of field:
191
191
  - **The chart as written:** `title`, `parts`, `credits` and `lines`, one
192
192
  entry per source line in order (the title, a bar line, a heading, a
193
193
  directive, a `part:` line, a credit, a lyric row, text, a break, or an
194
- invalid bar line kept as written), each with its line number.
194
+ invalid bar line kept as written), each with its line number. A bar
195
+ line, and an invalid one, carries `firstWritten`: the written number of its
196
+ first bar (0 for a pickup), played or not; absent on a line that writes
197
+ no bar, and on a line of a system whose bars the numbering does not
198
+ count (a one-line system whose line is dropped, say), and on a line past
199
+ a part's share of the lines in a very long chart of many parts (the
200
+ grammar's A.7 row lists every case). A pickup's line has
201
+ `firstWritten: 0`, which is falsy: test it with `!== undefined`.
195
202
  - **The chart as played**, worked out from the written lines:
196
203
  - `events` is play order with fermatas and an open repeat kept as
197
204
  events.
@@ -617,6 +617,7 @@ export function parseBarLine(text, line) {
617
617
  body = `${body.slice(0, -2)}|`;
618
618
  const written = barsWritten(body);
619
619
  const stray = strayEnding(body);
620
+ // bounded: a message and its token.
620
621
  if (stray)
621
622
  error(...stray);
622
623
  if (body.includes(":|") || body.includes("|:"))
@@ -118,6 +118,7 @@ export function planJump(lines, error) {
118
118
  const jump = first.get("jump");
119
119
  const plan = jump?.direction.kind === "jump" ? jump.direction : null;
120
120
  if (jump && plan)
121
+ // bounded: at most the four marks a jump can miss.
121
122
  problems.push(...missingMarks(jump, plan, first).map((m) => [jump, m]));
122
123
  const coda = first.get("coda");
123
124
  // Only the Coda an al Coda goes on; an unused one is an error of its own.
@@ -5,6 +5,7 @@ import { parseDirectiveLine } from "./directives.js";
5
5
  import { continueEndings } from "./endingLines.js";
6
6
  import { checkLines } from "./lines.js";
7
7
  import { attachLyrics, readLyricRow } from "./lyricRows.js";
8
+ import { append } from "./many.js";
8
9
  import { readPart } from "./partLine.js";
9
10
  import { groupSystems } from "./systems.js";
10
11
  const NEAR_DIRECTIVES = {
@@ -274,7 +275,7 @@ export function readDocument(text) {
274
275
  return partLine(read, t, line);
275
276
  const directive = parseDirectiveLine(t, line);
276
277
  if (directive) {
277
- diagnostics.push(...directive.diagnostics);
278
+ append(diagnostics, directive.diagnostics);
278
279
  return { kind: "directive", line, set: directive.set };
279
280
  }
280
281
  const old = oldFormat(t, line);
@@ -284,7 +285,7 @@ export function readDocument(text) {
284
285
  };
285
286
  const barLine = (t, line) => {
286
287
  const r = parseBarLine(t, line);
287
- diagnostics.push(...r.diagnostics);
288
+ append(diagnostics, r.diagnostics);
288
289
  return r.bars ?? { kind: "invalid", line, text: t, written: r.written };
289
290
  };
290
291
  /** A labelled line that can't be read: no space before its pipe, or a bad line name. */
@@ -322,7 +323,7 @@ export function readDocument(text) {
322
323
  /** `lyrics:` or `lyrics N:` then a bar line (grammar 7.7); one with an error stays text. */
323
324
  const lyricRow = (t, line) => {
324
325
  const read = readLyricRow(t, line);
325
- diagnostics.push(...read.diagnostics);
326
+ append(diagnostics, read.diagnostics);
326
327
  if (read.row || read.diagnostics.length)
327
328
  return read.row ?? { kind: "text", line, text: t };
328
329
  return null;
@@ -365,7 +366,8 @@ export function readDocument(text) {
365
366
  const grouped = groupParts(lines, read);
366
367
  const lyrics = attachLyrics(grouped.lines);
367
368
  const ended = continueEndings(lyrics.lines);
368
- diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics, ...ended.diagnostics);
369
+ for (const found of [grouped, lyrics, ended])
370
+ append(diagnostics, found.diagnostics);
369
371
  const { parts } = grouped;
370
372
  return {
371
373
  title,
@@ -30,6 +30,18 @@ export declare const MAX_EXPANDED_BARS = 10000;
30
30
  * times the lines never multiply.
31
31
  */
32
32
  export declare const workFor: (share: number) => number;
33
+ /**
34
+ * The directive lines one of `share` streams may apply: ten times its
35
+ * work. A stream is a part, or one line of a part that writes lines, so a
36
+ * chart's two-line part has two and each applies 500,000; `extractPart`
37
+ * plays a part of no lines, or one named line, as one stream. Every
38
+ * repetition of a section applies its directive lines again, so N
39
+ * repetitions of N lines would cost N squared with no bound but the
40
+ * file's size. An application costs about 30 ns, so a million bound it at
41
+ * tens of milliseconds; real charts apply a handful (the examples and
42
+ * fixtures at most 10, the owner's songs at most 2).
43
+ */
44
+ export declare const directivesFor: (share: number) => number;
33
45
  /** Every played bar in order, with an open repeat's pass included once. */
34
46
  export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
35
47
  /**
@@ -46,4 +58,12 @@ sing?: Sing): {
46
58
  diagnostics: ChartDiagnostic[];
47
59
  /** Whether play stopped at a limit: what follows from that alone goes unreported. */
48
60
  stopped: boolean;
61
+ /**
62
+ * The first written number of each line this expansion reads that writes
63
+ * a bar, by its line number: counting from 1 with no pickup shift, over
64
+ * the lines given (one stream's, in a chart of parts: no system sharing),
65
+ * played or not. None for a line that writes no bar, and for a line past
66
+ * a part's share of lines. `withFirstWritten` makes the bar lines' field.
67
+ */
68
+ firsts: Map<number, number>;
49
69
  };
@@ -1,5 +1,6 @@
1
1
  import { planJump } from "./direction.js";
2
2
  import { beatsOf } from "./directives.js";
3
+ import { append } from "./many.js";
3
4
  import { pedalWarnings } from "./pedal.js";
4
5
  import { pairRepeats } from "./repeats.js";
5
6
  import { perWritten, slotTimes } from "./shares.js";
@@ -13,6 +14,18 @@ const barsFor = (share) => Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
13
14
  * times the lines never multiply.
14
15
  */
15
16
  export const workFor = (share) => barsFor(share) * 10;
17
+ /**
18
+ * The directive lines one of `share` streams may apply: ten times its
19
+ * work. A stream is a part, or one line of a part that writes lines, so a
20
+ * chart's two-line part has two and each applies 500,000; `extractPart`
21
+ * plays a part of no lines, or one named line, as one stream. Every
22
+ * repetition of a section applies its directive lines again, so N
23
+ * repetitions of N lines would cost N squared with no bound but the
24
+ * file's size. An application costs about 30 ns, so a million bound it at
25
+ * tens of milliseconds; real charts apply a handful (the examples and
26
+ * fixtures at most 10, the owner's songs at most 2).
27
+ */
28
+ export const directivesFor = (share) => workFor(share) * 10;
16
29
  /**
17
30
  * The lines one of several parts reads: its share of the work, since the
18
31
  * parts times the lines would otherwise multiply; and the first it
@@ -143,6 +156,7 @@ sing) {
143
156
  const maxBars = barsFor(share);
144
157
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
145
158
  const maxWork = workFor(share);
159
+ const maxApplied = directivesFor(share);
146
160
  const { readable, unread } = shareOf(lines, share, maxWork);
147
161
  // The return after a jump plays sections again: it reports only what the first pass did not.
148
162
  const reported = new Set();
@@ -227,17 +241,27 @@ sing) {
227
241
  return markBar(c, line);
228
242
  return c.kind === "simile" ? simile(c, line) : ownBar(c, line);
229
243
  };
230
- for (const l of sections.flatMap((s) => s.lines)) {
231
- if (l.kind === "invalid")
232
- written += l.written;
233
- if (l.kind !== "bars")
234
- continue;
244
+ /** Each bar line's first written number, by its line number; none for a line that writes no bar. */
245
+ const firsts = new Map();
246
+ const resolveLine = (l) => {
235
247
  let bar = 0;
236
- resolved.set(l, l.cells
248
+ return l.cells
237
249
  .map((c) => resolveCell(c, l.line))
238
250
  .filter((p) => p !== null)
239
- .map((p) => (p.kind === "bar" ? { ...p, bar: bar++ } : p)));
240
- }
251
+ .map((p) => (p.kind === "bar" ? { ...p, bar: bar++ } : p));
252
+ };
253
+ /** A line's bars take the numbers after those written before it; an excluded line's too. */
254
+ const readLine = (l) => {
255
+ const first = written + 1;
256
+ if (l.kind === "invalid")
257
+ written += l.written;
258
+ if (l.kind === "bars")
259
+ resolved.set(l, resolveLine(l));
260
+ if (written >= first)
261
+ firsts.set(l.line, first);
262
+ };
263
+ for (const l of sections.flatMap((s) => s.lines))
264
+ readLine(l);
241
265
  const unused = pending.mark;
242
266
  if (unused)
243
267
  error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
@@ -300,6 +324,7 @@ sing) {
300
324
  };
301
325
  let count = 0;
302
326
  let work = 0;
327
+ let applied = 0;
303
328
  let capped = false;
304
329
  let openDepth = 0;
305
330
  const nestedOpen = new Set();
@@ -308,20 +333,20 @@ sing) {
308
333
  let againSung = 0;
309
334
  /** Bars a replay's `->` cut after they played: `count` counts them, the output doesn't. */
310
335
  let cutBars = 0;
311
- /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, or a part's lines. */
336
+ /** Why play stopped, after the bars it played: each limit but the bar cap's. */
337
+ const reasons = {
338
+ verses: () => `the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`,
339
+ lines: () => `each of ${share} parts reads at most ${maxWork} lines`,
340
+ work: () => "its repeats play too many times",
341
+ directives: () => `its directive lines are applied too many times (${maxApplied.toLocaleString("en-US")})`,
342
+ };
343
+ /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, directive lines applied too often, or a part's lines. */
312
344
  const stop = (line, why = "work") => {
313
345
  capped = true;
314
- const what = () => {
315
- if (why === "bars")
316
- return `expansion stopped at ${maxBars} bars`;
317
- const after = `expansion stopped after ${count - cutBars} bars`;
318
- if (why === "verses")
319
- return `${after}: the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`;
320
- if (why === "lines")
321
- return `${after}: each of ${share} parts reads at most ${maxWork} lines`;
322
- return `${after}: its repeats play too many times`;
323
- };
324
- error(line, what(), "x");
346
+ const what = why === "bars"
347
+ ? `expansion stopped at ${maxBars} bars`
348
+ : `expansion stopped after ${count - cutBars} bars: ${reasons[why]()}`;
349
+ error(line, what, "x");
325
350
  };
326
351
  /** A part that stopped reading its lines before play stopped says so. */
327
352
  const readAll = (next) => {
@@ -455,9 +480,16 @@ sing) {
455
480
  count++;
456
481
  out.push({ kind: "bar", bar: played });
457
482
  };
458
- /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
483
+ /**
484
+ * Play `body` `repeat` times into `out`; an open repeat plays one pass
485
+ * inside an open event. Its pass is work, as a counted pass is: a pass
486
+ * that plays nothing would otherwise repeat for free.
487
+ */
459
488
  const times = (repeat, line, out, body) => {
460
489
  if (repeat === "open") {
490
+ // Not once play has stopped: the stop is the only report of what it cut short.
491
+ if (!capped && ++work > maxWork)
492
+ return stop(line);
461
493
  if (openDepth > 0) {
462
494
  if (!nestedOpen.has(line))
463
495
  error(line, "an open repeat inside another open repeat", "x ...");
@@ -489,11 +521,17 @@ sing) {
489
521
  }
490
522
  Object.assign(where, { pass: outer.pass, passes: outer.passes });
491
523
  };
524
+ /** A directive line applied as play reaches it, once the budget has room for it. */
525
+ const applyLine = (l) => {
526
+ if (++applied > maxApplied)
527
+ return stop(l.line, "directives");
528
+ apply(l.set, l.line);
529
+ };
492
530
  const playLine = ({ line: l, repeat }, out) => {
493
531
  if (stopped())
494
532
  return;
495
533
  if (l.kind === "directive")
496
- apply(l.set, l.line);
534
+ return applyLine(l);
497
535
  if (l.kind !== "bars")
498
536
  return;
499
537
  times(repeat, l.line, out, (into) => {
@@ -554,11 +592,20 @@ sing) {
554
592
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(s) ?? [], into));
555
593
  return { replayOf: null, elided: false };
556
594
  };
557
- /** Whether `out` ends with the last bar written in `s` (grammar 6: what `->` cuts). */
558
- const reachesEnd = (s, out) => {
595
+ /** The written number of the last bar written in each section, found once: every `->` replay asks. */
596
+ const lastWritten = new Map();
597
+ const lastIn = (s) => {
598
+ if (lastWritten.has(s))
599
+ return lastWritten.get(s);
559
600
  const bars = s.lines.flatMap((l) => (l.kind === "bars" ? (resolved.get(l) ?? []) : []));
560
601
  const last = bars.findLast((p) => p.kind === "bar");
561
- return last?.kind === "bar" && flattenBars(out).at(-1)?.written === last.written;
602
+ lastWritten.set(s, last?.kind === "bar" ? last.written : undefined);
603
+ return lastWritten.get(s);
604
+ };
605
+ /** Whether `out` ends with the last bar written in `s` (grammar 6: what `->` cuts). */
606
+ const reachesEnd = (s, out) => {
607
+ const last = lastIn(s);
608
+ return last !== undefined && flattenBars(out).at(-1)?.written === last;
562
609
  };
563
610
  /** A replay's bars into `out`, then its own lines; null when it replays nothing. */
564
611
  const playReplay = (s, h, out) => {
@@ -606,7 +653,7 @@ sing) {
606
653
  const played = isWritten(s) ? playWritten(s, h, out) : playReplay(s, h, out);
607
654
  if (!played)
608
655
  return;
609
- events.push(...out);
656
+ append(events, out);
610
657
  record(h, out, played.replayOf, played.elided);
611
658
  };
612
659
  playSections();
@@ -635,6 +682,6 @@ sing) {
635
682
  };
636
683
  });
637
684
  if (pedal)
638
- diagnostics.push(...pedalWarnings(flattenBars(events)));
639
- return { events, sections: sectionsOut, diagnostics, stopped: capped };
685
+ append(diagnostics, pedalWarnings(flattenBars(events)));
686
+ return { events, sections: sectionsOut, diagnostics, stopped: capped, firsts };
640
687
  }
@@ -0,0 +1,10 @@
1
+ import type { Line } from "./types.js";
2
+ /**
3
+ * The lines with each bar line's `firstWritten` (grammar 2.4, A.7), from the
4
+ * numbering the parse's bars were played with: `firsts`, `expand`'s first
5
+ * number of each line it read (counting from 1, by line number), one
6
+ * lower when the chart opens with a pickup. A system's lines take the
7
+ * number of the one line of it that stream read, found among `written`
8
+ * (the chart's lines as written); a line that writes no bar takes none.
9
+ */
10
+ export declare function withFirstWritten(lines: Line[], written: Line[], firsts: Map<number, number>, pickup: boolean): Line[];
@@ -0,0 +1,30 @@
1
+ const isBarLine = (l) => l.kind === "bars" || l.kind === "invalid";
2
+ /** Whether a line writes a bar: a bar or `%` cell, or for an excluded line a bar its pipes write. */
3
+ const writesBar = (l) => l.kind === "invalid"
4
+ ? l.written > 0
5
+ : l.cells.some((c) => c.kind === "slots" || c.kind === "simile");
6
+ /**
7
+ * The lines with each bar line's `firstWritten` (grammar 2.4, A.7), from the
8
+ * numbering the parse's bars were played with: `firsts`, `expand`'s first
9
+ * number of each line it read (counting from 1, by line number), one
10
+ * lower when the chart opens with a pickup. A system's lines take the
11
+ * number of the one line of it that stream read, found among `written`
12
+ * (the chart's lines as written); a line that writes no bar takes none.
13
+ */
14
+ export function withFirstWritten(lines, written, firsts, pickup) {
15
+ const bySystem = new Map();
16
+ for (const l of written) {
17
+ if (!isBarLine(l) || l.system === undefined)
18
+ continue;
19
+ const first = firsts.get(l.line);
20
+ if (first !== undefined)
21
+ bySystem.set(l.system, first);
22
+ }
23
+ const shift = pickup ? 1 : 0;
24
+ return lines.map((l) => {
25
+ if (!isBarLine(l) || !writesBar(l))
26
+ return l;
27
+ const first = l.system === undefined ? firsts.get(l.line) : bySystem.get(l.system);
28
+ return first === undefined ? l : { ...l, firstWritten: first - shift };
29
+ });
30
+ }
@@ -1,3 +1,4 @@
1
+ import { append } from "./many.js";
1
2
  /** At most this many lines per part (grammar 7.6). */
2
3
  export const MAX_LINES = 4;
3
4
  const isLabelled = (l) => (l.kind === "bars" || l.kind === "invalid") && l.part !== undefined;
@@ -35,9 +36,13 @@ function nameLines(lines, report) {
35
36
  }
36
37
  /** Push `item` onto the list at `key`, starting it if new: a copy per item would cost the list squared. */
37
38
  function pushAt(map, key, ...items) {
39
+ pushAllAt(map, key, items);
40
+ }
41
+ /** Push `items` onto the list at `key` in order, starting it if new: one push per item, never a spread. */
42
+ function pushAllAt(map, key, items) {
38
43
  const known = map.get(key);
39
44
  if (known)
40
- known.push(...items);
45
+ append(known, items);
41
46
  else
42
47
  map.set(key, items);
43
48
  }
@@ -79,7 +84,7 @@ function bareBeside(systems) {
79
84
  for (const [part, own] of system) {
80
85
  const bare = own.filter((l) => l.lineName === undefined);
81
86
  if (bare.length && bare.length < own.length)
82
- pushAt(out, part, ...bare);
87
+ pushAllAt(out, part, bare);
83
88
  }
84
89
  return out;
85
90
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Arrays as long as the input, used whole without spreading them into a
3
+ * call: a spread passes one argument per element, and an engine takes only
4
+ * so many (V8 about 100,000, Bun more), so `xs.push(...ys)` and
5
+ * `Math.max(...ys)` throw a `RangeError` on a large enough chart.
6
+ */
7
+ /** Append `items` to `to` in order, as `to.push(...items)` would. */
8
+ export declare function append<T>(to: T[], items: readonly T[]): void;
9
+ /** The largest of `from` and `xs`, as `Math.max(from, ...xs)` would be; -Infinity for none. */
10
+ export declare function largest(xs: Iterable<number>, from?: number): number;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Arrays as long as the input, used whole without spreading them into a
3
+ * call: a spread passes one argument per element, and an engine takes only
4
+ * so many (V8 about 100,000, Bun more), so `xs.push(...ys)` and
5
+ * `Math.max(...ys)` throw a `RangeError` on a large enough chart.
6
+ */
7
+ /** Append `items` to `to` in order, as `to.push(...items)` would. */
8
+ export function append(to, items) {
9
+ for (const x of items)
10
+ to.push(x);
11
+ }
12
+ /** The largest of `from` and `xs`, as `Math.max(from, ...xs)` would be; -Infinity for none. */
13
+ export function largest(xs, from = Number.NEGATIVE_INFINITY) {
14
+ let most = from;
15
+ for (const x of xs)
16
+ most = Math.max(most, x);
17
+ return most;
18
+ }
@@ -16,7 +16,8 @@ export declare function parseChart(text: string): ChartParse;
16
16
  * line: the part's first line also plays its bare and tutti lines, and a
17
17
  * line rests where it isn't written. A part that writes its bare line
18
18
  * beside its named lines makes it a line of its own (`lineName` `""`), and
19
- * the named lines no longer play it. Null when the chart declares no part
19
+ * the named lines no longer play it. Its bar lines' `firstWritten` are the
20
+ * numbers its bars are played with. Null when the chart declares no part
20
21
  * with that label, or the part no line of that name. Never throws.
21
22
  */
22
23
  export declare function extractPart(text: string, label: string, lineName?: string): ChartParse | null;
@@ -1,5 +1,7 @@
1
1
  import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars, workFor } from "./expand.js";
3
+ import { withFirstWritten } from "./firstWritten.js";
4
+ import { append, largest } from "./many.js";
3
5
  import { projectPart, projectPartLines } from "./parts.js";
4
6
  import { pedalWarnings } from "./pedal.js";
5
7
  import { numberFromPickup } from "./pickup.js";
@@ -63,7 +65,7 @@ const lineOf = (e) => (e.kind === "bar" ? e.bar.line : e.line);
63
65
  /** The first event at which some part's timeline differs in shape from the lead's, or -1. */
64
66
  function stepAt(each) {
65
67
  const [lead = []] = each;
66
- const longest = Math.max(...each.map((events) => events.length));
68
+ const longest = largest(each.map((events) => events.length));
67
69
  for (let i = 0; i < longest; i++)
68
70
  if (each.some((events) => events[i]?.kind !== lead[i]?.kind))
69
71
  return i;
@@ -212,8 +214,16 @@ function playStreams(lines, parts, shown, voices) {
212
214
  const stopped = played.some((p) => p.stopped);
213
215
  const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d), stopped);
214
216
  const events = foldEvents(zipped, byPart(streams, shown), shown);
215
- diagnostics.push(...linedPedalWarnings(events, shown));
216
- return { events, sections: played[0]?.sections ?? [], diagnostics, stopped };
217
+ append(diagnostics, linedPedalWarnings(events, shown));
218
+ // The bars carry the first stream's numbers (`zipBar`), so its lines' numbers are the chart's.
219
+ const lead = played[0];
220
+ return {
221
+ events,
222
+ sections: lead?.sections ?? [],
223
+ diagnostics,
224
+ stopped,
225
+ firsts: lead?.firsts ?? new Map(),
226
+ };
217
227
  }
218
228
  const lined = (parts) => parts.some((p) => p.lines?.length);
219
229
  /** What the voices found as they sang (grammar 7.7), once playing is done; past a stop, not what it left unsung. */
@@ -238,7 +248,7 @@ export function parseChart(text) {
238
248
  part,
239
249
  parts: withSings(doc.parts, voice.all),
240
250
  credits: doc.credits,
241
- lines: doc.lines,
251
+ lines: withFirstWritten(doc.lines, doc.lines, played.firsts, pickup),
242
252
  events: played.events,
243
253
  bars,
244
254
  pickup,
@@ -277,7 +287,8 @@ function extractOf(doc, part, voices, lineName) {
277
287
  * line: the part's first line also plays its bare and tutti lines, and a
278
288
  * line rests where it isn't written. A part that writes its bare line
279
289
  * beside its named lines makes it a line of its own (`lineName` `""`), and
280
- * the named lines no longer play it. Null when the chart declares no part
290
+ * the named lines no longer play it. Its bar lines' `firstWritten` are the
291
+ * numbers its bars are played with. Null when the chart declares no part
281
292
  * with that label, or the part no line of that name. Never throws.
282
293
  */
283
294
  export function extractPart(text, label, lineName) {
@@ -293,7 +304,8 @@ export function extractPart(text, label, lineName) {
293
304
  const pickup = numberFromPickup(bars);
294
305
  // The lyric rows are their owner's, or the chart's when no part sings (grammar 7.7).
295
306
  const rows = voices.some((v) => v.singer === voice.owner);
296
- const lines = rows ? extract.lines : extract.lines.filter((l) => l.kind !== "lyrics");
307
+ const numbered = withFirstWritten(extract.lines, doc.lines, played.firsts, pickup);
308
+ const lines = rows ? numbered : numbered.filter((l) => l.kind !== "lyrics");
297
309
  const kept = new Set(lines.map((l) => l.line));
298
310
  // A stand-in may sit on another part's line; that part's problems are not this one's.
299
311
  for (const l of doc.lines)
@@ -3,6 +3,7 @@ import { printDirection } from "./direction.js";
3
3
  import { beatsOf } from "./directives.js";
4
4
  import { readDocument } from "./document.js";
5
5
  import { printKey } from "./keys.js";
6
+ import { largest } from "./many.js";
6
7
  import { extractPart, parseChart } from "./parse.js";
7
8
  import { splitSyllable } from "./syllable.js";
8
9
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
@@ -210,7 +211,7 @@ function partsIndex(parts) {
210
211
  if (!at.has(p.label))
211
212
  at.set(p.label, i);
212
213
  });
213
- const width = Math.max(...parts.flatMap(labelsOf).map((label) => label.length));
214
+ const width = largest(parts.flatMap(labelsOf).map((label) => label.length));
214
215
  const made = { at, width };
215
216
  partsKnown.set(parts, made);
216
217
  return made;
@@ -233,7 +234,7 @@ const spanOf = (k, bars, n) => [
233
234
  const roomOf = (columns, [a, b]) => columns.slice(a, b + 1).reduce((x, y) => x + y, 0) + 3 * (b - a);
234
235
  /** Each column's width: the widest of the bar lines' cells, widened for a row's cell that won't fit. */
235
236
  function columnsOf(lines, rows, bars) {
236
- const columns = (lines[0]?.cells ?? []).map((_, i) => Math.max(...lines.map((p) => p.cells[i]?.length ?? 0)));
237
+ const columns = (lines[0]?.cells ?? []).map((_, i) => largest(lines.map((p) => p.cells[i]?.length ?? 0)));
237
238
  for (const r of rows)
238
239
  for (const [k, c] of r.cells.entries()) {
239
240
  const room = roomOf(columns, spanOf(k, bars, columns.length));
@@ -248,7 +249,7 @@ function columnsOf(lines, rows, bars) {
248
249
  * pipes lined up; a row's cell spans the cells of its bar (grammar 7.7).
249
250
  */
250
251
  function alignBlock(lines, rows, bars, width) {
251
- const w = Math.max(width, ...rows.map((r) => r.label.length));
252
+ const w = largest(rows.map((r) => r.label.length), width);
252
253
  const columns = columnsOf(lines, rows, bars);
253
254
  const print = (p, pad) => `${p.label.padEnd(w)} ${joinPieces({ ...p, cells: p.cells.map(pad) })}`.trimEnd();
254
255
  const texts = new Map();
@@ -302,7 +303,7 @@ const lastKnown = new WeakMap();
302
303
  function lastOf(covers) {
303
304
  let last = lastKnown.get(covers);
304
305
  if (last === undefined) {
305
- last = Math.max(...covers);
306
+ last = largest(covers);
306
307
  lastKnown.set(covers, last);
307
308
  }
308
309
  return last;
@@ -1,7 +1,8 @@
1
1
  import { BETWEEN_ENDINGS } from "./endingLines.js";
2
+ import { append, largest } from "./many.js";
2
3
  const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
3
4
  const asLine = (line) => ({ kind: "line", line, repeat: null });
4
- const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
5
+ const highestPass = (endings) => largest(endings.flatMap((b) => b.ending ?? []));
5
6
  /** Every pass from 1 to the highest has exactly one ending, and the highest is at least 2. */
6
7
  function passProblems(endings, last) {
7
8
  const highest = highestPass(endings);
@@ -112,7 +113,7 @@ export function pairRepeats(lines, error) {
112
113
  const st = { items: [], open: null, endings: null };
113
114
  const finish = () => {
114
115
  if (st.endings)
115
- st.items.push(...closeEndings(st.endings, error));
116
+ append(st.items, closeEndings(st.endings, error));
116
117
  st.endings = null;
117
118
  };
118
119
  for (const l of lines) {
@@ -130,7 +131,7 @@ export function pairRepeats(lines, error) {
130
131
  finish();
131
132
  if (st.open) {
132
133
  error(st.open.line, "|: is never closed in this section", "|:");
133
- st.items.push(...st.open.entries.map((e) => ({ kind: "line", ...e })));
134
+ append(st.items, st.open.entries.map((e) => ({ kind: "line", ...e })));
134
135
  }
135
136
  return st.items;
136
137
  }
@@ -218,6 +218,27 @@ export type Line = {
218
218
  system?: number;
219
219
  /** Set when the line's bars or structure differ from its system's (an error): its part is tacet there. */
220
220
  dropped?: true;
221
+ /**
222
+ * The written number of the line's first bar (grammar 2.4, A.7): what
223
+ * `PlayedBar.written` is for that bar when a pass plays it, and the number
224
+ * it would have when none does. 0 when that bar is the chart's pickup.
225
+ * Every line of a system that writes a bar has the system's, a `dropped`
226
+ * line included.
227
+ * Absent when the line writes no bar (no bar or `%` cell), and on a line
228
+ * of a system whose bars the numbering does not count. The numbering is
229
+ * the first part's (its first line, when it writes lines): the chart's
230
+ * first declared part, or in an extract the extracted part. A system
231
+ * counts what its reference line (its first bar line not `dropped`)
232
+ * writes, whatever that part's own line there is: none when it writes no
233
+ * bar (a reference of only `...`, say). With no reference, it counts
234
+ * that part's own line there, else the system's first line: an excluded
235
+ * line's `written`, and none for a `dropped` bar line (a one-line system
236
+ * whose line is dropped, say). A line past a part's share of the lines
237
+ * (`expand`'s limit for a chart of several parts) has none either. A
238
+ * played bar's `line` may be a line with none (a tacet bar on a dropped
239
+ * line that writes no bar): `PlayedBar.written` is the bar's number.
240
+ */
241
+ firstWritten?: number;
221
242
  }
222
243
  /** A text line; `escaped` when written with a leading `\` (grammar 1), which `text` leaves off. */
223
244
  | {
@@ -264,6 +285,13 @@ export type Line = {
264
285
  part?: string;
265
286
  lineName?: string;
266
287
  system?: number;
288
+ /**
289
+ * The written number its first bar would have (grammar 2.4, A.7), as on
290
+ * a bar line: in a system, the system's. Absent when `written` is 0, and
291
+ * when the parse's numbering counts no bars for it, by the rule on a bar
292
+ * line's `firstWritten`.
293
+ */
294
+ firstWritten?: number;
267
295
  };
268
296
  export type PlayedBar = {
269
297
  /**
@@ -93,6 +93,7 @@ function shorthandFor(intervals) {
93
93
  * by a flat sixth (`C(b6,9)`, not `C6/9(b6)`), else the first.
94
94
  */
95
95
  function bestSuffix(candidates, exact, intervals) {
96
+ // bounded: the candidates are suffixes of the fixed vocabulary, a few at most.
96
97
  const most = Math.max(...candidates.map(exact));
97
98
  const tied = candidates.filter((c) => exact(c) === most);
98
99
  const shorthand = shorthandFor(intervals);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.25.1",
3
+ "version": "0.26.1",
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": {