barmark 0.16.0 → 0.17.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.
@@ -55,6 +55,37 @@ function scoreOrder(names, systems) {
55
55
  }
56
56
  return out;
57
57
  }
58
+ /**
59
+ * Each part's bare lines written beside its named lines in a system: the
60
+ * bare line is then the part's first line, its name "" (grammar 7.6).
61
+ */
62
+ function bareBeside(systems) {
63
+ const out = new Map();
64
+ for (const system of systems)
65
+ for (const [part, own] of byPart(system)) {
66
+ const bare = own.filter((l) => l.lineName === undefined);
67
+ if (bare.length && bare.length < own.length)
68
+ out.set(part, [...(out.get(part) ?? []), ...bare]);
69
+ }
70
+ return out;
71
+ }
72
+ /**
73
+ * Score order with each bare line written beside named lines first (as
74
+ * ""), unless the part already names four lines: those bare lines are
75
+ * then errors, and are reported.
76
+ */
77
+ function withBare(order, bare, report) {
78
+ const out = new Map(order);
79
+ for (const [part, lines] of bare) {
80
+ const named = order.get(part) ?? [];
81
+ if (named.length < MAX_LINES)
82
+ out.set(part, ["", ...named]);
83
+ else
84
+ for (const l of lines)
85
+ report(l, "a part has at most four lines");
86
+ }
87
+ return out;
88
+ }
58
89
  /** A system's lines of each part, after the first in score order, hold notes only. */
