barmark 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ /** Lines that may sit between endings, and between an ending's lines (grammar 5.1): they mean nothing to the timeline. */
2
+ export const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
3
+ const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
4
+ const systemOf = (l) => (l.kind === "bars" || l.kind === "invalid" ? l.system : undefined);
5
+ /** The chart's lines as units: each system's lines read as one, by its first line that reads and agrees. */
6
+ function unitsOf(lines) {
7
+ const units = [];
8
+ for (const l of lines) {
9
+ const last = units.at(-1);
10
+ const first = last?.lines[0];
11
+ if (last && first && inSystem(l) && systemOf(first) === systemOf(l))
12
+ last.lines.push(l);
13
+ else
14
+ units.push({ lines: [l], ref: l });
15
+ }
16
+ for (const u of units)
17
+ u.ref = u.lines.find((l) => l.kind === "bars" && !l.dropped) ?? u.lines[0];
18
+ return units;
19
+ }
20
+ const bars = (l) => (l.kind === "bars" ? l : null);
21
+ /** A bar line with no repeat start and no ending: one an ending can continue onto. */
22
+ const plain = (l) => l.kind === "bars" && !l.opens && !l.ending;
23
+ const startsEnding = (l) => l?.kind === "bars" && l.ending !== null;
24
+ /** The same lines, and directive lines too: what an ending would continue past if directives could sit in it. */
25
+ const PAST_DIRECTIVES = new Set([...BETWEEN_ENDINGS, "directive"]);
26
+ /** The first unit from `from` whose kind isn't one of `past`; reads only up to it. */
27
+ function nextHeard(units, from, past) {
28
+ let k = from;
29
+ while (k < units.length && past.has(units[k].ref.kind))
30
+ k++;
31
+ return units[k]?.ref;
32
+ }
33
+ /**
34
+ * The units an unclosed ending at `at` continues onto: the plain bar lines
35
+ * after it, up to its `:|` or the next ending, when another ending follows
36
+ * (grammar 5.1). The last ending has none, so it ends at its own line.
37
+ * `past` are the lines that may sit among them.
38
+ */
39
+ function continuation(units, at, past = BETWEEN_ENDINGS) {
40
+ const run = [];
41
+ for (let k = at + 1; k < units.length; k++) {
42
+ const ref = units[k].ref;
43
+ if (past.has(ref.kind))
44
+ continue;
45
+ if (startsEnding(ref))
46
+ return run;
47
+ if (!plain(ref))
48
+ return [];
49
+ run.push(k);
50
+ if (bars(ref)?.closes)
51
+ return startsEnding(nextHeard(units, k + 1, past)) ? run : [];
52
+ }
53
+ return [];
54
+ }
55
+ /** A directive line's own name, as its token: `time:`, `tempo:`. */
56
+ function directiveName(set) {
57
+ const first = Object.keys(set)[0] ?? "key";
58
+ const name = { tempoChange: "tempo", swingPercent: "feel" }[first] ?? first;
59
+ return `${name}:`;
60
+ }
61
+ /**
62
+ * The directive line that stopped an ending continuing, when without it
63
+ * the ending would have continued: named, beside the errors that follow
64
+ * (grammar 5.1). Null when nothing would have continued anyway.
65
+ */
66
+ function directiveInside(units, at, head) {
67
+ if (continuation(units, at).length || !continuation(units, at, PAST_DIRECTIVES).length)
68
+ return null;
69
+ for (let k = at + 1; k < units.length; k++) {
70
+ const ref = units[k].ref;
71
+ if (startsEnding(ref))
72
+ break;
73
+ if (ref.kind === "directive")
74
+ return {
75
+ line: ref.line,
76
+ severity: "error",
77
+ message: `a directive line ends the ending |${head.ending?.join(",")} above it; an ending's lines can't hold one`,
78
+ token: directiveName(ref.set),
79
+ };
80
+ }
81
+ return null;
82
+ }
83
+ /** Whether a `|:` is waiting for its `:|` after `l`: a heading or a `:|` ends it, a `|:` opens one. */
84
+ function stillOpen(open, l) {
85
+ if (l.kind === "section")
86
+ return false;
87
+ if (l.kind !== "bars")
88
+ return open;
89
+ return !l.closes && (open || l.opens);
90
+ }
91
+ /** Whether `l` is an ending of a paired repeat, moving the pairing past it. */
92
+ function paired(p, l) {
93
+ if (l.kind === "bars" && l.ending) {
94
+ p.endings = p.open || p.endings;
95
+ p.open = false;
96
+ return p.endings;
97
+ }
98
+ if (!(p.endings && BETWEEN_ENDINGS.has(l.kind))) {
99
+ p.endings = false;
100
+ p.open = stillOpen(p.open, l);
101
+ }
102
+ return false;
103
+ }
104
+ /**
105
+ * Mark the plain bar lines that continue an ending onto further lines
106
+ * (grammar 5.1, Kevin's decision 2026-11-10): each gets the ending's
107
+ * passes as `continues`. Only an ending of a paired repeat continues, so
108
+ * an ending with no `|:` before it leaves a stray `:|` stray. Never throws.
109
+ */
110
+ export function continueEndings(lines) {
111
+ const units = unitsOf(lines);
112
+ const marked = new Map();
113
+ const diagnostics = [];
114
+ const pairing = { open: false, endings: false };
115
+ for (let i = 0; i < units.length; i++) {
116
+ const ref = units[i].ref;
117
+ if (!paired(pairing, ref) || ref.kind !== "bars" || !ref.ending || ref.closes)
118
+ continue;
119
+ const run = continuation(units, i);
120
+ for (const k of run)
121
+ for (const l of units[k].lines)
122
+ marked.set(l, ref.ending);
123
+ const inside = directiveInside(units, i, ref);
124
+ if (inside)
125
+ diagnostics.push(inside);
126
+ // The lines it continues onto belong to the ending: the pairing goes on after them.
127
+ i = run.at(-1) ?? i;
128
+ }
129
+ if (!marked.size)
130
+ return { lines, diagnostics };
131
+ const out = lines.map((l) => {
132
+ const passes = marked.get(l);
133
+ return passes && l.kind === "bars" ? { ...l, continues: passes } : l;
134
+ });
135
+ return { lines: out, diagnostics };
136
+ }
@@ -3,24 +3,35 @@ 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;
18
- /** Every played bar in order, with an open repeat's pass included once. */
19
- export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
20
27
  /**
21
- * Turn the written chart into the bars in play order: sections and their
22
- * replays, repeats, directive changes, `%` and elision.
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.
23
31
  */
