barmark 0.15.0 → 0.17.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,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
+ }
@@ -9,7 +9,12 @@ export declare function zipEvents(each: ChartEvent[][], report: (d: ChartDiagnos
9
9
  export declare function parseChart(text: string): ChartParse;
10
10
  /**
11
11
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
12
- * its own bars, and `N.C.` marked `tacet` where it rests. Null when the
13
- * chart declares no part with that label. Never throws.
12
+ * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
13
+ * one of the part's lines alone (grammar 7.6), as a converter writes each
14
+ * line: the part's first line also plays its bare and tutti lines, and a
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
18
+ * with that label, or the part no line of that name. Never throws.
14
19
  */
15
- export declare function extractPart(text: string, label: string): ChartParse | null;
20
+ export declare function extractPart(text: string, label: string, lineName?: string): ChartParse | null;
@@ -1,6 +1,8 @@
1
1
  import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars } from "./expand.js";
3
- import { projectPart } from "./parts.js";
3
+ import { projectPart, projectPartLines } from "./parts.js";
4
+ import { pedalWarnings } from "./pedal.js";
5
+ import { together, voicesIn, voicesOf, withSings } from "./verses.js";
4
6
  const RANK = { error: 0, warning: 1 };
5
7
  /** Sorted by line, errors before warnings. */
6
8
  const sortDiagnostics = (all) => all.sort((a, b) => a.line - b.line || RANK[a.severity] - RANK[b.severity]);
@@ -20,9 +22,15 @@ function mergeReports(each) {
20
22
  }
21
23
  const partBar = (b) => b.tacet ? null : { line: b.line, slots: b.slots, ...(b.words && { words: b.words }) };
22
24
  const meterText = (b) => `${b.meter.n}/${b.meter.d}`;
23
- /** 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
+ */
24
31
  function zipBar(bars, report) {
25
32
  const [first, ...rest] = bars;
33
+ const lyrics = lyricsOf(bars);
26
34
  const playing = bars.filter((b) => !b.tacet);
27
35
  const meter = playing[0]?.meter ?? first.meter;
28
36
  const meters = [...new Set(playing.map(meterText))];
@@ -35,7 +43,13 @@ function zipBar(bars, report) {
35
43
  message: `the parts disagree on this bar's meter (${meters.join(", ")})`,
36
44
  token: "|",
37
45
  });
38
- 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
+ };
39
53
  }
40
54
  const lineOf = (e) => (e.kind === "bar" ? e.bar.line : e.line);
41
55
  /** The first event at which some part's timeline differs in shape from the lead's, or -1. */
@@ -78,41 +92,164 @@ export function zipEvents(each, report) {
78
92
  return e;
79
93
  });
80
94
  }
