barmark 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { toHarte } from "./harte.js";
2
2
  import { noteSemitone, transpose } from "./intervals.js";
3
3
  import { canonicalParts, printChord } from "./print.js";
4
+ import { alteredFifth, bareScan, intoGroup, pullBare, separate, stackedWarning, } from "./stacked.js";
4
5
  import { ALIASES, chordIntervals, EXTENSIONS, isOmission, OMISSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
5
6
  const ROOT = /^[A-G][#b]?/;
6
7
  const INLINE_ALTERATION = /^(b5|#5|b9|#9|#11|b13)/;
@@ -71,6 +72,14 @@ function toneProblem(tone, before) {
71
72
  }
72
73
  return TONES.includes(tone) ? null : `"${tone}" is not a tone a parenthesis can add`;
73
74
  }
75
+ /** The parts a normalized symbol is spelled from, valid together, or why not. */
76
+ function readParts(text, symbol) {
77
+ const read = tokenize(text);
78
+ if (typeof read === "string")
79
+ return { message: `${symbol}: ${read}`, token: symbol };
80
+ const parts = powerChord(read);
81
+ return validateParts(parts, symbol) ?? parts;
82
+ }
74
83
  const ORDINAL = { 3: "3rd", 5: "5th" };
75
84
  /**
76
85
  * The intervals once `no3`/`no5` leave out a tone, or why they can't: the
@@ -113,14 +122,19 @@ function logicGroups(rest) {
113
122
  const others = tones.filter((t) => t !== "5");
114
123
  return `5${others.length ? `(${others.join(",")})` : ""}${joined.slice(group[0].length)}`;
115
124
  }
116
- /** Appendix A.5 and A.6: Unicode, rejections, then aliases into canonical vocabulary. */
117
- function normalizeSymbol(symbol) {
118
- const text = symbol.replace(/♯/g, "#").replace(/♭/g, "b");
125
+ const BARE_ADD = bareScan("add(?:2|4|9|11)");
126
+ /** The text a symbol is read from: ♯ and ♭ as # and b (Appendix A.5). */
127
+ const ascii = (symbol) => symbol.replace(/♯/g, "#").replace(/♭/g, "b");
128
+ /** Appendix A.5 and A.6: rejections, then aliases into canonical vocabulary. */
129
+ function normalizeSymbol(text) {
119
130
  const rejected = rejection(text, noteSemitone);
120
131
  if (rejected)
121
132
  return rejected;
122
133
  const root = ROOT.exec(text)?.[0] ?? "";
123
134
  let rest = text.slice(root.length);
135
+ // Stacked spellings first, on the name as written; the aliases then read what is left.
136
+ const separated = separate(rest);
137
+ rest = separated.text;
124
138
  for (const [pattern, replacement] of ALIASES)
125
139
  rest = rest.replace(pattern, replacement);
126
140
  rest = logicGroups(rest);
@@ -129,33 +143,42 @@ function normalizeSymbol(symbol) {
129
143
  // `(add9)` is `(9)`: inside a group, `add` before a tone it may add is dropped.
130
144
  rest = rest.replace(/(?<=[(,]\s*)add(2|4|9|11)(?=\s*[,)])/g, "$1");
131
145
  // A bare `add9` outside any group; what is left inside one is the tokenizer's to name.
132
- const bare = /add(2|4|9|11)(?![^(]*\))/g;
133
- const added = [...rest.matchAll(bare)].map((m) => m[1] ?? "");
134
- if (added.length) {
135
- rest = rest.replace(bare, "");
136
- const close = rest.indexOf(")");
137
- if (close >= 0)
138
- rest = `${rest.slice(0, close)},${added.join(",")}${rest.slice(close)}`;
139
- else {
140
- const slash = /\/[A-G][#b]?$/.exec(rest);
141
- const at = slash ? slash.index : rest.length;
142
- rest = `${rest.slice(0, at)}(${added.join(",")})${rest.slice(at)}`;
143
- }
144
- }
145
- return { text: root + rest };
146
+ const bare = pullBare(rest, BARE_ADD);
147
+ rest = intoGroup(bare.text, bare.taken.map((a) => a.slice(3)));
148
+ return { text: root + rest, separated };
149
+ }
150
+ /**
151
+ * The warning a stacked spelling reads with (grammar 3): its suggestion is
152
+ * the symbol with its items separated, or the canonical spelling when that
153
+ * would not read as the same chord.
154
+ */
155
+ function stacked(symbol, text, normal, canonical) {
156
+ const { runTogether, bareOmission } = normal.separated;
157
+ if (!runTogether && !bareOmission)
158
+ return null;
159
+ const root = ROOT.exec(text)?.[0] ?? "";
160
+ const written = root + separate(text.slice(root.length)).text;
161
+ const check = parseChord(written);
162
+ const same = check.ok && check.value.canonical === canonical;
163
+ return stackedWarning(symbol, normal.separated, same ? written : canonical);
146
164
  }
147
165
  export function parseChord(symbol) {
148
- const normal = normalizeSymbol(symbol);
166
+ const text = ascii(symbol);
167
+ const normal = normalizeSymbol(text);
149
168
  if (!("text" in normal))
150
169
  return { ok: false, error: normal };
151
- const read = tokenize(normal.text);
152
- if (typeof read === "string") {
153
- return { ok: false, error: { message: `${symbol}: ${read}`, token: symbol } };
170
+ const r = readChord(symbol, normal.text);
171
+ if (!r.ok) {
172
+ return { ok: false, error: alteredFifth(symbol, text, r.error, (s) => parseChord(s).ok) };
154
173
  }
155
- const parts = powerChord(read);
156
- const invalid = validateParts(parts, symbol);
157
- if (invalid)
158
- return { ok: false, error: invalid };
174
+ const warning = stacked(symbol, text, normal, r.value.canonical);
175
+ return warning ? { ...r, warnings: [warning, ...r.warnings] } : r;
176
+ }
177
+ /** The chord a normalized symbol names. */
178
+ function readChord(symbol, text) {
179
+ const parts = readParts(text, symbol);
180
+ if ("message" in parts)
181
+ return { ok: false, error: parts };
159
182
  const added = chordIntervals({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) }, symbol);
160
183
  const { warnings, alteredOpen } = added;
161
184
  const intervals = omit(added.intervals, parts, symbol);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stacked spellings (grammar 3, Appendix A.5): notation programs print a
3
+ * chord's alterations one after another with no separator ("D6 add9
4
+ * omit5"), so a chart arrives as `D6(omit5add9)` or `Gadd9omit3`. These
5
+ * read as their comma-separated form. Every scan here is one pass over the
6
+ * text, so a long symbol costs its length.
7
+ */
8
+ import type { Diagnostic } from "./types.js";
9
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
10
+ export declare const bareScan: (bare: string) => RegExp;
11
+ /**
12
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
13
+ * taken out (and each group's items passed through `group`), and what was
14
+ * taken.
15
+ */
16
+ export declare function pullBare(rest: string, scan: RegExp, group?: (inner: string) => string): {
17
+ text: string;
18
+ taken: string[];
19
+ };
20
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
21
+ export declare function intoGroup(rest: string, items: string[]): string;
22
+ export type Separated = {
23
+ text: string;
24
+ runTogether: boolean;
25
+ bareOmission: boolean;
26
+ };
27
+ /**
28
+ * The text after a root with items run together in a parenthesis separated
29
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
30
+ * quality however it is spelled, before any parenthesis or slash bass)
31
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
32
+ * `add9(omit3)`.
33
+ */
34
+ export declare function separate(rest: string): Separated;
35
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
36
+ export declare function stackedWarning(symbol: string, separated: Separated, suggestion: string): Diagnostic | null;
37
+ /**
38
+ * The error for a symbol that can't be read, with a suggestion when it
39
+ * writes an altered fifth before the parenthesis on a chord with no
40
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
41
+ * whether a suggestion reads. Where the root's own accidental could be the
42
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
43
+ * suggestion; only when that fifth reading would itself read.
44
+ */
45
+ export declare function alteredFifth(symbol: string, text: string, error: Diagnostic, reads: (symbol: string) => boolean): Diagnostic;
@@ -0,0 +1,122 @@
1
+ /** The shape of one parenthesis item; the tokenizer judges what it names. */
2
+ const ITEM = /^(?:add\d+|(?:omit\s*|no)\d+|[b#]?\d+)$/;
3
+ /** Where an item run together with the one before it starts. */
4
+ const ITEM_START = /(?=add|omit|no|[b#])/;
5
+ /** A slash bass at the end of the text after the root. */
6
+ const BASS = /\/[A-G][#b]?$/;
7
+ /** Where the chord's name ends: its first parenthesis or slash bass. */
8
+ const NAME_END = /\(|\/[A-G]/;
9
+ /** The items run together in one parenthesis item, or the item alone when it isn't a run of valid items. */
10
+ function splitItem(item) {
11
+ const pieces = item.split(ITEM_START).map((p) => p.trim());
12
+ return pieces.length > 1 && pieces.every((p) => ITEM.test(p)) ? pieces : [item];
13
+ }
14
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
15
+ export const bareScan = (bare) => new RegExp(String.raw `\((?<inner>[^()]*)\)|${bare}`, "g");
16
+ /**
17
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
18
+ * taken out (and each group's items passed through `group`), and what was
19
+ * taken.
20
+ */
21
+ export function pullBare(rest, scan, group = (inner) => inner) {
22
+ const taken = [];
23
+ const text = rest.replace(scan, (match, ...args) => {
24
+ const { inner } = args.at(-1);
25
+ if (inner !== undefined)
26
+ return `(${group(inner)})`;
27
+ taken.push(match);
28
+ return "";
29
+ });
30
+ return { text, taken };
31
+ }
32
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
33
+ export function intoGroup(rest, items) {
34
+ if (!items.length)
35
+ return rest;
36
+ const close = rest.lastIndexOf(")");
37
+ if (close >= 0)
38
+ return `${rest.slice(0, close)},${items.join(",")}${rest.slice(close)}`;
39
+ const at = BASS.exec(rest)?.index ?? rest.length;
40
+ return `${rest.slice(0, at)}(${items.join(",")})${rest.slice(at)}`;
41
+ }
42
+ /** A parenthesis and its items. */
43
+ const GROUP = /\((?<inner>[^()]*)\)/g;
44
+ /** A bare `omit`/`no` ending the chord's name. */
45
+ const TRAILING_OMISSION = /(?:omit\s*|no)\d+$/;
46
+ /**
47
+ * The text after a root with items run together in a parenthesis separated
48
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
49
+ * quality however it is spelled, before any parenthesis or slash bass)
50
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
51
+ * `add9(omit3)`.
52
+ */
53
+ export function separate(rest) {
54
+ let runTogether = false;
55
+ const split = (inner) => {
56
+ const items = inner.split(",");
57
+ const out = items.flatMap(splitItem);
58
+ if (out.length > items.length)
59
+ runTogether = true;
60
+ return out.join(",");
61
+ };
62
+ const text = rest.replace(GROUP, (_, inner) => `(${split(inner)})`);
63
+ // The chord's name: what comes before the first parenthesis or slash bass
64
+ // (a slash before a letter; `6/9` is an extension), whatever follows it.
65
+ const end = NAME_END.exec(text)?.index ?? text.length;
66
+ const name = text.slice(0, end);
67
+ const bare = TRAILING_OMISSION.exec(name);
68
+ if (!bare)
69
+ return { text, runTogether, bareOmission: false };
70
+ const moved = intoGroup(name.slice(0, bare.index) + text.slice(end), [bare[0]]);
71
+ return { text: moved, runTogether, bareOmission: true };
72
+ }
73
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
74
+ export function stackedWarning(symbol, separated, suggestion) {
75
+ const why = [
76
+ ...(separated.runTogether ? ["items in a parenthesis are separated by commas"] : []),
77
+ ...(separated.bareOmission ? ["an omission goes in parentheses"] : []),
78
+ ];
79
+ if (!why.length)
80
+ return null;
81
+ return { message: `${symbol}: ${why.join("; ")}`, token: symbol, suggestion };
82
+ }
83
+ /** An altered fifth straight after the root (and `m`), with no extension: `F#b5(omit3)`. */
84
+ const ALTERED_FIFTH = /^([A-G][#b]?)(m?)([b#]5)(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
85
+ /** A root whose accidental a following `5` could be read with: `Gb5`, `G#5`. */
86
+ const SWALLOWED = /^([A-G])([#b])5(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
87
+ /**
88
+ * The error for a symbol that can't be read, with a suggestion when it
89
+ * writes an altered fifth before the parenthesis on a chord with no
90
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
91
+ * whether a suggestion reads. Where the root's own accidental could be the
92
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
93
+ * suggestion; only when that fifth reading would itself read.
94
+ */
95
+ export function alteredFifth(symbol, text, error, reads) {
96
+ const s = SWALLOWED.exec(text);
97
+ if (s) {
98
+ const [, letter = "", accidental = "", inner, bass = ""] = s;
99
+ const items = inner?.trim() ? `,${inner}` : "";
100
+ const fifth = letter + separate(`(${accidental}5${items})${bass}`).text;
101
+ if (!reads(fifth))
102
+ return error;
103
+ const power = `${letter}${accidental}5`;
104
+ return {
105
+ ...error,
106
+ message: `${error.message}; ambiguous: ${power} is always the ${letter}${accidental} power chord (grammar 3); a ${letter} chord with a ${accidental}5 writes it in the parentheses`,
107
+ };
108
+ }
109
+ const m = ALTERED_FIFTH.exec(text);
110
+ if (!m)
111
+ return error;
112
+ const [, root = "", minor = "", fifth = "", inner, bass = ""] = m;
113
+ const items = inner?.trim() ? `,${inner}` : "";
114
+ const suggestion = root + separate(`${minor}(${fifth}${items})${bass}`).text;
115
+ if (!reads(suggestion))
116
+ return error;
117
+ return {
118
+ message: `${symbol}: an altered 5th goes in the parentheses unless it follows an extension (grammar 3)`,
119
+ token: symbol,
120
+ suggestion,
121
+ };
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -31,7 +31,7 @@
31
31
  ],
32
32
  "author": "Kevin Peckham",
33
33
  "license": "MIT",
34
- "homepage": "https://github.com/kevinpeckham/barmark/tree/main/packages/barmark#readme",
34
+ "homepage": "https://www.barmark.dev",
35
35
  "repository": {
36
36
  "type": "git",
37
37
  "url": "git+https://github.com/kevinpeckham/barmark.git",