32
+ export declare const workFor: (share: number) => number;
33
+ /** Every played bar in order, with an open repeat's pass included once. */
34
+ export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
24
35
  /**
25
36
  * `label` names the part a projected chart is (grammar 7.4), for its
26
37
  * messages; `share` is how many parts split the expansion budget.
@@ -33,4 +44,6 @@ sing?: Sing): {
33
44
  events: ChartEvent[];
34
45
  sections: SectionOccurrence[];
35
46
  diagnostics: ChartDiagnostic[];
47
+ /** Whether play stopped at a limit: what follows from that alone goes unreported. */
48
+ stopped: boolean;
36
49
  };
@@ -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,23 +95,28 @@ 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
  */
118
+ /** The lines of a repeat's ending for `pass` (grammar 5.1), or none. */
119
+ const endingOn = (it, pass) => it.endings.find((x) => x.passes.includes(pass))?.entries ?? [];
83
120
  /**
84
121
  * `label` names the part a projected chart is (grammar 7.4), for its
85
122
  * messages; `share` is how many parts split the expansion budget.
@@ -90,9 +127,10 @@ pedal = true,
90
127
  /** The words each bar sings, for the line that sings them (grammar 7.7). */
91
128
  sing) {
92
129
  const diagnostics = [];
93
- const maxBars = Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
130
+ const maxBars = barsFor(share);
94
131
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
95
- const maxWork = maxBars * 10;
132
+ const maxWork = workFor(share);
133
+ const { readable, unread } = shareOf(lines, share, maxWork);
96
134
  // The return after a jump plays sections again: it reports only what the first pass did not.
97
135
  const reported = new Set();
98
136
  let again = false;
@@ -104,7 +142,7 @@ sing) {
104
142
  diagnostics.push({ line, severity: "error", message, token });
105
143
  };
106
144
  const sections = [{ heading: null, lines: [] }];