81
- /** Several parts: each projected and played, then zipped into one timeline (grammar 7.4). */
82
- function playParts(lines, parts) {
83
- const played = parts.map((p) => expand(projectPart(lines, parts, p.label ?? ""), p.label, parts.length));
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);
97
+ const streamsOf = (shown) => shown.flatMap((p, part) => p.lines?.length
98
+ ? p.lines.map((name) => ({ part, label: p.label ?? "", name }))
99
+ : [{ part, label: p.label ?? "", name: null }]);
100
+ /** A part's share of a bar from its streams' shares: its first playing line leads (grammar 7.6). */
101
+ function partOf(p, own) {
102
+ const playing = own.filter((e) => e[1] !== null);
103
+ const lead = playing[0]?.[1];
104
+ if (!lead)
105
+ return null;
106
+ if (!p.lines?.length)
107
+ return lead;
108
+ const lines = playing.map(([s, b]) => ({
109
+ name: s.name ?? "",
110
+ line: b.line,
111
+ slots: b.slots,
112
+ ...(b.words && { words: b.words }),
113
+ }));
114
+ return { ...lead, lines };
115
+ }
116
+ /** A zipped bar of streams as a bar of parts; with one part shown, its lines sit on the bar itself. */
117
+ function foldBar(bar, streams, shown) {
118
+ const each = bar.parts ?? [];
119
+ const parts = shown.map((p, i) => partOf(p, streams.flatMap((s, j) => (s.part === i ? [[s, each[j] ?? null]] : []))));
120
+ const { parts: _p, words: _w, tacet: _t, ...shared } = bar;
121
+ const lead = parts[0];
122
+ const top = lead
123
+ ? { ...shared, line: lead.line, slots: lead.slots, ...(lead.words && { words: lead.words }) }
124
+ : bar;
125
+ if (shown.length > 1)
126
+ return { ...top, parts };
127
+ const { parts: _q, ...alone } = top;
128
+ return lead?.lines ? { ...alone, lines: lead.lines } : alone;
129
+ }
130
+ function foldEvents(events, streams, shown) {
131
+ return events.map((e) => {
132
+ if (e.kind === "bar")
133
+ return { kind: "bar", bar: foldBar(e.bar, streams, shown) };
134
+ if (e.kind === "open")
135
+ return { ...e, events: foldEvents(e.events, streams, shown) };
136
+ return e;
137
+ });
138
+ }
139
+ /** A part's own bars from a folded bar: tacet where none of its lines plays. */
140
+ function partView(b, i, shown) {
141
+ if (shown === 1)
142
+ return b;
143
+ const own = b.parts?.[i];
144
+ return own ? { ...b, line: own.line, slots: own.slots } : { ...b, slots: [], tacet: true };
145
+ }
146
+ /** The pedal warnings of each part that writes lines, walked on the part, not one line (grammar 2.9, 7.6). */
147
+ function linedPedalWarnings(events, shown) {
148
+ const bars = flattenBars(events);
149
+ return shown.flatMap((p, i) => p.lines?.length ? pedalWarnings(bars.map((b) => partView(b, i, shown.length))) : []);
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
+ }
164
+ /**
165
+ * Parts and their lines: each stream projected and played, zipped into one
166
+ * timeline, then folded into the parts shown (grammar 7.4, 7.6). With a
167
+ * voice, the stream that sings takes the words.
168
+ */
169
+ function playStreams(lines, parts, shown, voices) {
170
+ const streams = streamsOf(shown);
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]));
84
173
  const diagnostics = mergeReports(played.map((p) => p.diagnostics));
85
- const events = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
174
+ const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
175
+ const events = foldEvents(zipped, streams, shown);
176
+ diagnostics.push(...linedPedalWarnings(events, shown));
86
177
  return { events, sections: played[0]?.sections ?? [], diagnostics };
87
178
  }
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
+ }
88
187
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
89
188
  export function parseChart(text) {
90
189
  const doc = readDocument(text);
91
- const played = doc.parts.length > 1 ? playParts(doc.lines, doc.parts) : expand(doc.lines);
190
+ const voice = voicesOf(doc.lines, doc.parts);
191
+ const played = doc.parts.length > 1 || lined(doc.parts)
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) : [];
92
195
  return {
93
196
  title: doc.title,
94
- part: doc.part,
95
- parts: doc.parts,
197
+ part,
198
+ parts: withSings(doc.parts, voice.all),
96
199
  credits: doc.credits,
97
200
  lines: doc.lines,
98
201
  events: played.events,
99
202
  bars: flattenBars(played.events),
100
203
  sections: played.sections,
101
- diagnostics: sortDiagnostics([...doc.diagnostics, ...played.diagnostics]),
204
+ diagnostics: sortDiagnostics([
205
+ ...doc.diagnostics,
206
+ ...voice.diagnostics,
207
+ ...played.diagnostics,
208
+ ...sungChecks(voice.voices),
209
+ ]),
102
210
  };
103
211
  }
212
+ /** What an extract holds and plays: one of the part's lines, the part with its lines, or the part. */
213
+ function extractOf(doc, part, voices, lineName) {
214
+ const label = part.label ?? "";
215
+ const sing = together(voices.map((v) => v.sing));
216
+ if (lineName !== undefined) {
217
+ const name = part.lines?.find((n) => n.toLowerCase() === lineName.toLowerCase());
218
+ if (name === undefined)
219
+ return null;
220
+ const lines = projectPart(doc.lines, doc.parts, label, name);
221
+ return { lines, played: expand(lines, lineLabel(label, name), 1, true, sing) };
222
+ }
223
+ if (part.lines?.length)
224
+ return {
225
+ lines: projectPartLines(doc.lines, label),
226
+ played: playStreams(doc.lines, doc.parts, [part], voices),
227
+ };
228
+ const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
229
+ return { lines, played: expand(lines, part.label, 1, true, sing) };
230
+ }
104
231
  /**
105
232
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
106
- * its own bars, and `N.C.` marked `tacet` where it rests. Null when the
107
- * chart declares no part with that label. Never throws.
233
+ * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
234
+ * one of the part's lines alone (grammar 7.6), as a converter writes each
235
+ * line: the part's first line also plays its bare and tutti lines, and a
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
239
+ * with that label, or the part no line of that name. Never throws.
108
240
  */
