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.
@@ -1,7 +1,10 @@
1
1
  import { parseChord } from "../chords/parse.js";
2
2
  import { misplacedRepeat, parseBarLine, readRepeat, repeatTail } from "./barLine.js";
3
3
  import { creditsOf, nearCredit, readCredit } from "./credits.js";
4
- import { DIRECTIVE_AFTER, parseDirectiveLine } from "./directives.js";
4
+ import { parseDirectiveLine } from "./directives.js";
5
+ import { checkLines } from "./lines.js";
6
+ import { attachLyrics, readLyricRow } from "./lyricRows.js";
7
+ import { readPart } from "./partLine.js";
5
8
  import { groupSystems } from "./systems.js";
6
9
  const NEAR_DIRECTIVES = {
7
10
  meter: "time",
@@ -11,24 +14,6 @@ const NEAR_DIRECTIVES = {
11
14
  instrument: "part",
12
15
  parts: "part",
13
16
  };
14
- /** A `part:` line's label and name, or why it has none (grammar 7.3). */
15
- function readPart(text) {
16
- const m = /^part\s*:(.*)$/i.exec(text);
17
- if (!m)
18
- return null;
19
- const value = (m[1] ?? "").trim().replace(/\s+/g, " ");
20
- if (DIRECTIVE_AFTER.test(value))
21
- return "part: goes on a line of its own; the name runs to the end of the line";
22
- const labelled = /^([^\s=]*)\s*=\s*(.*)$/.exec(value);
23
- if (!labelled)
24
- return value ? { name: value } : "part: needs a name";
25
- const [, label, name] = labelled;
26
- if (!label)
27
- return "part: needs a label before =";
28
- if (/^[|#@0-9]/.test(label))
29
- return "a part label can't start with |, #, @ or a digit";
30
- return name ? { label, name } : "part: needs a name after the label";
31
- }
32
17
  /**
33
18
  * Several parts each need a label, and no two may share one in any case
34
19
  * (grammar 7.4). A part that breaks either rule is text, with the error.
@@ -51,7 +36,12 @@ function checkParts(lines, diagnostics) {
51
36
  }
52
37
  return parts;
53
38
  }
54
- const partOf = (l) => (l.label ? { label: l.label, name: l.name } : { name: l.name });
39
+ const partOf = (l) => ({
40
+ ...(l.label && { label: l.label }),
41
+ name: l.name,
42
+ ...(l.instrument && { instrument: l.instrument }),
43
+ ...(l.clef && { clef: l.clef }),
44
+ });
55
45
  function partProblem(l, seen) {
56
46
  if (!l.label)
57
47
  return {
@@ -102,7 +92,25 @@ function readHeading(text, line, diagnostics) {
102
92
  });
103
93
  return { kind: "section", line, name: rest, repeat, elided };
104
94
  }
95
+ /** A declared label written before a bar line, exactly, or a part's label, a dot and a line's name (grammar 7.6). */
96
+ function findLabel(word, declared) {
97
+ const match = (w) => declared.find((p) => p.label?.toLowerCase() === w.toLowerCase())?.label;
98
+ const exact = match(word);
99
+ if (exact)
100
+ return { part: exact };
101
+ const dot = word.lastIndexOf(".");
102
+ const label = dot > 0 ? match(word.slice(0, dot)) : undefined;
103
+ return label ? { part: label, lineName: word.slice(dot + 1) } : null;
104
+ }
105
+ /** The word before a bar line, whether a space follows it, and the bar line. */
106
+ function splitLabel(t) {
107
+ const m = LABELLED.exec(t);
108
+ return m ? { word: m[1] ?? "", space: Boolean(m[2]), rest: m[3] ?? "" } : null;
109
+ }
110
+ const LINE_NAME = /^[A-Za-z0-9]+$/;
105
111
  /** A label and the bar line after it: `Gtr | G |` (grammar 7.4). */
112
+ /** Three or more hyphens alone: `---` ends a system (grammar 1, 7.4). */
113
+ const BREAK = /^-{3,}$/;
106
114
  const LABELLED = /^([^\s|]+)(\s*)(\|.*)$/;
107
115
  const readsCleanly = (barLine) => {
108
116
  const read = parseBarLine(barLine, 0);
@@ -183,7 +191,7 @@ function escapedBarLine(text) {
183
191
  function noBarLines(lines) {
184
192
  if (lines.some((l) => l.kind === "bars" || l.kind === "invalid"))
185
193
  return null;
186
- const first = lines.find((l) => l.kind === "text");
194
+ const first = lines.find((l) => l.kind === "text" && !l.escaped);
187
195
  if (first?.kind !== "text")
188
196
  return null;
189
197
  return {
@@ -193,6 +201,22 @@ function noBarLines(lines) {
193
201
  token: first.text,
194
202
  };
195
203
  }
204
+ /** A part's bare line in a single-part chart with no lines is unlabelled, as before (grammar 7.4). */
205
+ function unlabelled(l) {
206
+ if (l.kind !== "bars" && l.kind !== "invalid")
207
+ return l;
208
+ const { part: _p, ...rest } = l;
209
+ return rest;
210
+ }
211
+ /** Systems and part lines, when the chart has several parts or a part writes lines (grammar 7.4, 7.6). */
212
+ function groupParts(lines, parts) {
213
+ const lined = lines.some((l) => (l.kind === "bars" || l.kind === "invalid") && l.lineName !== undefined);
214
+ if (parts.length < 2 && !lined)
215
+ return { lines: lines.map(unlabelled), parts, diagnostics: [] };
216
+ const systems = groupSystems(lines);
217
+ const checked = checkLines(systems.lines, parts);
218
+ return { ...checked, diagnostics: [...systems.diagnostics, ...checked.diagnostics] };
219
+ }
196
220
  /** Classify every line of a chart: title, sections, directives, bar lines and text. */
197
221
  export function readDocument(text) {
198
222
  const lines = [];
@@ -239,39 +263,57 @@ export function readDocument(text) {
239
263
  diagnostics.push(...r.diagnostics);
240
264
  return r.bars ?? { kind: "invalid", line, text: t, written: r.written };
241
265
  };
242
- /** A declared part's bar line; labelled only when the chart has several parts. */
266
+ const declaredParts = () => lines.filter((l) => l.kind === "part");
267
+ /** A labelled line that can't be read: no space before its pipe, or a bad line name. */
268
+ const badLabel = (t, line, word, rest, owner) => {
269
+ const space = t.length > word.length + rest.length;
270
+ diagnostics.push({
271
+ line,
272
+ severity: "error",
273
+ message: space ? "a line name is letters and digits" : "a space goes between the label and |",
274
+ token: t,
275
+ ...(!space && { suggestion: `${word} ${rest}` }),
276
+ });
277
+ return { kind: "invalid", line, text: t, written: parseBarLine(rest, line).written, ...owner };
278
+ };
279
+ /** A declared part's bar line, or one of its lines (`Pno.RH`, grammar 7.6). */
243
280
  const labelledLine = (t, line) => {
244
- const m = LABELLED.exec(t);
245
- const declared = lines.filter((l) => l.kind === "part");
246
- const found = declared.find((p) => p.label?.toLowerCase() === m?.[1]?.toLowerCase());
247
- if (!m || !found?.label)
281
+ const split = splitLabel(t);
282
+ const owner = split && findLabel(split.word, declaredParts());
283
+ if (!split || !owner)
248
284
  return null;
249
- const [, word = "", space, rest = ""] = m;
250
- if (!space) {
251
- diagnostics.push({
252
- line,
253
- severity: "error",
254
- message: "a space goes between the label and |",
255
- token: t,
256
- suggestion: `${word} ${rest}`,
257
- });
258
- const written = parseBarLine(rest, line).written;
259
- return {
260
- kind: "invalid",
261
- line,
262
- text: t,
263
- written,
264
- ...(declared.length > 1 && { part: found.label }),
265
- };
266
- }
285
+ const { word, space, rest } = split;
286
+ if (!space || !LINE_NAME.test(owner.lineName ?? "X"))
287
+ return badLabel(t, line, word, rest, owner);
267
288
  const read = barLine(rest, line);
268
- if (declared.length < 2 || (read.kind !== "bars" && read.kind !== "invalid"))
269
- return read;
270
- return { ...read, part: found.label };
289
+ return read.kind === "bars" || read.kind === "invalid" ? { ...read, ...owner } : read;
290
+ };
291
+ /** A leading `\` makes the rest text, whatever it looks like (grammar 1). */
292
+ const escapedLine = (t, line) => {
293
+ const text = t.slice(1);
294
+ const old = oldFormat(text, line);
295
+ if (old)
296
+ diagnostics.push(old);
297
+ return { kind: "text", line, text, escaped: true };
298
+ };
299
+ /** `lyrics:` or `lyrics N:` then a bar line (grammar 7.7); one with an error stays text. */
300
+ const lyricRow = (t, line) => {
301
+ const read = readLyricRow(t, line);
302
+ diagnostics.push(...read.diagnostics);
303
+ if (read.row || read.diagnostics.length)
304
+ return read.row ?? { kind: "text", line, text: t };
305
+ return null;
271
306
  };
272
307
  const classify = (t, line) => {
308
+ if (BREAK.test(t))
309
+ return { kind: "break", line };
310
+ if (t.startsWith("\\"))
311
+ return escapedLine(t, line);
273
312
  if (t.startsWith("|"))
274
313
  return barLine(t, line);
314
+ const row = lyricRow(t, line);
315
+ if (row)
316
+ return row;
275
317
  const labelled = labelledLine(t, line);
276
318
  if (labelled)
277
319
  return labelled;
@@ -292,15 +334,17 @@ export function readDocument(text) {
292
334
  const empty = noBarLines(lines);
293
335
  if (empty)
294
336
  diagnostics.push(empty);
295
- const parts = checkParts(lines, diagnostics);
296
- const grouped = parts.length > 1 ? groupSystems(lines) : { lines, diagnostics: [] };
297
- diagnostics.push(...grouped.diagnostics);
337
+ const read = checkParts(lines, diagnostics);
338
+ const grouped = groupParts(lines, read);
339
+ const lyrics = attachLyrics(grouped.lines);
340
+ diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics);
341
+ const { parts } = grouped;
298
342
  return {
299
343
  title,
300
344
  part: parts.length === 1 ? (parts[0] ?? null) : null,
301
345
  parts,
302
346
  credits: creditsOf(lines),
303
- lines: grouped.lines,
347
+ lines: lyrics.lines,
304
348
  diagnostics,
305
349
  };
306
350
  }
@@ -1,4 +1,18 @@
1
1
  import type { ChartDiagnostic, ChartEvent, Line, PlayedBar, SectionOccurrence } from "./types.js";
2
+ /**
3
+ * Where a played bar comes from, for its words (grammar 7.7): its bar
4
+ * line, its place among that line's bars (from 0), the pass of the repeat
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.
7
+ */
8
+ export type BarSource = {
9
+ line: number;
10
+ bar: number;
11
+ pass: number | null;
12
+ replay: number | null;
13
+ };
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"];
2
16
  /** Nested repeats multiply; expansion stops here rather than run away. */
3
17
  export declare const MAX_EXPANDED_BARS = 10000;
4
18
  /** Every played bar in order, with an open repeat's pass included once. */
@@ -11,7 +25,11 @@ export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
11
25
  * `label` names the part a projected chart is (grammar 7.4), for its
12
26
  * messages; `share` is how many parts split the expansion budget.
13
27
  */
14
- export declare function expand(lines: Line[], label?: string, share?: number): {
28
+ export declare function expand(lines: Line[], label?: string, share?: number,
29
+ /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
30
+ pedal?: boolean,
31
+ /** The words each bar sings, for the line that sings them (grammar 7.7). */
32
+ sing?: Sing): {
15
33
  events: ChartEvent[];
16
34
  sections: SectionOccurrence[];
17
35
  diagnostics: ChartDiagnostic[];
@@ -1,8 +1,18 @@
1
1
  import { planJump } from "./direction.js";
2
2
  import { beatsOf } from "./directives.js";
3
+ import { pedalWarnings } from "./pedal.js";
3
4
  import { pairRepeats } from "./repeats.js";
5
+ import { slotTimes } from "./shares.js";
4
6
  /** Nested repeats multiply; expansion stops here rather than run away. */
5
7
  export const MAX_EXPANDED_BARS = 10_000;
8
+ /** A slot without its syllable: `%` copies a bar's notes, not its words (grammar 4.3). */
9
+ const unsungSimple = (s) => {
10
+ if (s.kind !== "chord" || !s.syllable)
11
+ return s;
12
+ const { syllable: _, ...rest } = s;
13
+ return rest;
14
+ };
15
+ const unsung = (s) => s.kind === "group" ? { ...s, members: s.members.map(unsungSimple) } : unsungSimple(s);
6
16
  /**
7
17
  * How each mark moves play along. A mark the jump does not use is an error
8
18
  * that drops the jump, so with a jump planned every mark here applies.
@@ -27,13 +37,6 @@ function uneven(slots, meter, line) {
27
37
  }
28
38
  const PUSH_MARKS = { eighth: "<", sixteenth: "<<" };
29
39
  const PUSH_LENGTH = { eighth: 1 / 8, sixteenth: 1 / 16 };
30
- /** Each simple slot of a bar, in order, with how long it lasts in whole notes. */
31
- function timed(bar) {
32
- const each = bar.meter.n / bar.meter.d / bar.slots.length;
33
- return bar.slots.flatMap((s) => s.kind === "group"
34
- ? s.members.map((m) => ({ slot: m, length: each / s.members.length }))
35
- : [{ slot: s, length: each }]);
36
- }
37
40
  /** Why a push can't take its time from a slot this long; null when it can. */
38
41
  function pushProblem(push, before) {
39
42
  if (before === null)
@@ -81,7 +84,11 @@ function removeLastBar(events) {
81
84
  * `label` names the part a projected chart is (grammar 7.4), for its
82
85
  * messages; `share` is how many parts split the expansion budget.
83
86
  */
84
- export function expand(lines, label, share = 1) {
87
+ export function expand(lines, label, share = 1,
88
+ /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
89
+ pedal = true,
90
+ /** The words each bar sings, for the line that sings them (grammar 7.7). */
91
+ sing) {
85
92
  const diagnostics = [];
86
93
  const maxBars = Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
87
94
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
@@ -132,8 +139,8 @@ export function expand(lines, label, share = 1) {
132
139
  else if (previous.tacet)
133
140
  tacetBefore(line, "% has nothing to copy");
134
141
  const meter = previous?.meter ?? null;
135
- const slots = previous?.slots ?? [{ kind: "hold" }];
136
- return marked({ kind: "bar", meter, slots, own: false, written: ++written }, c.words);
142
+ const slots = previous?.slots.map(unsung) ?? [{ kind: "hold" }];
143
+ return marked({ kind: "bar", meter, slots, own: false, written: ++written, bar: 0 }, c.words);
137
144
  };
138
145
  /** A bar that opens with `/` holds what was sounding before it. */
139
146
  const checkHold = (c, line) => {
@@ -155,6 +162,7 @@ export function expand(lines, label, share = 1) {
155
162
  slots: c.slots,
156
163
  own: true,
157
164
  written: ++written,
165
+ bar: 0,
158
166
  ...(c.tacet && { tacet: c.tacet }),
159
167
  };
160
168
  return marked(bar, c.words);
@@ -173,7 +181,11 @@ export function expand(lines, label, share = 1) {
173
181
  written += l.written;
174
182
  if (l.kind !== "bars")
175
183
  continue;
176
- resolved.set(l, l.cells.map((c) => resolveCell(c, l.line)).filter((p) => p !== null));
184
+ let bar = 0;
185
+ resolved.set(l, l.cells
186
+ .map((c) => resolveCell(c, l.line))
187
+ .filter((p) => p !== null)
188
+ .map((p) => (p.kind === "bar" ? { ...p, bar: bar++ } : p)));
177
189
  }
178
190
  const unused = pending.mark;
179
191
  if (unused)
@@ -238,6 +250,8 @@ export function expand(lines, label, share = 1) {
238
250
  error(line, `expansion stopped at ${maxBars} bars`, "x");
239
251
  };
240
252
  let sectionName = null;
253
+ /** 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 };
241
255
  let phase = "main";
242
256
  const stopped = () => capped || phase === "jumped" || phase === "done";
243
257
  const jumped = () => phase === "jumped";
@@ -274,12 +288,18 @@ export function expand(lines, label, share = 1) {
274
288
  ...(p.tacet && { tacet: p.tacet }),
275
289
  };
276
290
  };
291
+ /** The bar with the words it sings here, if any (grammar 7.7). */
292
+ const sung = (bar, p, line) => {
293
+ const lyrics = sing?.(bar, { line, bar: p.bar, ...where });
294
+ return lyrics ? { ...bar, lyrics } : bar;
295
+ };
277
296
  /** How long the slot played just before is, in whole notes; null after a fermata or at the start. */
278
297
  const before = { length: null };
279
298
  const pushReported = new Set();
280
299
  /** Each push takes its time from the slot played just before it (grammar 2.8). */
281
300
  const checkPushes = (bar) => {
282
- for (const { slot, length } of timed(bar)) {
301
+ const timed = slotTimes(bar.slots, bar.meter);
302
+ for (const { slot, length } of timed) {
283
303
  const problem = slot.push && pushProblem(slot.push, before.length);
284
304
  const key = `${bar.line}\u0000${problem}`;
285
305
  if (problem && !pushReported.has(key)) {
@@ -307,7 +327,7 @@ export function expand(lines, label, share = 1) {
307
327
  count++;
308
328
  const bar = barOf(p, line);
309
329
  checkPushes(bar);
310
- out.push({ kind: "bar", bar });
330
+ out.push({ kind: "bar", bar: sung(bar, p, line) });
311
331
  };
312
332
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
313
333
  const times = (repeat, line, out, body) => {
@@ -327,12 +347,19 @@ export function expand(lines, label, share = 1) {
327
347
  return;
328
348
  }
329
349
  // After the jump every repeat plays once.
330
- const passes = phase === "main" ? (repeat ?? 1) : 1;
331
- for (let i = 0; i < passes && !stopped(); i++) {
350
+ passes(phase === "main" ? (repeat ?? 1) : 1, repeat !== null, line, () => body(out));
351
+ };
352
+ /** Play `n` passes; a repeat's are numbered for the words (grammar 7.7), a plain line's are not. */
353
+ const passes = (n, counted, line, play) => {
354
+ const outer = where.pass;
355
+ for (let i = 0; i < n && !stopped(); i++) {
332
356
  if (++work > maxWork)
333
357
  return stop(line);
334
- body(out);
358
+ if (counted)
359
+ where.pass = i + 1;
360
+ play();
335
361
  }
362
+ where.pass = outer;
336
363
  };
337
364
  const playLine = ({ line: l, repeat }, out) => {
338
365
  if (stopped())
@@ -363,15 +390,19 @@ export function expand(lines, label, share = 1) {
363
390
  const playEndings = (it, out) => {
364
391
  const highest = typeof it.repeat === "number" ? it.repeat : 1;
365
392
  const first = phase === "main" ? 1 : highest;
393
+ const outer = where.pass;
366
394
  for (let pass = first; pass <= highest && !stopped(); pass++) {
367
395
  if (++work > maxWork)
368
396
  return stop(it.line);
397
+ // The return after a jump is no new pass: it plays pass 1's words (grammar 7.7).
398
+ where.pass = phase === "main" ? pass : 1;
369
399
  for (const e of it.entries)
370
400
  playLine(e, out);
371
401
  const ending = it.endings.find((x) => x.passes.includes(pass));
372
402
  if (ending)
373
403
  playLine(ending.entry, out);
374
404
  }
405
+ where.pass = outer;
375
406
  };
376
407
  const events = [];
377
408
  const occurrences = [];
@@ -403,7 +434,9 @@ export function expand(lines, label, share = 1) {
403
434
  error(h.line, unmatchedReplay(h, sections), h.name);
404
435
  return null;
405
436
  }
437
+ where.replay = h.line;
406
438
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
439
+ where.replay = null;
407
440
  const elided = h.elided && removeLastBar(out);
408
441
  // A replay heading stands for its bars: its own lines (directives) come after them.
409
442
  playItems(itemsOf.get(s) ?? [], out);
@@ -457,5 +490,7 @@ export function expand(lines, label, share = 1) {
457
490
  form: forms.get(written) ?? 0,
458
491
  };
459
492
  });
493
+ if (pedal)
494
+ diagnostics.push(...pedalWarnings(flattenBars(events)));
460
495
  return { events, sections: sectionsOut, diagnostics };
461
496
  }
@@ -5,8 +5,13 @@ export { printDirection } from "./direction.js";
5
5
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
+ export { CLEF_NAMES, type ClefName, INSTRUMENTS, type InstrumentInfo, type InstrumentName, instrumentInfo, type WrittenInterval, } from "./instruments.js";
9
+ export { MAX_LINES } from "./lines.js";
8
10
  export { extractPart, parseChart } from "./parse.js";
9
11
  export { projectPart } from "./parts.js";
12
+ export { pedalStates } from "./pedal.js";
10
13
  export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
14
+ export { memberShares } from "./shares.js";
15
+ export { streamKey } from "./systems.js";
11
16
  export { type TransposeBy, transposeChart } from "./transpose.js";
12
17
  export type * from "./types.js";
@@ -5,7 +5,12 @@ export { printDirection } from "./direction.js";
5
5
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
+ export { CLEF_NAMES, INSTRUMENTS, instrumentInfo, } from "./instruments.js";
9
+ export { MAX_LINES } from "./lines.js";
8
10
  export { extractPart, parseChart } from "./parse.js";
9
11
  export { projectPart } from "./parts.js";
12
+ export { pedalStates } from "./pedal.js";
10
13
  export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
14
+ export { memberShares } from "./shares.js";
15
+ export { streamKey } from "./systems.js";
11
16
  export { transposeChart } from "./transpose.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The instruments a part may name (grammar 7.3): a closed list, each with
3
+ * what a converter needs to notate it. A chart is always at concert pitch;
4
+ * `written` only says how far above it a converter writes the part.
5
+ */
6
+ export type ClefName = "treble" | "bass" | "treble 8vb" | "alto";
7
+ export declare const CLEF_NAMES: readonly ClefName[];
8
+ export type InstrumentName = "piano" | "electric piano" | "organ" | "synth" | "acoustic guitar" | "electric guitar" | "electric bass" | "double bass" | "trumpet in Bb" | "alto sax" | "tenor sax" | "trombone" | "flute" | "violin" | "cello" | "voice";
9
+ /** How far above sounding pitch a part is written, in scale steps and semitones. */
10
+ export type WrittenInterval = {
11
+ diatonic: number;
12
+ chromatic: number;
13
+ };
14
+ export type InstrumentInfo = {
15
+ name: InstrumentName;
16
+ /** The clef of its (upper) staff; a two-staff instrument's lower staff is bass. */
17
+ clef: ClefName;
18
+ staves: 1 | 2;
19
+ written: WrittenInterval;
20
+ /** Its General MIDI program, 1–128. */
21
+ program: number;
22
+ };
23
+ export declare const INSTRUMENTS: readonly InstrumentInfo[];
24
+ /** The listed instrument with this name, in any case; null when there is none. */
25
+ export declare function instrumentInfo(name: string): InstrumentInfo | null;
26
+ /** The listed names an unknown one is near: those holding all its words, or else within two edits. */
27
+ export declare function nearInstruments(name: string): InstrumentName[];
@@ -0,0 +1,48 @@
1
+ export const CLEF_NAMES = ["treble", "bass", "treble 8vb", "alto"];
2
+ const SOUNDING = { diatonic: 0, chromatic: 0 };
3
+ const OCTAVE_UP = { diatonic: 7, chromatic: 12 };
4
+ const row = (name, clef, staves, program, written = SOUNDING) => ({ name, clef, staves, written, program });
5
+ export const INSTRUMENTS = [
6
+ row("piano", "treble", 2, 1),
7
+ row("electric piano", "treble", 2, 5),
8
+ row("organ", "treble", 2, 17),
9
+ row("synth", "treble", 2, 81),
10
+ // A guitar's treble 8vb clef carries its octave: written where it sounds.
11
+ row("acoustic guitar", "treble 8vb", 1, 26),
12
+ row("electric guitar", "treble 8vb", 1, 28),
13
+ row("electric bass", "bass", 1, 34, OCTAVE_UP),
14
+ row("double bass", "bass", 1, 33, OCTAVE_UP),
15
+ row("trumpet in Bb", "treble", 1, 57, { diatonic: 1, chromatic: 2 }),
16
+ row("alto sax", "treble", 1, 66, { diatonic: 5, chromatic: 9 }),
17
+ row("tenor sax", "treble", 1, 67, { diatonic: 8, chromatic: 14 }),
18
+ row("trombone", "bass", 1, 58),
19
+ row("flute", "treble", 1, 74),
20
+ row("violin", "treble", 1, 41),
21
+ row("cello", "bass", 1, 43),
22
+ row("voice", "treble", 1, 53),
23
+ ];
24
+ const key = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
25
+ /** The listed instrument with this name, in any case; null when there is none. */
26
+ export function instrumentInfo(name) {
27
+ return INSTRUMENTS.find((i) => key(i.name) === key(name)) ?? null;
28
+ }
29
+ /** Levenshtein distance, for near names. */
30
+ function distance(a, b) {
31
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
32
+ for (let i = 1; i <= a.length; i++) {
33
+ const next = [i];
34
+ for (let j = 1; j <= b.length; j++)
35
+ next[j] = Math.min((prev[j] ?? 0) + 1, (next[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1));
36
+ prev = next;
37
+ }
38
+ return prev[b.length] ?? 0;
39
+ }
40
+ /** The listed names an unknown one is near: those holding all its words, or else within two edits. */
41
+ export function nearInstruments(name) {
42
+ const words = key(name).split(" ");
43
+ const holding = INSTRUMENTS.filter((i) => words.every((w) => key(i.name).split(" ").includes(w)));
44
+ const near = holding.length
45
+ ? holding
46
+ : INSTRUMENTS.filter((i) => distance(key(i.name), key(name)) <= 2);
47
+ return near.map((i) => i.name);
48
+ }
@@ -0,0 +1,14 @@
1
+ import type { ChartDiagnostic, DeclaredPart, Line, Part } from "./types.js";
2
+ /** At most this many lines per part (grammar 7.6). */
3
+ export declare const MAX_LINES = 4;
4
+ /**
5
+ * Check a chart's part lines (grammar 7.6), after systems are numbered:
6
+ * names, the four-line limit, score order, and that only a part's first
7
+ * line in a system, in score order, holds harmony or pedal marks. A line that breaks a rule is an
8
+ * error and is marked `dropped`. Never throws.
9
+ */
10
+ export declare function checkLines(lines: Line[], parts: Part[]): {
11
+ lines: Line[];
12
+ parts: DeclaredPart[];
13
+ diagnostics: ChartDiagnostic[];
14
+ };
@@ -0,0 +1,130 @@
1
+ /** At most this many lines per part (grammar 7.6). */
2
+ export const MAX_LINES = 4;
3
+ const isLabelled = (l) => (l.kind === "bars" || l.kind === "invalid") && l.part !== undefined;
4
+ const members = (s) => (s.kind === "group" ? s.members : [s]);
5
+ const slotsOf = (l) => l.cells.flatMap((c) => (c.kind === "slots" ? c.slots.flatMap(members) : []));
6
+ /** Why a line that is not its part's first in a system can't be what it is, or null (grammar 7.6). */
7
+ function notesOnlyProblem(l) {
8
+ const slots = slotsOf(l);
9
+ const harmony = slots.some((s) => s.kind === "nc" ||
10
+ s.kind === "unknown" ||
11
+ (s.kind === "chord" && (s.chord.kind !== "notes" || s.voicing !== undefined)));
12
+ if (harmony)
13
+ return "chord symbols go on the part's first line; write a note set here, or a voicing on the first line";
14
+ return slots.some((s) => s.kind === "chord" && s.pedal)
15
+ ? "a pedal mark goes on the part's first line"
16
+ : null;
17
+ }
18
+ /** Each part's line names in first-appearance order, each line renamed to its first spelling; a fifth is an error. */
19
+ function nameLines(lines, report) {
20
+ const names = new Map();
21
+ const out = lines.map((l) => {
22
+ if (!isLabelled(l) || l.lineName === undefined)
23
+ return l;
24
+ const own = names.get(l.part ?? "") ?? [];
25
+ const known = own.find((n) => n.toLowerCase() === l.lineName?.toLowerCase());
26
+ if (known)
27
+ return { ...l, lineName: known };
28
+ if (own.length >= MAX_LINES)
29
+ return report(l, "a part has at most four lines");
30
+ names.set(l.part ?? "", [...own, l.lineName]);
31
+ return l;
32
+ });
33
+ return { lines: out, names };
34
+ }
35
+ /** A system's lines by part, in written order. */
36
+ function byPart(system) {
37
+ const out = new Map();
38
+ for (const l of system)
39
+ out.set(l.part ?? "", [...(out.get(l.part ?? "") ?? []), l]);
40
+ return out;
41
+ }
42
+ /**
43
+ * Each part's score order (grammar 7.6): its lines as the first system
44
+ * writing two or more of them writes them, then any others in the order
45
+ * they first appear.
46
+ */
47
+ function scoreOrder(names, systems) {
48
+ const out = new Map();
49
+ 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 ?? [];
54
+ out.set(part, [...first, ...all.filter((n) => !first.includes(n))]);
55
+ }
56
+ return out;
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
+ }
89
+ /** A system's lines of each part, after the first in score order, hold notes only. */
90
+ function checkSystem(system, order, report) {
91
+ for (const [part, written] of byPart(system)) {
92
+ const rank = (l) => l.lineName === undefined ? -1 : (order.get(part) ?? []).indexOf(l.lineName);
93
+ const own = [...written].sort((a, b) => rank(a) - rank(b));
94
+ for (const l of own.slice(1)) {
95
+ const problem = l.kind === "bars" ? notesOnlyProblem(l) : null;
96
+ if (problem)
97
+ report(l, problem);
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * Check a chart's part lines (grammar 7.6), after systems are numbered:
103
+ * names, the four-line limit, score order, and that only a part's first
104
+ * line in a system, in score order, holds harmony or pedal marks. A line that breaks a rule is an
105
+ * error and is marked `dropped`. Never throws.
106
+ */
107
+ export function checkLines(lines, parts) {
108
+ const diagnostics = [];
109
+ const failed = new Set();
110
+ const report = (l, message) => {
111
+ diagnostics.push({ line: l.line, severity: "error", message, token: l.part ?? "" });
112
+ failed.add(l.line);
113
+ return l;
114
+ };
115
+ const named = nameLines(lines, report);
116
+ const systems = new Map();
117
+ for (const l of named.lines)
118
+ 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);
122
+ for (const system of systems.values())
123
+ checkSystem(system.filter((l) => !failed.has(l.line)), order, report);
124
+ const out = named.lines.map((l) => l.kind === "bars" && failed.has(l.line) ? { ...l, dropped: true } : l);
125
+ const declared = parts.map((p) => {
126
+ const own = order.get(p.label ?? "");
127
+ return own ? { ...p, lines: own } : p;
128
+ });
129
+ return { lines: out, parts: declared, diagnostics };
130
+ }