barmark 0.15.0 → 0.16.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.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,49 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.16.0] - 2026-11-04
13
+
14
+ A grammar change: part lines (7.6), sustain pedal marks (2.9), dotted
15
+ figures (2.2), and `instrument:` and `clef:` on the `part:` line (7.3).
16
+ Charts that read before read the same. Implements the
17
+ [grammar v0.1 draft](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md).
18
+
19
+ ### Added
20
+
21
+ - **Part lines** (grammar 7.6): up to four lines per part, labelled
22
+ `Pno.RH |` and `Pno.LH |`, in systems as parts are. The first line in a
23
+ system carries the harmony and the others notes only; a fifth line, or
24
+ a chord on another line, is an error. Bar lines gain `lineName`,
25
+ declared parts gain `lines`, and the canonical form sorts a system's
26
+ lines into score order: the order of the part's first system writing
27
+ two or more of its lines, so an intro for the left hand alone keeps the
28
+ right hand first. `streamKey` and `MAX_LINES` are exported.
29
+ Each line plays on its own: a played bar's part entry gains `lines`
30
+ (`LineBar`: name, line, slots, words), one per line playing there, and
31
+ the part's `slots` are its first playing line's. A bare line and a tutti
32
+ line play as the part's first line; a line not written rests. A
33
+ single-part chart's bars, and an extracted part's, carry `lines`
34
+ themselves, and `printPart` keeps the `Pno.RH |` labels.
35
+ `extractPart(text, label, lineName)` gives one line alone, as a
36
+ converter writes it: resting (tacet) where the line isn't written.
37
+ - **Sustain pedal marks** (grammar 2.9): `+G` presses or changes the
38
+ pedal, `*G` lifts it; `--`, a tacet bar and the chart's end lift it too.
39
+ A chord slot gains `pedal`, and `pedalStates` gives whether the pedal is
40
+ down at the end of each slot, in play order. A `*` with the pedal
41
+ already up is a warning.
42
+ - **Dotted figures** (grammar 2.2): a dot after one member of a
43
+ two-member group, `C._D` (a dotted eighth and a sixteenth in a beat)
44
+ or `C_D.`. Group members gain `dotted`, and `memberShares` gives each
45
+ member's share of its slot. `N.C._G` keeps its meaning, and a misplaced
46
+ `...`, `D.S.` or `D.C.` keeps its own message.
47
+ - **`instrument:` and `clef:` on the `part:` line** (grammar 7.3):
48
+ `part: Tpt = Trumpet, instrument: trumpet in Bb`, `part: Ld = Lead,
49
+ clef: bass`. The instrument comes from a list of 16 (`INSTRUMENTS`,
50
+ `instrumentInfo`), each with its clef, written transposition, staves
51
+ and General MIDI program, for converters. `Part` gains `instrument` and
52
+ `clef`, present when written. An unknown instrument is an error naming
53
+ the near ones; `clef:` on a keyboard is an error.
54
+
12
55
  ## [0.15.0] - 2026-11-04
13
56
 
14
57
  A grammar change: credit lines (7.5). Charts that read before read the
@@ -383,7 +426,8 @@ The first working release: the reference parser and printer for the
383
426
 
384
427
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
385
428
 