109
- export function extractPart(text, label) {
241
+ export function extractPart(text, label, lineName) {
110
242
  const doc = readDocument(text);
111
243
  const part = doc.parts.find((p) => p.label?.toLowerCase() === label.toLowerCase());
112
- if (!part)
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;
247
+ if (!part || !extract)
113
248
  return null;
114
- const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
115
- const played = expand(lines, part.label);
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");
116
253
  const kept = new Set(lines.map((l) => l.line));
117
254
  // A stand-in may sit on another part's line; that part's problems are not this one's.
118
255
  for (const l of doc.lines)
@@ -120,16 +257,17 @@ export function extractPart(text, label) {
120
257
  kept.delete(l.line);
121
258
  return {
122
259
  title: doc.title,
123
- part,
124
- parts: [part],
260
+ part: withSings([part], voice.all)[0] ?? part,
261
+ parts: withSings([part], voice.all),
125
262
  credits: doc.credits,
126
263
  lines,
127
264
  events: played.events,
128
265
  bars: flattenBars(played.events),
129
266
  sections: played.sections,
130
267
  diagnostics: sortDiagnostics([
131
- ...doc.diagnostics.filter((d) => kept.has(d.line)),
268
+ ...[...doc.diagnostics, ...voice.diagnostics].filter((d) => kept.has(d.line)),
132
269
  ...played.diagnostics,
270
+ ...sungChecks(voices),
133
271
  ]),
134
272
  };
135
273
  }
@@ -0,0 +1,3 @@
1
+ import type { Part } from "./types.js";
2
+ /** A `part:` line's label, name and attributes, or why it has none (grammar 7.3). */
3
+ export declare function readPart(text: string): Part | string | null;
@@ -0,0 +1,73 @@
1
+ import { DIRECTIVE_AFTER } from "./directives.js";
2
+ import { CLEF_NAMES, instrumentInfo, nearInstruments, } from "./instruments.js";
3
+ /** A `part:` line's label, name and attributes, or why it has none (grammar 7.3). */
4
+ export function readPart(text) {
5
+ const m = /^part\s*:(.*)$/i.exec(text);
6
+ if (!m)
7
+ return null;
8
+ const found = splitAttributes((m[1] ?? "").trim().replace(/\s+/g, " "));
9
+ if (typeof found === "string")
10
+ return found;
11
+ const attributes = readAttributes(found.attributes);
12
+ if (typeof attributes === "string")
13
+ return attributes;
14
+ const named = readName(found.value);
15
+ return typeof named === "string" ? named : { ...named, ...attributes };
16
+ }
17
+ /** The label and name before any attributes. */
18
+ function readName(value) {
19
+ if (DIRECTIVE_AFTER.test(value))
20
+ return "part: goes on a line of its own; the name runs to the end of the line";
21
+ const labelled = /^([^\s=]*)\s*=\s*(.*)$/.exec(value);
22
+ if (!labelled)
23
+ return value ? { name: value } : "part: needs a name";
24
+ const [, label, name] = labelled;
25
+ if (!label)
26
+ return "part: needs a label before =";
27
+ if (/^[|#@0-9]/.test(label))
28
+ return "a part label can't start with |, #, @ or a digit";
29
+ return name ? { label, name } : "part: needs a name after the label";
30
+ }
31
+ const ATTRIBUTE = /,\s*(instrument|clef)\s*:\s*([^,]*)$/i;
32
+ /** `, instrument: …` and `, clef: …` peeled off the end of the line, in either order. */
33
+ function splitAttributes(text) {
34
+ let value = text;
35
+ const attributes = new Map();
36
+ for (let m = ATTRIBUTE.exec(value); m; m = ATTRIBUTE.exec(value)) {
37
+ const name = (m[1] ?? "").toLowerCase();
38
+ if (attributes.has(name))
39
+ return `part: names its ${name} once`;
40
+ attributes.set(name, (m[2] ?? "").trim());
41
+ value = value.slice(0, m.index).trim();
42
+ }
43
+ return { value, attributes };
44
+ }
45
+ /** The instrument and clef written, each checked against its list. */
46
+ function readAttributes(written) {
47
+ const instrument = readInstrument(written.get("instrument"));
48
+ if (typeof instrument === "string")
49
+ return instrument;
50
+ const clef = written.get("clef")?.toLowerCase();
51
+ if (clef === undefined)
52
+ return instrument ? { instrument: instrument.name } : {};
53
+ const problem = clefProblem(clef, instrument?.staves ?? 1);
54
+ if (problem)
55
+ return problem;
56
+ return { ...(instrument && { instrument: instrument.name }), clef: clef };
57
+ }
58
+ /** The listed instrument written, null when none is, or why it isn't one. */
59
+ function readInstrument(name) {
60
+ if (name === undefined)
61
+ return null;
62
+ return instrumentInfo(name) ?? unknownInstrument(name);
63
+ }
64
+ function clefProblem(clef, staves) {
65
+ if (!CLEF_NAMES.includes(clef))
66
+ return `${clef || "an empty clef"} is not a clef; write ${CLEF_NAMES.join(", ")}`;
67
+ return staves === 2 ? "a keyboard has a treble and a bass staff; leave clef: out" : null;
68
+ }
69
+ function unknownInstrument(name) {
70
+ const near = nearInstruments(name);
71
+ const hint = near.length ? `: did you mean ${near.join(" or ")}?` : "";
72
+ return `${name || "an empty name"} is not an instrument barmark knows${hint}`;
73
+ }
@@ -1,7 +1,12 @@
1
- import type { Line, Part } from "./types.js";
1
+ import type { DeclaredPart, Line } from "./types.js";
2
2
  /**
3
3
  * One part of a multi-part chart as a single-part chart's lines (grammar
4
4
  * 7.4): the tutti lines, the part's own lines, and a bar of `N.C.` marked
5
- * `tacet` for each bar of a system it doesn't play. Never throws.
5
+ * `tacet` for each bar of a system it doesn't play. With `lineName`, one
6
+ * of the part's lines (grammar 7.6): the part's first line also plays
7
+ * its bare lines and the tutti lines, and a line rests (tacet) wherever
8
+ * it isn't written. Never throws.
6
9
  */
7
- export declare function projectPart(lines: Line[], parts: Part[], label: string): Line[];
10
+ export declare function projectPart(lines: Line[], parts: DeclaredPart[], label: string, lineName?: string | null): Line[];
11
+ /** One part's lines kept as written, labels and all, with a stand-in for each system it doesn't play: what an extract prints (grammar 7.6). */
12
+ export declare function projectPartLines(lines: Line[], label: string): Line[];
@@ -34,13 +34,22 @@ function standIn(system, at) {
34
34
  /** A part's own line, as a single-part chart writes it. */
35
35
  function unlabelled(l) {
36
36
  if (l.kind === "invalid") {
37
- const { part: _p, system: _s, ...rest } = l;
37
+ const { part: _p, lineName: _n, system: _s, ...rest } = l;
38
38
  return rest;
39
39
  }
40
- const { part: _p, system: _s, dropped: _d, ...rest } = l;
40
+ const { part: _p, lineName: _n, system: _s, dropped: _d, ...rest } = l;
41
41
  return rest;
42
42
  }
43
- const plays = (l, key) => l.part?.toLowerCase() === key && l.kind === "bars" && !l.dropped;
43
+ const plays = (l) => l?.kind === "bars" && !l.dropped;
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
+ const ownLine = (system, s) => system.find((m) => m.part?.toLowerCase() === s.key &&
46
+ (s.name === null
47
+ ? true
48
+ : m.lineName === undefined
49
+ ? s.first && !(m.kind === "bars" && m.dropped)
50
+ : m.lineName.toLowerCase() === s.name.toLowerCase()));
51
+ /** A tutti line as a stream other than its part's first hears it: tacet. */
52
+ const restingTutti = (l) => l.kind === "bars" ? { ...l, cells: l.cells.map(standInCell) } : l;
44
53
  const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
45
54
  function systemsOf(lines) {
46
55
  const systems = new Map();
@@ -49,16 +58,18 @@ function systemsOf(lines) {
49
58
  systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
50
59
  return systems;
51
60
  }
52
- /** What one line becomes in the part's chart: itself, its unlabelled self, a stand-in, or nothing. */
53
- function projectLine(l, key, systems) {
61
+ /** What one line becomes in the stream's chart: itself, its unlabelled self, a stand-in, or nothing. */
62
+ function projectLine(l, s, systems) {
54
63
  if (l.kind === "part")
55
- return l.label?.toLowerCase() === key ? l : null;
56
- return inSystem(l) ? projectSystemLine(l, key, systems.get(l.system) ?? []) : l;
64
+ return l.label?.toLowerCase() === s.key ? l : null;
65
+ if (inSystem(l))
66
+ return projectSystemLine(l, s, systems.get(l.system) ?? []);
67
+ return s.first ? l : restingTutti(l);
57
68
  }
58
- /** A system's line in one part's chart: the part's own line, a stand-in where it rests, or nothing. */
59
- function projectSystemLine(l, key, system) {
60
- const own = system.find((m) => m.part?.toLowerCase() === key);
61
- if (own === l && plays(l, key))
69
+ /** A system's line in one stream's chart: its own line, a stand-in where it rests, or nothing. */
70
+ function projectSystemLine(l, s, system) {
71
+ const own = ownLine(system, s);
72
+ if (own === l && plays(l))
62
73
  return unlabelled(l);
63
74
  const at = own ?? referenceOf(system) ?? system[0];
64
75
  return at === l ? standIn(system, l) : null;
@@ -66,12 +77,37 @@ function projectSystemLine(l, key, system) {
66
77
  /**
67
78
  * One part of a multi-part chart as a single-part chart's lines (grammar
68
79
  * 7.4): the tutti lines, the part's own lines, and a bar of `N.C.` marked
69
- * `tacet` for each bar of a system it doesn't play. Never throws.
80
+ * `tacet` for each bar of a system it doesn't play. With `lineName`, one
81
+ * of the part's lines (grammar 7.6): the part's first line also plays
82
+ * its bare lines and the tutti lines, and a line rests (tacet) wherever
83
+ * it isn't written. Never throws.
70
84
  */
71
- export function projectPart(lines, parts, label) {
85
+ export function projectPart(lines, parts, label, lineName = null) {
72
86
  if (!parts.length)
73
87
  return lines;
74
88
  const key = label.toLowerCase();
89
+ const part = parts.find((p) => p.label?.toLowerCase() === key);
90
+ const first = part?.lines?.[0];
91
+ const s = { key, name: lineName, first: lineName === null || lineName === first };
75
92
  const systems = systemsOf(lines);
76
- return lines.map((l) => projectLine(l, key, systems)).filter((l) => l !== null);
93
+ return lines.map((l) => projectLine(l, s, systems)).filter((l) => l !== null);
94
+ }
95
+ /** One part's lines kept as written, labels and all, with a stand-in for each system it doesn't play: what an extract prints (grammar 7.6). */
96
+ export function projectPartLines(lines, label) {
97
+ const key = label.toLowerCase();
98
+ const systems = systemsOf(lines);
99
+ return lines
100
+ .map((l) => {
101
+ if (l.kind === "part")
102
+ return l.label?.toLowerCase() === key ? l : null;
103
+ if (!inSystem(l))
104
+ return l;
105
+ const system = systems.get(l.system) ?? [];
106
+ const own = system.filter((m) => m.part?.toLowerCase() === key);
107
+ if (own.length)
108
+ return own.includes(l) ? l : null;
109
+ const at = referenceOf(system) ?? system[0];
110
+ return at === l ? standIn(system, l) : null;
111
+ })
112
+ .filter((l) => l !== null);
77
113
  }
@@ -0,0 +1,5 @@
1
+ import type { ChartDiagnostic, PlayedBar } from "./types.js";
2
+ /** Whether the pedal is down at the end of each slot of each bar, in play order. The chart's end lifts it. */
3
+ export declare function pedalStates(bars: PlayedBar[]): boolean[][];
4
+ /** A warning for each `*` played with the pedal already up, once per line. */
5
+ export declare function pedalWarnings(bars: PlayedBar[]): ChartDiagnostic[];