107
- for (const l of lines) {
145
+ for (const l of readable) {
108
146
  if (l.kind === "section")
109
147
  sections.push({ heading: l, lines: [] });
110
148
  else if (l.kind !== "title")
@@ -192,7 +230,7 @@ sing) {
192
230
  error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
193
231
  // Pair |: and :| within each section, with any endings.
194
232
  const itemsOf = new Map(sections.map((s) => [s, pairRepeats(s.lines, error)]));
195
- const plan = planJump(lines, error);
233
+ const plan = planJump(readable, error);
196
234
  const start = () => ({
197
235
  key: null,
198
236
  time: { n: 4, d: 4 },
@@ -245,13 +283,38 @@ sing) {
245
283
  let openDepth = 0;
246
284
  const nestedOpen = new Set();
247
285
  const checked = new Set();
248
- const stop = (line) => {
286
+ /** Verses sung by bars playing again: work, counted for the message. */
287
+ let againSung = 0;
288
+ /** Bars a replay's `->` cut after they played: `count` counts them, the output doesn't. */
289
+ let cutBars = 0;
290
+ /** Stop playing, saying why: the bar cap, the verses sung again, repeats that play too much, or a part's lines. */
291
+ const stop = (line, why = "work") => {
249
292
  capped = true;
250
- error(line, `expansion stopped at ${maxBars} bars`, "x");
293
+ const what = () => {
294
+ if (why === "bars")
295
+ return `expansion stopped at ${maxBars} bars`;
296
+ const after = `expansion stopped after ${count - cutBars} bars`;
297
+ if (why === "verses")
298
+ return `${after}: the bars played again sing too many verses (${againSung.toLocaleString("en-US")})`;
299
+ if (why === "lines")
300
+ return `${after}: each of ${share} parts reads at most ${maxWork} lines`;
301
+ return `${after}: its repeats play too many times`;
302
+ };
303
+ error(line, what(), "x");
304
+ };
305
+ /** A part that stopped reading its lines before play stopped says so. */
306
+ const readAll = (next) => {
307
+ // Play that ended (at Fine, after the jump) never reaches the lines past the share.
308
+ if (next && !capped && phase !== "done")
309
+ stop(next.line, "lines");
251
310
  };
252
311
  let sectionName = null;
253
312
  /** 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 };
313
+ const where = {
314
+ pass: null,
315
+ passes: null,
316
+ replay: null,
317
+ };
255
318
  let phase = "main";
256
319
  const stopped = () => capped || phase === "jumped" || phase === "done";
257
320
  const jumped = () => phase === "jumped";
@@ -273,7 +336,6 @@ sing) {
273
336
  /** A bar as played now; in a one-bar meter it also carries the `time:` in force (grammar 2.4). */
274
337
  const barOf = (p, line) => {
275
338
  const meter = p.meter ?? state.time;
276
- checkSlots(p, meter, line);
277
339
  const { key, tempo, change: tempoChange, feel, swingPercent } = state;
278
340
  return {
279
341
  index: 0,
@@ -293,26 +355,63 @@ sing) {
293
355
  ...(p.tacet && { tacet: p.tacet }),
294
356
  };
295
357
  };
358
+ /** Where a played bar comes from, for its words (grammar 7.7). */
359
+ const sourceOf = (p, line) => ({
360
+ line,
361
+ bar: p.bar,
362
+ ...where,
363
+ });
296
364
  /** The bar with the words it sings here, if any (grammar 7.7). */
297
365
  const sung = (bar, p, line) => {
298
- const lyrics = sing?.(bar, { line, bar: p.bar, ...where });
366
+ const lyrics = sing?.(bar, sourceOf(p, line));
299
367
  return lyrics ? { ...bar, lyrics } : bar;
300
368
  };
301
369
  /** How long the slot played just before is, in whole notes; null after a fermata or at the start. */
302
370
  const before = { length: null };
303
371
  const pushReported = new Set();
372
+ const report = (line, problem, push) => {
373
+ const key = `${line}\u0000${problem}`;
374
+ if (!problem || pushReported.has(key))
375
+ return;
376
+ pushReported.add(key);
377
+ error(line, problem, PUSH_MARKS[push ?? "eighth"]);
378
+ };
379
+ const pushesOf = perWritten(pushesIn);
304
380
  /** Each push takes its time from the slot played just before it (grammar 2.8). */
305
381
  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
- }
382
+ const { first, inner, last } = pushesOf(bar.slots, bar.meter);
383
+ if (first?.push)
384
+ report(bar.line, pushProblem(first.push, before.length), first.push);
385
+ for (const [push, problem] of inner)
386
+ report(bar.line, problem, push);
387
+ if (last !== null)
388
+ before.length = last;
389
+ };
390
+ /**
391
+ * The verses a written bar would sing playing again here: work, since
392
+ * many verses replayed many times would otherwise multiply. Its first
393
+ * play's are as many as are written, so they cost nothing more. Asked
394
+ * before the bar is sung, so a bar the budget stops sings nothing.
395
+ */
396
+ const sungBefore = new Set();
397
+ const replayedVerses = (p, bar, line) => sungBefore.has(p) ? (sing?.verses(bar, sourceOf(p, line)) ?? 0) : 0;
398
+ /** Each output bar's charge for its verses, so a bar `->` cuts gives its charge back to the message. */
399
+ const charged = new WeakMap();
400
+ /** A bar as played and sung: its checks and its words, once the budget has room for it. */
401
+ const playBar = (p, line) => {
402
+ const bar = barOf(p, line);
403
+ const again = replayedVerses(p, bar, line);
404
+ if (work + again > maxWork)
405
+ return null;
406
+ work += again;
407
+ againSung += again;
408
+ sungBefore.add(p);
409
+ checkSlots(p, bar.meter, line);
410
+ checkPushes(bar);
411
+ const played = sung(bar, p, line);
412
+ if (again)
413
+ charged.set(played, again);
414
+ return played;
316
415
  };
317
416
  const emit = (p, line, out) => {
318
417
  if (stopped())
@@ -328,11 +427,12 @@ sing) {
328
427
  return void out.push({ kind: "fermata", line });
329
428
  }
330
429
  if (count >= maxBars)
331
- return stop(line);
430
+ return stop(line, "bars");
431
+ const played = playBar(p, line);
432
+ if (!played)
433
+ return stop(line, "verses");
332
434
  count++;
333
- const bar = barOf(p, line);
334
- checkPushes(bar);
335
- out.push({ kind: "bar", bar: sung(bar, p, line) });
435
+ out.push({ kind: "bar", bar: played });
336
436
  };
337
437
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
338
438
  const times = (repeat, line, out, body) => {
@@ -356,7 +456,9 @@ sing) {
356
456
  };
357
457
  /** Play `n` passes; a repeat's are numbered for the words (grammar 7.7), a plain line's are not. */
358
458
  const passes = (n, counted, line, play) => {
359
- const outer = where.pass;
459
+ const outer = { ...where };
460
+ if (counted)
461
+ where.passes = n;
360
462
  for (let i = 0; i < n && !stopped(); i++) {
361
463
  if (++work > maxWork)
362
464
  return stop(line);
@@ -364,7 +466,7 @@ sing) {
364
466
  where.pass = i + 1;
365
467
  play();
366
468
  }
367
- where.pass = outer;
469
+ Object.assign(where, { pass: outer.pass, passes: outer.passes });
368
470
  };
369
471
  const playLine = ({ line: l, repeat }, out) => {
370
472
  if (stopped())
@@ -395,7 +497,9 @@ sing) {
395
497
  const playEndings = (it, out) => {
396
498
  const highest = typeof it.repeat === "number" ? it.repeat : 1;
397
499
  const first = phase === "main" ? 1 : highest;
398
- const outer = where.pass;
500
+ const outer = { ...where };
501
+ // After the jump only the last pass plays.
502
+ where.passes = highest - first + 1;
399
503
  for (let pass = first; pass <= highest && !stopped(); pass++) {
400
504
  if (++work > maxWork)
401
505
  return stop(it.line);
@@ -403,11 +507,10 @@ sing) {
403
507
  where.pass = phase === "main" ? pass : 1;
404
508
  for (const e of it.entries)
405
509
  playLine(e, out);
406
- const ending = it.endings.find((x) => x.passes.includes(pass));
407
- if (ending)
408
- playLine(ending.entry, out);
510
+ for (const e of endingOn(it, pass))
511
+ playLine(e, out);
409
512
  }
410
- where.pass = outer;
513
+ Object.assign(where, { pass: outer.pass, passes: outer.passes });
411
514
  };
412
515
  const events = [];
413
516
  const occurrences = [];
@@ -449,7 +552,13 @@ sing) {
449
552
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
450
553
  where.replay = null;
451
554
  // 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);
555
+ const cut = h.elided && reachesEnd(source, out) ? removeLastBar(out) : null;
556
+ if (cut) {
557
+ // The message counts what is output: the cut bar and its verses are not.
558
+ cutBars++;
559
+ againSung -= charged.get(cut) ?? 0;
560
+ }
561
+ const elided = cut !== null;
453
562
  // A replay heading stands for its bars: its own lines (directives) come after them.
454
563
  playItems(itemsOf.get(s) ?? [], out);
455
564
  return { replayOf: source.heading.line, elided };
@@ -486,6 +595,7 @@ sing) {
486
595
  phase = plan.to === "start" ? "return" : "seek segno";
487
596
  playSections();
488
597
  }
598
+ readAll(unread);
489
599
  flattenBars(events).forEach((b, i) => {
490
600
  b.index = i + 1;
491
601
  });
@@ -504,5 +614,5 @@ sing) {
504
614
  });