386
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.15.0...HEAD
429
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.16.0...HEAD
430
+ [0.16.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.15.0...barmark-v0.16.0
387
431
  [0.15.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.14.1...barmark-v0.15.0
388
432
  [0.14.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.14.0...barmark-v0.14.1
389
433
  [0.14.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.13.0...barmark-v0.14.0
package/README.md CHANGED
@@ -96,6 +96,29 @@ printPart(text, "Pno"); // the same as text: tacet bars written N.C.
96
96
  projectPart(chart.lines, chart.parts, "Pno"); // one part's lines
97
97
  ```
98
98
 
99
+ A part can also write up to four **lines** that play together, a
100
+ pianist's two hands (grammar 7.6), and name its instrument and clef
101
+ (7.3):
102
+
103
+ ```
104
+ part: Pno = Piano, instrument: piano
105
+ part: Bs = Bass, instrument: electric bass
106
+
107
+ Pno.RH | +G{B3 D4 G4} | *C{C4 E4 G4} |
108
+ Pno.LH | {G2}._{D3} / | {C3} |
109
+ Bs | {G1} | {C2} |
110
+ ```
111
+
112
+ The first line in a system carries the chord symbols, the others note
113
+ sets only. `+` presses the sustain pedal and `*` lifts it (2.9);
114
+ `{G2}._{D3}` is a dotted eighth and a sixteenth (2.2).
115
+
116
+ ```ts
117
+ chart.bars[0].parts[0].lines; // [{ name: "RH", line, slots }, { name: "LH", … }]
118
+ extractPart(text, "Pno", "LH"); // one line alone, resting where it isn't written
119
+ pedalStates(chart.bars); // whether the pedal is down after each slot
120
+ ```
121
+
99
122
  `printChart` sorts a system into score order and lines up its pipes.
100
123
  `chart.part` still gives the one part of a single-part chart, and is
101
124
  deprecated in favour of `parts`.
@@ -67,6 +67,15 @@ export function misplacedRepeat(token) {
67
67
  /** Diagnostics listed per line before the rest are summarized. */
68
68
  const MAX_LINE_DIAGNOSTICS = 20;
69
69
  /** Split a group on `_`, leaving any `_` inside braces to the note set. */
70
+ const DOT_PLACE = "a dot goes on one member of a two-member group (C._D or C_D.); write other rhythms with / holds";
71
+ /**
72
+ * Tokens that end in a dot without being dotted: `N.C.`'s spellings, a
73
+ * run of dots (`...`), and the directions `D.S.` and `D.C.`, which keep
74
+ * their own messages when misplaced.
75
+ */
76
+ const UNDOTTED = /^[<>^+*]*n\.?c\.?$|^\.+$|^d\.[sc]\.$/i;
77
+ /** A member ending in a dot that is not one of the undotted tokens. */
78
+ const isDotted = (m) => m.endsWith(".") && !UNDOTTED.test(m);
70
79
  function groupMembers(token) {
71
80
  const out = [""];
72
81
  let depth = 0;
@@ -239,13 +248,27 @@ function directionWithWords(bare, meter, words) {
239
248
  }
240
249
  const ARTICULATION = { ">": "accent", "^": "hit" };
241
250
  const PUSH = { 1: "eighth", 2: "sixteenth" };
242
- /** A slot's leading marks (grammar 2.7, 2.8): a push, then an articulation, then the slot itself. */
251
+ const PEDAL = { "+": "press", "*": "release" };
252
+ /** A slot's leading marks (grammar 2.7–2.9): a pedal mark, a push, an articulation, then the slot. */
243
253
  function readMarks(token) {
254
+ const late = /^([<>^]+)([+*])(.*)$/.exec(token);
255
+ if (late)
256
+ return {
257
+ problem: "a pedal mark comes before a push or an accent",
258
+ token,
259
+ suggestion: `${late[2]}${late[1]}${late[3]}`,
260
+ };
261
+ const pedal = PEDAL[token[0] ?? ""];
262
+ const marked = readPushAndAccent(pedal ? token.slice(1) : token, token);
263
+ return "problem" in marked || !pedal ? marked : { pedal, ...marked };
264
+ }
265
+ /** A push, then an articulation, then the slot itself (grammar 2.7, 2.8). */
266
+ function readPushAndAccent(token, written) {
244
267
  const pushes = /^<*/.exec(token)?.[0].length ?? 0;
245
268
  const push = PUSH[pushes];
246
269
  if (pushes && !push)
247
- return { problem: "a push is < (an eighth) or << (a sixteenth)", token };
248
- const marked = readArticulation(token.slice(pushes), token);
270
+ return { problem: "a push is < (an eighth) or << (a sixteenth)", token: written };
271
+ const marked = readArticulation(token.slice(pushes), written);
249
272
  return "problem" in marked ? marked : { ...(push ? { push } : {}), ...marked };
250
273
  }
251
274
  /** A leading `>` or `^`, and the slot after it; a push after it is written in the wrong order. */
@@ -261,15 +284,24 @@ function readArticulation(text, token) {
261
284
  }
262
285
  const UNPUSHABLE = new Set(["/", "?", "%", "...", "…"]);
263
286
  /** Why these marks can't go on this slot; null when they can. */
287
+ /** Whether a slot is one of `/`, `?`, `--` or `N.C.`, which take no accent or pedal. */
288
+ const isPlain = (rest) => UNPUSHABLE.has(rest) || SILENCE.has(rest) || /^n\.?c\.?$/i.test(rest);
289
+ /** Each rule on marks: when it is broken, and what the error says. */
290
+ const MARK_RULES = [
291
+ [(m, inGroup) => Boolean(m.push) && inGroup, "a push goes on a whole slot, not inside a group"],
292
+ [
293
+ (m) => Boolean(m.push) && UNPUSHABLE.has(m.rest),
294
+ "a push goes on a chord, a note set, N.C. or --",
295
+ ],
296
+ [
297
+ (m) => Boolean(m.articulation) && isPlain(m.rest),
298
+ "an accent or a hit goes on a chord or a note set",
299
+ ],
300
+ [(m) => Boolean(m.pedal) && isPlain(m.rest), "a pedal mark goes on a chord or a note set"],
301
+ ];
264
302
  function marksProblem(marks, inGroup, token) {
265
- if (marks.push && inGroup)
266
- return { problem: "a push goes on a whole slot, not inside a group", token };
267
- if (marks.push && UNPUSHABLE.has(marks.rest))
268
- return { problem: "a push goes on a chord, a note set, N.C. or --", token };
269
- const plain = UNPUSHABLE.has(marks.rest) || SILENCE.has(marks.rest) || /^n\.?c\.?$/i.test(marks.rest);
270
- if (marks.articulation && plain)
271
- return { problem: "an accent or a hit goes on a chord or a note set", token };
272
- return null;
303
+ const broken = MARK_RULES.find(([breaks]) => breaks(marks, inGroup));
304
+ return broken ? { problem: broken[1], token } : null;
273
305
  }
274
306
  /** Whether a voicing's note is one of the chord's, by pitch class. */
275
307
  const inChord = (note, chord) => {
@@ -433,22 +465,33 @@ export function parseBarLine(text, line) {
433
465
  if (problem)
434
466
  return report(problem);
435
467
  const base = simple(marks.rest);
436
- const { push, articulation } = marks;
468
+ const { pedal, push, articulation } = marks;
437
469
  return (base &&
438
470
  {
439
471
  ...base,
472
+ ...(pedal ? { pedal } : {}),
440
473
  ...(push ? { push } : {}),
441
474
  ...(articulation ? { articulation } : {}),
442
475
  });
443
476
  };
477
+ /** A group member, dotted when it ends in a dot that is not part of `N.C.` (grammar 2.2). */
478
+ const memberOf = (m) => {
479
+ if (!isDotted(m))
480
+ return markedSlot(m, true);
481
+ const s = markedSlot(m.slice(0, -1), true);
482
+ return s && { ...s, dotted: true };
483
+ };
444
484
  /** One slot token: a simple slot, or a `_` group of them. */
445
485
  const slotOf = (token) => {
446
486
  const members = groupMembers(token);
447
487
  if (members.length === 1)
448
- return markedSlot(token, false);
488
+ return isDotted(token) ? error(DOT_PLACE, token) : markedSlot(token, false);
489
+ const dots = members.filter(isDotted).length;
490
+ if (dots && (members.length > 2 || dots > 1))
491
+ return error(DOT_PLACE, token);
449
492
  const out = [];
450
493
  for (const m of members) {
451
- const s = m ? markedSlot(m, true) : error("an empty member in a group", token);
494
+ const s = m ? memberOf(m) : error("an empty member in a group", token);
452
495
  if (s)
453
496
  out.push(s);
454
497
  }
@@ -1,9 +1,9 @@
1
- import type { ChartDiagnostic, Credits, Line, Part } from "./types.js";
1
+ import type { ChartDiagnostic, Credits, DeclaredPart, Line } from "./types.js";
2
2
  /** Classify every line of a chart: title, sections, directives, bar lines and text. */
3
3
  export declare function readDocument(text: string): {
4
4
  title: string | null;
5
- part: Part | null;
6
- parts: Part[];
5
+ part: DeclaredPart | null;
6
+ parts: DeclaredPart[];
7
7
  credits: Credits;
8
8
  lines: Line[];
9
9
  diagnostics: ChartDiagnostic[];
@@ -1,7 +1,9 @@
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 { readPart } from "./partLine.js";
5
7
  import { groupSystems } from "./systems.js";
6
8
  const NEAR_DIRECTIVES = {
7
9
  meter: "time",
@@ -11,24 +13,6 @@ const NEAR_DIRECTIVES = {
11
13
  instrument: "part",
12
14
  parts: "part",
13
15
  };
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
16
  /**
33
17
  * Several parts each need a label, and no two may share one in any case
34
18
  * (grammar 7.4). A part that breaks either rule is text, with the error.
@@ -51,7 +35,12 @@ function checkParts(lines, diagnostics) {
51
35
  }
52
36
  return parts;
53
37
  }
54
- const partOf = (l) => (l.label ? { label: l.label, name: l.name } : { name: l.name });
38
+ const partOf = (l) => ({
39
+ ...(l.label && { label: l.label }),
40
+ name: l.name,
41
+ ...(l.instrument && { instrument: l.instrument }),
42
+ ...(l.clef && { clef: l.clef }),
43
+ });
55
44
  function partProblem(l, seen) {
56
45
  if (!l.label)
57
46
  return {
@@ -102,6 +91,22 @@ function readHeading(text, line, diagnostics) {
102
91
  });
103
92
  return { kind: "section", line, name: rest, repeat, elided };
104
93
  }
94
+ /** A declared label written before a bar line, exactly, or a part's label, a dot and a line's name (grammar 7.6). */
95
+ function findLabel(word, declared) {
96
+ const match = (w) => declared.find((p) => p.label?.toLowerCase() === w.toLowerCase())?.label;
97
+ const exact = match(word);
98
+ if (exact)
99
+ return { part: exact };
100
+ const dot = word.lastIndexOf(".");
101
+ const label = dot > 0 ? match(word.slice(0, dot)) : undefined;
102
+ return label ? { part: label, lineName: word.slice(dot + 1) } : null;
103
+ }
104
+ /** The word before a bar line, whether a space follows it, and the bar line. */
105
+ function splitLabel(t) {
106
+ const m = LABELLED.exec(t);
107
+ return m ? { word: m[1] ?? "", space: Boolean(m[2]), rest: m[3] ?? "" } : null;
108
+ }
109
+ const LINE_NAME = /^[A-Za-z0-9]+$/;
105
110
  /** A label and the bar line after it: `Gtr | G |` (grammar 7.4). */
106
111
  const LABELLED = /^([^\s|]+)(\s*)(\|.*)$/;
107
112
  const readsCleanly = (barLine) => {
@@ -193,6 +198,22 @@ function noBarLines(lines) {
193
198
  token: first.text,
194
199
  };
195
200
  }
201
+ /** A part's bare line in a single-part chart with no lines is unlabelled, as before (grammar 7.4). */
202
+ function unlabelled(l) {
203
+ if (l.kind !== "bars" && l.kind !== "invalid")
204
+ return l;
205
+ const { part: _p, ...rest } = l;
206
+ return rest;
207
+ }
208
+ /** Systems and part lines, when the chart has several parts or a part writes lines (grammar 7.4, 7.6). */
209
+ function groupParts(lines, parts) {
210
+ const lined = lines.some((l) => (l.kind === "bars" || l.kind === "invalid") && l.lineName !== undefined);
211
+ if (parts.length < 2 && !lined)
212
+ return { lines: lines.map(unlabelled), parts, diagnostics: [] };
213
+ const systems = groupSystems(lines);
214
+ const checked = checkLines(systems.lines, parts);
215
+ return { ...checked, diagnostics: [...systems.diagnostics, ...checked.diagnostics] };
216
+ }
196
217
  /** Classify every line of a chart: title, sections, directives, bar lines and text. */
197
218
  export function readDocument(text) {
198
219
  const lines = [];
@@ -239,35 +260,30 @@ export function readDocument(text) {
239
260
  diagnostics.push(...r.diagnostics);
240
261
  return r.bars ?? { kind: "invalid", line, text: t, written: r.written };
241
262
  };
242
- /** A declared part's bar line; labelled only when the chart has several parts. */
263
+ const declaredParts = () => lines.filter((l) => l.kind === "part");
264
+ /** A labelled line that can't be read: no space before its pipe, or a bad line name. */
265
+ const badLabel = (t, line, word, rest, owner) => {
266
+ const space = t.length > word.length + rest.length;
267
+ diagnostics.push({
268
+ line,
269
+ severity: "error",
270
+ message: space ? "a line name is letters and digits" : "a space goes between the label and |",
271
+ token: t,
272
+ ...(!space && { suggestion: `${word} ${rest}` }),
273
+ });
274
+ return { kind: "invalid", line, text: t, written: parseBarLine(rest, line).written, ...owner };
275
+ };
276
+ /** A declared part's bar line, or one of its lines (`Pno.RH`, grammar 7.6). */
243
277
  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)
278
+ const split = splitLabel(t);
279
+ const owner = split && findLabel(split.word, declaredParts());
280
+ if (!split || !owner)
248
281
  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
- }
282
+ const { word, space, rest } = split;
283
+ if (!space || !LINE_NAME.test(owner.lineName ?? "X"))
284
+ return badLabel(t, line, word, rest, owner);
267
285
  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 };
286
+ return read.kind === "bars" || read.kind === "invalid" ? { ...read, ...owner } : read;
271
287
  };
272
288
  const classify = (t, line) => {
273
289
  if (t.startsWith("|"))
@@ -292,9 +308,10 @@ export function readDocument(text) {
292
308
  const empty = noBarLines(lines);
293
309
  if (empty)
294
310
  diagnostics.push(empty);
295
- const parts = checkParts(lines, diagnostics);
296
- const grouped = parts.length > 1 ? groupSystems(lines) : { lines, diagnostics: [] };
311
+ const read = checkParts(lines, diagnostics);
312
+ const grouped = groupParts(lines, read);
297
313
  diagnostics.push(...grouped.diagnostics);
314
+ const { parts } = grouped;
298
315
  return {
299
316
  title,
300
317
  part: parts.length === 1 ? (parts[0] ?? null) : null,
@@ -11,7 +11,9 @@ export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
11
11
  * `label` names the part a projected chart is (grammar 7.4), for its
12
12
  * messages; `share` is how many parts split the expansion budget.
13
13
  */
14
- export declare function expand(lines: Line[], label?: string, share?: number): {
14
+ export declare function expand(lines: Line[], label?: string, share?: number,
15
+ /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
16
+ pedal?: boolean): {
15
17
  events: ChartEvent[];
16
18
  sections: SectionOccurrence[];
17
19
  diagnostics: ChartDiagnostic[];
@@ -1,6 +1,8 @@
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 { memberShares } from "./shares.js";
4
6
  /** Nested repeats multiply; expansion stops here rather than run away. */
5
7
  export const MAX_EXPANDED_BARS = 10_000;
6
8
  /**
@@ -31,7 +33,10 @@ const PUSH_LENGTH = { eighth: 1 / 8, sixteenth: 1 / 16 };
31
33
  function timed(bar) {
32
34
  const each = bar.meter.n / bar.meter.d / bar.slots.length;
33
35
  return bar.slots.flatMap((s) => s.kind === "group"
34
- ? s.members.map((m) => ({ slot: m, length: each / s.members.length }))
36
+ ? memberShares(s.members).map((share, i) => ({
37
+ slot: s.members[i],
38
+ length: each * share,
39
+ }))
35
40
  : [{ slot: s, length: each }]);
36
41
  }
37
42
  /** Why a push can't take its time from a slot this long; null when it can. */
@@ -81,7 +86,9 @@ function removeLastBar(events) {
81
86
  * `label` names the part a projected chart is (grammar 7.4), for its
82
87
  * messages; `share` is how many parts split the expansion budget.
83
88
  */
84
- export function expand(lines, label, share = 1) {
89
+ export function expand(lines, label, share = 1,
90
+ /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
91
+ pedal = true) {
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.
@@ -457,5 +464,7 @@ export function expand(lines, label, share = 1) {
457
464
  form: forms.get(written) ?? 0,
458
465
  };
459
466
  });
467
+ if (pedal)
468
+ diagnostics.push(...pedalWarnings(flattenBars(events)));
460
469
  return { events, sections: sectionsOut, diagnostics };
461
470
  }
@@ -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,98 @@
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
+ /** A system's lines of each part, after the first in score order, hold notes only. */
59
+ function checkSystem(system, order, report) {
60
+ for (const [part, written] of byPart(system)) {
61
+ const rank = (l) => l.lineName === undefined ? -1 : (order.get(part) ?? []).indexOf(l.lineName);
62
+ const own = [...written].sort((a, b) => rank(a) - rank(b));
63
+ for (const l of own.slice(1)) {
64
+ const problem = l.kind === "bars" ? notesOnlyProblem(l) : null;
65
+ if (problem)
66
+ report(l, problem);
67
+ }
68
+ }
69
+ }
70
+ /**
71
+ * Check a chart's part lines (grammar 7.6), after systems are numbered:
72
+ * names, the four-line limit, score order, and that only a part's first
73
+ * line in a system, in score order, holds harmony or pedal marks. A line that breaks a rule is an
74
+ * error and is marked `dropped`. Never throws.
75
+ */
76
+ export function checkLines(lines, parts) {
77
+ const diagnostics = [];
78
+ const failed = new Set();
79
+ const report = (l, message) => {
80
+ diagnostics.push({ line: l.line, severity: "error", message, token: l.part ?? "" });
81
+ failed.add(l.line);
82
+ return l;
83
+ };
84
+ const named = nameLines(lines, report);
85
+ const systems = new Map();
86
+ for (const l of named.lines)
87
+ if (isLabelled(l) && l.system !== undefined && !failed.has(l.line))
88
+ systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
89
+ const order = scoreOrder(named.names, [...systems.values()]);
90
+ for (const system of systems.values())
91
+ checkSystem(system, order, report);
92
+ const out = named.lines.map((l) => l.kind === "bars" && failed.has(l.line) ? { ...l, dropped: true } : l);
93
+ const declared = parts.map((p) => {
94
+ const own = order.get(p.label ?? "");
95
+ return own ? { ...p, lines: own } : p;
96
+ });
97
+ return { lines: out, parts: declared, diagnostics };
98
+ }