59
90
  function checkSystem(system, order, report) {
60
91
  for (const [part, written] of byPart(system)) {
@@ -86,9 +117,10 @@ export function checkLines(lines, parts) {
86
117
  for (const l of named.lines)
87
118
  if (isLabelled(l) && l.system !== undefined && !failed.has(l.line))
88
119
  systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
89
- const order = scoreOrder(named.names, [...systems.values()]);
120
+ const bare = bareBeside([...systems.values()]);
121
+ const order = withBare(scoreOrder(named.names, [...systems.values()]), bare, report);
90
122
  for (const system of systems.values())
91
- checkSystem(system, order, report);
123
+ checkSystem(system.filter((l) => !failed.has(l.line)), order, report);
92
124
  const out = named.lines.map((l) => l.kind === "bars" && failed.has(l.line) ? { ...l, dropped: true } : l);
93
125
  const declared = parts.map((p) => {
94
126
  const own = order.get(p.label ?? "");
@@ -0,0 +1,25 @@
1
+ import type { ChartDiagnostic, Line } from "./types.js";
2
+ type LyricsLine = Extract<Line, {
3
+ kind: "lyrics";
4
+ }>;
5
+ /** `lyrics:` or `lyrics N:`, then a bar line (grammar 7.7). */
6
+ export declare const LYRIC_ROW: RegExp;
7
+ /**
8
+ * A lyric row (grammar 7.7), not yet attached to the bars it covers. Null
9
+ * when the line isn't one, or when it has an error.
10
+ */
11
+ export declare function readLyricRow(text: string, line: number): {
12
+ row: LyricsLine | null;
13
+ diagnostics: ChartDiagnostic[];
14
+ };
15
+ /**
16
+ * Attach each lyric row to the bar lines it covers (grammar 7.7): the bar
17
+ * line or system just above it, or under a replay heading the replayed
18
+ * section's lines, one row each per verse. A row covering nothing, or with
19
+ * a bar count other than its unit's, is an error. Never throws.
20
+ */
21
+ export declare function attachLyrics(lines: Line[]): {
22
+ lines: Line[];
23
+ diagnostics: ChartDiagnostic[];
24
+ };
25
+ export {};
@@ -0,0 +1,178 @@
1
+ import { isBar } from "./barLine.js";
2
+ import { readSyllable } from "./syllable.js";
3
+ /** `lyrics:` or `lyrics N:`, then a bar line (grammar 7.7). */
4
+ export const LYRIC_ROW = /^lyrics(?:\s+(\d+))?:\s*(\|.*)$/i;
5
+ /** One token of a lyric row: `/` a hold, `--` a breath, else a syllable (4.3); null when none reads. */
6
+ function readToken(token) {
7
+ if (token === "/")
8
+ return { kind: "hold" };
9
+ if (token === "--")
10
+ return { kind: "breath" };
11
+ if (/["{}]/.test(token))
12
+ return null;
13
+ const syllable = readSyllable(token);
14
+ return syllable?.kind === "sung" ? { kind: "syllable", syllable } : null;
15
+ }
16
+ /** A slot: a token, or tokens joined by `_` into a group. */
17
+ function readSlot(token) {
18
+ const members = token.split("_").map(readToken);
19
+ if (members.some((m) => m === null))
20
+ return null;
21
+ const read = members;
22
+ return read.length === 1 ? (read[0] ?? null) : { kind: "group", members: read };
23
+ }
24
+ const problemOf = (token) => /["{}]/.test(token)
25
+ ? "a lyric row holds syllables only: no quotes or braces"
26
+ : `not a syllable: ${token}`;
27
+ /** A row's cells, each a list of slots, with a diagnostic for each that doesn't read. */
28
+ function readCells(bar, line) {
29
+ const diagnostics = [];
30
+ const parts = bar.split("|").slice(1);
31
+ if (parts.at(-1)?.trim() === "")
32
+ parts.pop();
33
+ else
34
+ diagnostics.push({
35
+ line,
36
+ severity: "warning",
37
+ message: "missing trailing |",
38
+ token: parts.at(-1)?.trim() ?? "",
39
+ });
40
+ const cells = parts.map((part) => {
41
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
42
+ if (!tokens.length)
43
+ diagnostics.push({
44
+ line,
45
+ severity: "error",
46
+ message: "empty bar in a lyric row; a bar with nothing sung is --",
47
+ token: "| |",
48
+ });
49
+ return tokens.flatMap((token) => {
50
+ const slot = readSlot(token);
51
+ if (!slot)
52
+ diagnostics.push({ line, severity: "error", message: problemOf(token), token });
53
+ return slot ? [slot] : [];
54
+ });
55
+ });
56
+ return { cells, diagnostics };
57
+ }
58
+ /** Why a verse number can't be read, or null: from 1 up to the largest safe integer, so it prints back as written. */
59
+ const verseProblem = (verse) => {
60
+ if (verse === 0)
61
+ return "a verse is numbered from 1";
62
+ return verse > Number.MAX_SAFE_INTEGER
63
+ ? `a verse number goes up to ${Number.MAX_SAFE_INTEGER}`
64
+ : null;
65
+ };
66
+ /**
67
+ * A lyric row (grammar 7.7), not yet attached to the bars it covers. Null
68
+ * when the line isn't one, or when it has an error.
69
+ */
70
+ export function readLyricRow(text, line) {
71
+ const m = LYRIC_ROW.exec(text);
72
+ if (!m)
73
+ return { row: null, diagnostics: [] };
74
+ const verse = m[1] === undefined ? null : Number(m[1]);
75
+ const problem = verse === null ? null : verseProblem(verse);
76
+ if (problem)
77
+ return { row: null, diagnostics: [{ line, severity: "error", message: problem, token: text }] };
78
+ const { cells, diagnostics } = readCells(m[2] ?? "", line);
79
+ const failed = diagnostics.some((d) => d.severity === "error");
80
+ return { row: failed ? null : { kind: "lyrics", line, verse, cells, covers: [] }, diagnostics };
81
+ }
82
+ /** A lyric row, or a line kept as text because its row has an error: either holds its place. */
83
+ const isRow = (l) => l.kind === "lyrics" || (l.kind === "text" && !l.escaped && LYRIC_ROW.test(l.text));
84
+ const isCovered = (l) => l.kind === "bars" || l.kind === "invalid";
85
+ const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
86
+ const plural = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
87
+ /** Why a row can't lie under a unit, or null: its bar count must be the unit's. */
88
+ function countProblem(row, unit) {
89
+ const ref = unit.find((l) => l.kind === "bars" && !l.dropped);
90
+ if (ref?.kind !== "bars")
91
+ return null;
92
+ const n = ref.cells.filter(isBar).length;
93
+ if (row.cells.length === n)
94
+ return null;
95
+ return `this lyric row has ${plural(row.cells.length, "bar")}; the bar line it covers has ${n} (line ${ref.line})`;
96
+ }
97
+ function sectionsOf(lines) {
98
+ const sections = [{ name: null, lines: [] }];
99
+ for (const l of lines)
100
+ if (l.kind === "section")
101
+ sections.push({ name: l.name, lines: [] });
102
+ else
103
+ sections.at(-1)?.lines.push(l);
104
+ return sections;
105
+ }
106
+ /** A section's bar lines as units, and each row under a unit with the unit it lies under. */
107
+ function unitsOf(lines) {
108
+ const units = [];
109
+ const under = new Map();
110
+ let above = null;
111
+ for (const l of lines) {
112
+ if (isCovered(l)) {
113
+ if (above && l.system !== undefined && above[0]?.system === l.system)
114
+ above.push(l);
115
+ else {
116
+ above = [l];
117
+ units.push(above);
118
+ }
119
+ }
120
+ else if (isRow(l))
121
+ under.set(l, above);
122
+ else
123
+ above = null;
124
+ }
125
+ return { units, under };
126
+ }
127
+ const NOT_UNDER = "a lyric row goes under a bar line, or under a replay heading";
128
+ /** A row's verse as written, so each verse's rows under a replay count apart. */
129
+ const verseOf = (row) => row.kind === "lyrics"
130
+ ? String(row.verse ?? "")
131
+ : row.kind === "text"
132
+ ? (LYRIC_ROW.exec(row.text)?.[1] ?? "")
133
+ : "";
134
+ /** Rows under a replay heading: each verse's rows cover the replayed section's units in turn. */
135
+ function replayRows(rows, source, name) {
136
+ const counts = new Map();
137
+ const problem = `${name} has ${plural(source.length, "bar line")} to cover; this lyric row is one too many`;
138
+ return rows.map((row) => {
139
+ const k = counts.get(verseOf(row)) ?? 0;
140
+ counts.set(verseOf(row), k + 1);
141
+ return { row, unit: source[k], problem };
142
+ });
143
+ }
144
+ /** Where each row of a section lies, recording a written section's units for its replays. */
145
+ function placeRows(s, definitions) {
146
+ const { units, under } = unitsOf(s.lines);
147
+ const key = s.name === null ? null : normalize(s.name);
148
+ const source = key === null ? undefined : definitions.get(key);
149
+ if (key !== null && units.length)
150
+ definitions.set(key, units);
151
+ if (units.length || !source)
152
+ return [...under].map(([row, unit]) => ({ row, unit, problem: NOT_UNDER }));
153
+ return replayRows([...under.keys()], source, s.name ?? "");
154
+ }
155
+ /**
156
+ * Attach each lyric row to the bar lines it covers (grammar 7.7): the bar
157
+ * line or system just above it, or under a replay heading the replayed
158
+ * section's lines, one row each per verse. A row covering nothing, or with
159
+ * a bar count other than its unit's, is an error. Never throws.
160
+ */
161
+ export function attachLyrics(lines) {
162
+ const diagnostics = [];
163
+ const covers = new Map();
164
+ const definitions = new Map();
165
+ const placed = sectionsOf(lines).flatMap((s) => placeRows(s, definitions));
166
+ // A row with an error of its own (kept as text) only holds its place.
167
+ for (const { row, unit, problem } of placed) {
168
+ if (row.kind !== "lyrics")
169
+ continue;
170
+ const why = unit ? countProblem(row, unit) : problem;
171
+ if (why)
172
+ diagnostics.push({ line: row.line, severity: "error", message: why, token: "lyrics" });
173
+ if (unit)
174
+ covers.set(row, unit.map((l) => l.line));
175
+ }
176
+ const out = lines.map((l) => (l.kind === "lyrics" ? { ...l, covers: covers.get(l) ?? [] } : l));
177
+ return { lines: out, diagnostics };
178
+ }
@@ -12,7 +12,9 @@ export declare function parseChart(text: string): ChartParse;
12
12
  * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
13
13
  * one of the part's lines alone (grammar 7.6), as a converter writes each
14
14
  * line: the part's first line also plays its bare and tutti lines, and a
15
- * line rests where it isn't written. Null when the chart declares no part
15
+ * line rests where it isn't written. A part that writes its bare line
16
+ * beside its named lines makes it a line of its own (`lineName` `""`), and
17
+ * the named lines no longer play it. Null when the chart declares no part
16
18
  * with that label, or the part no line of that name. Never throws.
17
19
  */
18
20
  export declare function extractPart(text: string, label: string, lineName?: string): ChartParse | null;
@@ -2,6 +2,7 @@ import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars } from "./expand.js";
3
3
  import { projectPart, projectPartLines } from "./parts.js";
4
4
  import { pedalWarnings } from "./pedal.js";
5
+ import { together, voicesIn, voicesOf, withSings } from "./verses.js";
5
6
  const RANK = { error: 0, warning: 1 };
6
7
  /** Sorted by line, errors before warnings. */
7
8
  const sortDiagnostics = (all) => all.sort((a, b) => a.line - b.line || RANK[a.severity] - RANK[b.severity]);
@@ -21,9 +22,15 @@ function mergeReports(each) {
21
22
  }
22
23
  const partBar = (b) => b.tacet ? null : { line: b.line, slots: b.slots, ...(b.words && { words: b.words }) };
23
24
  const meterText = (b) => `${b.meter.n}/${b.meter.d}`;
24
- /** One bar of every part: shared fields from the first, the meter from the first that plays. */
25
+ /** Every stream's words in a bar, in verse order, then score order (grammar 7.7). */
26
+ const lyricsOf = (bars) => bars.flatMap((b) => b.lyrics ?? []).sort((a, b) => a.verse - b.verse);
27
+ /**
28
+ * One bar of every part: shared fields from the first, the meter from the
29
+ * first that plays, the words of every stream that sings.
30
+ */
25
31
  function zipBar(bars, report) {
26
32
  const [first, ...rest] = bars;
33
+ const lyrics = lyricsOf(bars);
27
34
  const playing = bars.filter((b) => !b.tacet);
28
35
  const meter = playing[0]?.meter ?? first.meter;
29
36
  const meters = [...new Set(playing.map(meterText))];
@@ -36,7 +43,13 @@ function zipBar(bars, report) {
36
43
  message: `the parts disagree on this bar's meter (${meters.join(", ")})`,
37
44
  token: "|",
38
45
  });
39
- return { ...first, meter, parts: [first, ...rest].map(partBar) };
46
+ const { lyrics: _l, ...shared } = first;
47
+ return {
48
+ ...shared,
49
+ meter,
50
+ parts: [first, ...rest].map(partBar),
51
+ ...(lyrics.length && { lyrics }),
52
+ };
40
53
  }
41
54
  const lineOf = (e) => (e.kind === "bar" ? e.bar.line : e.line);
42
55
  /** The first event at which some part's timeline differs in shape from the lead's, or -1. */
@@ -79,6 +92,8 @@ export function zipEvents(each, report) {
79
92
  return e;
80
93
  });
81
94
  }
95
+ /** How a stream's line is labelled in its messages: `Pno.RH`, or the part's label for its bare line. */
96
+ const lineLabel = (label, name) => (name ? `${label}.${name}` : label);
82
97
  const streamsOf = (shown) => shown.flatMap((p, part) => p.lines?.length
83
98
  ? p.lines.map((name) => ({ part, label: p.label ?? "", name }))
84
99
  : [{ part, label: p.label ?? "", name: null }]);
@@ -133,13 +148,28 @@ function linedPedalWarnings(events, shown) {
133
148
  const bars = flattenBars(events);
134
149
  return shown.flatMap((p, i) => p.lines?.length ? pedalWarnings(bars.map((b) => partView(b, i, shown.length))) : []);
135
150
  }
151
+ /** The stream a voice sings on: its singing line, else its part's first; the first shown for the chart's words. */
152
+ function singingStream(streams, singer) {
153
+ const label = singer?.label?.toLowerCase();
154
+ if (label === undefined)
155
+ return 0;
156
+ const own = (s) => s.label.toLowerCase() === label;
157
+ const at = streams.findIndex((s) => own(s) && (s.name ?? "").toLowerCase() === singer?.sings?.toLowerCase());
158
+ return at >= 0 ? at : streams.findIndex(own);
159
+ }
160
+ /** Each stream's words: the voices singing on it, together. */
161
+ function singsOn(streams, voices) {
162
+ return streams.map((_, i) => together(voices.filter((v) => singingStream(streams, v.singer) === i).map((v) => v.sing)));
163
+ }
136
164
  /**
137
165
  * Parts and their lines: each stream projected and played, zipped into one
138
- * timeline, then folded into the parts shown (grammar 7.4, 7.6).
166
+ * timeline, then folded into the parts shown (grammar 7.4, 7.6). With a
167
+ * voice, the stream that sings takes the words.
139
168
  */
140
- function playStreams(lines, parts, shown) {
169
+ function playStreams(lines, parts, shown, voices) {
141
170
  const streams = streamsOf(shown);
142
- const played = streams.map((s) => expand(projectPart(lines, parts, s.label, s.name), s.name === null ? s.label : `${s.label}.${s.name}`, streams.length, s.name === null));
171
+ const sings = singsOn(streams, voices);
172
+ const played = streams.map((s, i) => expand(projectPart(lines, parts, s.label, s.name), lineLabel(s.label, s.name), streams.length, s.name === null, sings[i]));
143
173
  const diagnostics = mergeReports(played.map((p) => p.diagnostics));
144
174
  const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
145
175
  const events = foldEvents(zipped, streams, shown);
@@ -147,57 +177,79 @@ function playStreams(lines, parts, shown) {
147
177
  return { events, sections: played[0]?.sections ?? [], diagnostics };
148
178
  }
149
179
  const lined = (parts) => parts.some((p) => p.lines?.length);
180
+ /** What the voices found as they sang (grammar 7.7), once playing is done. */
181
+ function sungChecks(voices) {
182
+ return voices.flatMap((v) => {
183
+ v.finish();
184
+ return v.diagnostics;
185
+ });
186
+ }
150
187
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
151
188
  export function parseChart(text) {
152
189
  const doc = readDocument(text);
190
+ const voice = voicesOf(doc.lines, doc.parts);
153
191
  const played = doc.parts.length > 1 || lined(doc.parts)
154
- ? playStreams(doc.lines, doc.parts, doc.parts)
155
- : expand(doc.lines);
192
+ ? playStreams(doc.lines, doc.parts, doc.parts, voice.voices)
193
+ : expand(doc.lines, undefined, 1, true, together(voice.voices.map((v) => v.sing)));
194
+ const [part = null] = doc.part ? withSings([doc.part], voice.all) : [];
156
195
  return {
157
196
  title: doc.title,
158
- part: doc.part,
159
- parts: doc.parts,
197
+ part,
198
+ parts: withSings(doc.parts, voice.all),
160
199
  credits: doc.credits,
161
200
  lines: doc.lines,
162
201
  events: played.events,
163
202
  bars: flattenBars(played.events),
164
203
  sections: played.sections,
165
- diagnostics: sortDiagnostics([...doc.diagnostics, ...played.diagnostics]),
204
+ diagnostics: sortDiagnostics([
205
+ ...doc.diagnostics,
206
+ ...voice.diagnostics,
207
+ ...played.diagnostics,
208
+ ...sungChecks(voice.voices),
209
+ ]),
166
210
  };
167
211
  }
168
212
  /** What an extract holds and plays: one of the part's lines, the part with its lines, or the part. */
169
- function extractOf(doc, part, lineName) {
213
+ function extractOf(doc, part, voices, lineName) {
170
214
  const label = part.label ?? "";
215
+ const sing = together(voices.map((v) => v.sing));
171
216
  if (lineName !== undefined) {
172
217
  const name = part.lines?.find((n) => n.toLowerCase() === lineName.toLowerCase());
173
- if (!name)
218
+ if (name === undefined)
174
219
  return null;
175
220
  const lines = projectPart(doc.lines, doc.parts, label, name);
176
- return { lines, played: expand(lines, `${label}.${name}`) };
221
+ return { lines, played: expand(lines, lineLabel(label, name), 1, true, sing) };
177
222
  }
178
223
  if (part.lines?.length)
179
224
  return {
180
225
  lines: projectPartLines(doc.lines, label),
181
- played: playStreams(doc.lines, doc.parts, [part]),
226
+ played: playStreams(doc.lines, doc.parts, [part], voices),
182
227
  };
183
228
  const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
184
- return { lines, played: expand(lines, part.label) };
229
+ return { lines, played: expand(lines, part.label, 1, true, sing) };
185
230
  }
186
231
  /**
187
232
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
188
233
  * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
189
234
  * one of the part's lines alone (grammar 7.6), as a converter writes each
190
235
  * line: the part's first line also plays its bare and tutti lines, and a
191
- * line rests where it isn't written. Null when the chart declares no part
236
+ * line rests where it isn't written. A part that writes its bare line
237
+ * beside its named lines makes it a line of its own (`lineName` `""`), and
238
+ * the named lines no longer play it. Null when the chart declares no part
192
239
  * with that label, or the part no line of that name. Never throws.
193
240
  */
194
241
  export function extractPart(text, label, lineName) {
195
242
  const doc = readDocument(text);
196
243
  const part = doc.parts.find((p) => p.label?.toLowerCase() === label.toLowerCase());
197
- const extract = part ? extractOf(doc, part, lineName) : null;
244
+ const voice = voicesOf(doc.lines, doc.parts);
245
+ const voices = part ? voicesIn(voice.voices, part, lineName) : [];
246
+ const extract = part ? extractOf(doc, part, voices, lineName) : null;
198
247
  if (!part || !extract)
199
248
  return null;
200
- const { lines, played } = extract;
249
+ const { played } = extract;
250
+ // The lyric rows are their owner's, or the chart's when no part sings (grammar 7.7).
251
+ const rows = voices.some((v) => v.singer === voice.owner);
252
+ const lines = rows ? extract.lines : extract.lines.filter((l) => l.kind !== "lyrics");
201
253
  const kept = new Set(lines.map((l) => l.line));
202
254
  // A stand-in may sit on another part's line; that part's problems are not this one's.
203
255
  for (const l of doc.lines)
@@ -205,16 +257,17 @@ export function extractPart(text, label, lineName) {
205
257
  kept.delete(l.line);
206
258
  return {
207
259
  title: doc.title,
208
- part,
209
- parts: [part],
260
+ part: withSings([part], voice.all)[0] ?? part,
261
+ parts: withSings([part], voice.all),
210
262
  credits: doc.credits,
211
263
  lines,
212
264
  events: played.events,
213
265
  bars: flattenBars(played.events),
214
266
  sections: played.sections,
215
267
  diagnostics: sortDiagnostics([
216
- ...doc.diagnostics.filter((d) => kept.has(d.line)),
268
+ ...[...doc.diagnostics, ...voice.diagnostics].filter((d) => kept.has(d.line)),
217
269
  ...played.diagnostics,
270
+ ...sungChecks(voices),
218
271
  ]),
219
272
  };
220
273
  }
@@ -41,12 +41,12 @@ function unlabelled(l) {
41
41
  return rest;
42
42
  }
43
43
  const plays = (l) => l?.kind === "bars" && !l.dropped;
44
- /** The stream's own line in a system, if written. */
44
+ /** The stream's own line in a system, if written; a bare line dropped from a part's lines is none of them (grammar 7.6). */
45
45
  const ownLine = (system, s) => system.find((m) => m.part?.toLowerCase() === s.key &&
46
46
  (s.name === null
47
47
  ? true
48
48
  : m.lineName === undefined
49
- ? s.first
49
+ ? s.first && !(m.kind === "bars" && m.dropped)
50
50
  : m.lineName.toLowerCase() === s.name.toLowerCase()));
51
51
  /** A tutti line as a stream other than its part's first hears it: tacet. */
52
52
  const restingTutti = (l) => l.kind === "bars" ? { ...l, cells: l.cells.map(standInCell) } : l;