505
615
  if (pedal)
506
616
  diagnostics.push(...pedalWarnings(flattenBars(events)));
507
- return { events, sections: sectionsOut, diagnostics };
617
+ return { events, sections: sectionsOut, diagnostics, stopped: capped };
508
618
  }
@@ -11,7 +11,8 @@ 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 { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
14
+ export { opensWithPickup } from "./pickup.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
15
16
  export { memberShares } from "./shares.js";
16
17
  export { streamKey } from "./systems.js";
17
18
  export { type TransposeBy, transposeChart } from "./transpose.js";
@@ -11,7 +11,8 @@ 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 { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
14
+ export { opensWithPickup } from "./pickup.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
15
16
  export { memberShares } from "./shares.js";
16
17
  export { streamKey } from "./systems.js";
17
18
  export { transposeChart } from "./transpose.js";
@@ -7,7 +7,8 @@ const slotsOf = (l) => l.cells.flatMap((c) => (c.kind === "slots" ? c.slots.flat
7
7
  function notesOnlyProblem(l) {
8
8
  const slots = slotsOf(l);
9
9
  const harmony = slots.some((s) => s.kind === "nc" ||
10
- s.kind === "unknown" ||
10
+ // An unreadable slot is already an error of its own, not harmony written here.
11
+ (s.kind === "unknown" && s.text === undefined) ||
11
12
  (s.kind === "chord" && (s.chord.kind !== "notes" || s.voicing !== undefined)));
12
13
  if (harmony)
13
14
  return "chord symbols go on the part's first line; write a note set here, or a voicing on the first line";
@@ -32,11 +33,19 @@ function nameLines(lines, report) {
32
33
  });
33
34
  return { lines: out, names };
34
35
  }
36
+ /** Push `item` onto the list at `key`, starting it if new: a copy per item would cost the list squared. */
37
+ function pushAt(map, key, ...items) {
38
+ const known = map.get(key);
39
+ if (known)
40
+ known.push(...items);
41
+ else
42
+ map.set(key, items);
43
+ }
35
44
  /** A system's lines by part, in written order. */
36
45
  function byPart(system) {
37
46
  const out = new Map();
38
47
  for (const l of system)
39
- out.set(l.part ?? "", [...(out.get(l.part ?? "") ?? []), l]);
48
+ pushAt(out, l.part ?? "", l);
40
49
  return out;
41
50
  }
42
51
  /**
@@ -45,12 +54,17 @@ function byPart(system) {
45
54
  * they first appear.
46
55
  */
47
56
  function scoreOrder(names, systems) {
57
+ // Each part's first system writing two or more of its lines, found in one pass over the systems.
58
+ const full = new Map();
59
+ for (const system of systems)
60
+ for (const [part, own] of system) {
61
+ const named = own.flatMap((l) => l.lineName ?? []);
62
+ if (named.length > 1 && !full.has(part))
63
+ full.set(part, named);
64
+ }
48
65
  const out = new Map();
49
66
  for (const [part, all] of names) {
50
- const full = systems
51
- .map((s) => (byPart(s).get(part) ?? []).flatMap((l) => l.lineName ?? []))
52
- .find((n) => n.length > 1);
53
- const first = full ?? [];
67
+ const first = full.get(part) ?? [];
54
68
  out.set(part, [...first, ...all.filter((n) => !first.includes(n))]);
55
69
  }
56
70
  return out;
@@ -62,10 +76,10 @@ function scoreOrder(names, systems) {
62
76
  function bareBeside(systems) {
63
77
  const out = new Map();
64
78
  for (const system of systems)
65
- for (const [part, own] of byPart(system)) {
79
+ for (const [part, own] of system) {
66
80
  const bare = own.filter((l) => l.lineName === undefined);
67
81
  if (bare.length && bare.length < own.length)
68
- out.set(part, [...(out.get(part) ?? []), ...bare]);
82
+ pushAt(out, part, ...bare);
69
83
  }
70
84
  return out;
71
85
  }
@@ -116,9 +130,11 @@ export function checkLines(lines, parts) {
116
130
  const systems = new Map();
117
131
  for (const l of named.lines)
118
132
  if (isLabelled(l) && l.system !== undefined && !failed.has(l.line))
119
- systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
120
- const bare = bareBeside([...systems.values()]);
121
- const order = withBare(scoreOrder(named.names, [...systems.values()]), bare, report);
133
+ pushAt(systems, l.system, l);
134
+ // Each system's lines by part, once: not once for every part.
135
+ const parted = [...systems.values()].map(byPart);
136
+ const bare = bareBeside(parted);
137
+ const order = withBare(scoreOrder(named.names, parted), bare, report);
122
138
  for (const system of systems.values())
123
139
  checkSystem(system.filter((l) => !failed.has(l.line)), order, report);
124
140
  const out = named.lines.map((l) => l.kind === "bars" && failed.has(l.line) ? { ...l, dropped: true } : l);
@@ -84,12 +84,22 @@ const isRow = (l) => l.kind === "lyrics" || (l.kind === "text" && !l.escaped &&
84
84
  const isCovered = (l) => l.kind === "bars" || l.kind === "invalid";
85
85
  const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
86
86
  const plural = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
87
+ /** Each unit's reference line and its bar count, found once however many rows lie under it. */
88
+ const referenceOf = new WeakMap();
89
+ function unitReference(unit) {
90
+ if (referenceOf.has(unit))
91
+ return referenceOf.get(unit) ?? null;
92
+ const ref = unit.find((l) => l.kind === "bars" && !l.dropped);
93
+ const found = ref ? { ref, n: ref.cells.filter(isBar).length } : null;
94
+ referenceOf.set(unit, found);
95
+ return found;
96
+ }
87
97
  /** Why a row can't lie under a unit, or null: its bar count must be the unit's. */
88
98
  function countProblem(row, unit) {
89
- const ref = unit.find((l) => l.kind === "bars" && !l.dropped);
90
- if (ref?.kind !== "bars")
99
+ const found = unitReference(unit);
100
+ if (!found)
91
101
  return null;
92
- const n = ref.cells.filter(isBar).length;
102
+ const { ref, n } = found;
93
103
  if (row.cells.length === n)
94
104
  return null;
95
105
  return `this lyric row has ${plural(row.cells.length, "bar")}; the bar line it covers has ${n} (line ${ref.line})`;
@@ -161,6 +171,8 @@ function placeRows(s, definitions) {
161
171
  export function attachLyrics(lines) {
162
172
  const diagnostics = [];
163
173
  const covers = new Map();
174
+ // One list of lines for each unit, shared by its rows: a copy per row costs the rows times the unit's lines.
175
+ const linesOf = new Map();
164
176
  const definitions = new Map();
165
177
  const placed = sectionsOf(lines).flatMap((s) => placeRows(s, definitions));
166
178
  // A row with an error of its own (kept as text) only holds its place.
@@ -170,8 +182,11 @@ export function attachLyrics(lines) {
170
182
  const why = unit ? countProblem(row, unit) : problem;
171
183
  if (why)
172
184
  diagnostics.push({ line: row.line, severity: "error", message: why, token: "lyrics" });
173
- if (unit)
174
- covers.set(row, unit.map((l) => l.line));
185
+ if (!unit)
186
+ continue;
187
+ const own = linesOf.get(unit) ?? unit.map((l) => l.line);
188
+ linesOf.set(unit, own);
189
+ covers.set(row, own);
175
190
  }
176
191
  const out = lines.map((l) => (l.kind === "lyrics" ? { ...l, covers: covers.get(l) ?? [] } : l));
177
192
  return { lines: out, diagnostics };