jpfun 1.0.0 → 1.1.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.
Files changed (51) hide show
  1. package/README.md +1 -1
  2. package/dist/functions/bar/index.js +3 -0
  3. package/dist/functions/default.js +2 -1
  4. package/dist/functions/gliss/index.js +81 -7
  5. package/dist/functions/grace/index.d.ts +1 -8
  6. package/dist/functions/grace/index.js +20 -48
  7. package/dist/functions/key/index.js +1 -0
  8. package/dist/functions/note/index.d.ts +5 -2
  9. package/dist/functions/note/index.js +158 -13
  10. package/dist/functions/note/source-transform.d.ts +8 -2
  11. package/dist/functions/note/source-transform.js +25 -11
  12. package/dist/functions/page/index.d.ts +1 -36
  13. package/dist/functions/page/index.js +4 -4
  14. package/dist/functions/set/index.js +2 -2
  15. package/dist/functions/stack/index.js +6 -4
  16. package/dist/functions/temporal.d.ts +3 -0
  17. package/dist/functions/text/index.js +2 -2
  18. package/dist/functions/up/index.js +9 -7
  19. package/dist/functions/voice/connections.js +2 -2
  20. package/dist/functions/voice/lyrics.d.ts +2 -0
  21. package/dist/functions/voice/lyrics.js +4 -4
  22. package/dist/functions/voice/voice.js +2 -2
  23. package/dist/functions/voice/voices.d.ts +2 -1
  24. package/dist/functions/voice/voices.js +2 -2
  25. package/dist/index.d.ts +6 -34
  26. package/dist/index.js +6 -34
  27. package/dist/jpfun.min.js +41 -41
  28. package/dist/layout/engine.js +13 -21
  29. package/dist/layout/model.d.ts +1 -1
  30. package/dist/layout/types.d.ts +2 -1
  31. package/dist/lowering/accidentalMemory.d.ts +33 -0
  32. package/dist/lowering/accidentalMemory.js +84 -0
  33. package/dist/lowering/loweringContext.js +4 -0
  34. package/dist/parser/grammarType.d.ts +6 -1
  35. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  36. package/dist/parser/parse-utils/string-utils.js +1 -1
  37. package/dist/parser/parserContext.d.ts +25 -25
  38. package/dist/parser/parserContext.js +54 -146
  39. package/dist/parser/preprocess.js +10 -23
  40. package/dist/parser/syntax.d.ts +9 -0
  41. package/dist/parser/syntax.js +109 -0
  42. package/dist/pipeline.js +3 -2
  43. package/dist/playback/compile.js +4 -6
  44. package/dist/playback/event.d.ts +1 -2
  45. package/dist/playback/event.js +2 -3
  46. package/dist/render/index.d.ts +1 -0
  47. package/dist/render/index.js +1 -0
  48. package/grammar.md +1 -0
  49. package/package.json +1 -1
  50. package/dist/functions/voice/index.d.ts +0 -2
  51. package/dist/functions/voice/index.js +0 -2
package/README.md CHANGED
@@ -77,7 +77,7 @@ The registry is shared across compilations. Names are case-insensitive, and late
77
77
 
78
78
  ### Note Transformations & Editor Analysis
79
79
 
80
- - `transformNotes(source, lowering, operation, ranges?)`: Returns `{ span, text }[]` edits for `"to-absolute"`, `"to-relative"`, `"semitone-up"`, or `"semitone-down"`. Use lowering from the exact same source; apply edits in one editor transaction or from right to left.
80
+ - `transformNotes(source, lowering, operation, ranges?, relower?)`: Returns `{ span, text }[]` edits for `"to-absolute"`, `"to-relative"`, `"semitone-up"`, or `"semitone-down"`. Use lowering from the exact same source; apply edits in one editor transaction or from right to left. Semitone shifts on numbered notes with `note.carry` enabled need `relower(source) => LoweringResult` to re-lower candidates and pin accidentals so other pitches stay unchanged.
81
81
  - `analyzeScoreSyntax(source, functions?)`: Fault-tolerant lexical/call analysis for real-time editor highlighting and completion.
82
82
  - `Diagnostic.format(code, message, params)`: Override to localize diagnostic messages.
83
83
 
@@ -192,6 +192,9 @@ class BarTemporalNode extends TemporalNodeBase {
192
192
  this.mergeKey = ANCHOR_KEY;
193
193
  this.initLayoutBox();
194
194
  }
195
+ onTimeState(state) {
196
+ state.accidentals.clear(this.track);
197
+ }
195
198
  /**
196
199
  * 给 bar 两侧的相邻元素增加 mu,避免被压缩到一起
197
200
  */
@@ -30,7 +30,8 @@ import { TremoloNode } from "./tremolo/index.js";
30
30
  import { VoltaNode } from "./volta/index.js";
31
31
  import { TieNode } from "./tie/index.js";
32
32
  import { TupletNode } from "./tuplet/index.js";
33
- import { VoiceNode, VoicesNode } from "./voice/index.js";
33
+ import { VoiceNode } from "./voice/voice.js";
34
+ import { VoicesNode } from "./voice/voices.js";
34
35
  export const defaultFunctions = [
35
36
  NoteNode, DashNode, RestNode, BarNode,
36
37
  DivNode, DotNode, TupletNode, TremoloNode, // 装饰性
@@ -62,6 +62,66 @@ function layoutHost(node, line) {
62
62
  }
63
63
  return node;
64
64
  }
65
+ /** 将刚性半宽提升至 min,并从同侧弹簧 margin 中等量扣减 */
66
+ function reserveSide(el, side, min) {
67
+ const w = side === "L" ? "WL" : "WR";
68
+ const m = side === "L" ? "margin_L" : "margin_R";
69
+ if (min > el[w]) {
70
+ el[m] = Math.max(0, el[w] + el[m] - min);
71
+ el[w] = min;
72
+ }
73
+ }
74
+ /** 在指定音轨行上按各列实际跨度比例预留 start..end 的最小锚点间距 */
75
+ function reserveSpan(line, track, from, to, minSpan) {
76
+ if (minSpan <= 0)
77
+ return;
78
+ line.registerHorizontalLayoutHook(from, to, ({ columns, rows, start, end, X, fixed }) => {
79
+ let row = 0;
80
+ while (row < rows && columns[start][row].time.track !== track)
81
+ row++;
82
+ if (row >= rows)
83
+ return;
84
+ let needed = minSpan;
85
+ let total = 0;
86
+ const gaps = new Float64Array(end - start);
87
+ for (let c = start; c < end; c++) {
88
+ if (fixed[c]) {
89
+ needed -= X[c + 1] - X[c];
90
+ continue;
91
+ }
92
+ let gap = 0;
93
+ for (let r = 0; r < rows; r++) {
94
+ const a = columns[c][r], b = columns[c + 1][r];
95
+ gap = Math.max(gap, a.WR + a.margin_R + b.WL + b.margin_L);
96
+ }
97
+ gaps[c - start] = gap;
98
+ total += gap;
99
+ }
100
+ if (needed <= 0)
101
+ return;
102
+ if (total <= 0) {
103
+ for (let c = start; c < end; c++) {
104
+ if (!fixed[c]) {
105
+ reserveSide(columns[c][row], "R", needed);
106
+ break;
107
+ }
108
+ }
109
+ return;
110
+ }
111
+ const scale = needed / total;
112
+ for (let c = start; c < end; c++) {
113
+ if (fixed[c])
114
+ continue;
115
+ const a = columns[c][row], b = columns[c + 1][row];
116
+ const target = gaps[c - start] * scale;
117
+ const wA = a.WR + a.margin_R;
118
+ const pair = wA + b.WL + b.margin_L;
119
+ const rightTarget = pair > 0 ? target * (wA / pair) : target / 2;
120
+ reserveSide(a, "R", rightTarget);
121
+ reserveSide(b, "L", target - rightTarget);
122
+ }
123
+ });
124
+ }
65
125
  class GlissAttachment {
66
126
  sourceSpan;
67
127
  kind = "gliss";
@@ -141,13 +201,27 @@ class GlissAttachment {
141
201
  const span = Math.max(endpoint.ast.size, target.ast.size) * 1.4;
142
202
  const right = from.box.w - from.box.anchor + span;
143
203
  // 只扩张求解器占位,不改变端点图形、附点位置或下一轮的 box
144
- fromLine.registerHorizontalLayoutHook(from, from, ({ columns }) => {
145
- // 留白作用于起点整列;取最大值,避免多条关系重复累加占位。
146
- for (const element of columns[start])
147
- element.WR = Math.max(element.WR, right);
148
- });
149
- if (fromLine !== toLine) {
150
- const left = to.box.anchor + span;
204
+ if (fromLine === toLine) {
205
+ reserveSpan(fromLine, from.track, from, to, right + to.box.anchor);
206
+ return;
207
+ }
208
+ const lastCol = fromLine.columns.length - 1;
209
+ if (start < lastCol) {
210
+ const lastRight = Math.max(...fromLine.columns[lastCol].map(h => h.box.w - h.box.anchor));
211
+ reserveSpan(fromLine, from.track, from, fromLine.columns[lastCol][0], right - lastRight);
212
+ }
213
+ else {
214
+ fromLine.registerHorizontalLayoutHook(from, from, ({ columns }) => {
215
+ for (const element of columns[start])
216
+ element.WR = Math.max(element.WR, right);
217
+ });
218
+ }
219
+ const left = to.box.anchor + span;
220
+ const entry = toLine.trackRuns.get(target.track)?.find(item => !item.T.isZero());
221
+ if (entry && toLine.columnOf(entry) < end) {
222
+ reserveSpan(toLine, to.track, entry, to, left - entry.box.anchor);
223
+ }
224
+ else {
151
225
  toLine.registerHorizontalLayoutHook(to, to, ({ columns }) => {
152
226
  for (const element of columns[end])
153
227
  element.WL = Math.max(element.WL, left);
@@ -22,16 +22,9 @@ declare class GraceFunction extends ASTFunctionNode {
22
22
  grace: ASTNodeBase;
23
23
  side: GraceSide;
24
24
  size: number;
25
- /**
26
- * `A > B`:前倚音必须左结合,而右操作数是把后续全部解析完才取的,
27
- * 所以 `1>2>3` 到这里已经成了 `1>(2>3)`。把 A 插回链条最深处就能恢复为 `(1>2)>3`
28
- */
29
- private static attachPre;
30
- private static create;
31
25
  get children(): ASTNodeBase[];
32
26
  timeFlowModel(): null;
33
- constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null, scale?: number);
34
- setGrace(node: ASTNodeBase, factor?: number): void;
27
+ constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
35
28
  private adopt;
36
29
  /** 宿主收敛成一个可见 Temporal,倚音展开成局部时间列,然后整体折叠进一个复合节点 */
37
30
  loweringEnter(ctx: LoweringContext, track: Track): GraceTemporal[];
@@ -23,8 +23,6 @@ const SHOULDER_PORT = "shoulder";
23
23
  * 所以只能在此刻回头改。这发生在 parse 进行中,不违反「AST parse 后只读」。
24
24
  */
25
25
  function scaleFontSize(node, factor) {
26
- if (factor === 1)
27
- return;
28
26
  const sized = node;
29
27
  if (typeof sized.size === "number")
30
28
  sized.size *= factor;
@@ -106,56 +104,31 @@ class GraceFunction extends ASTFunctionNode {
106
104
  if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
107
105
  return null;
108
106
  const side = n.data.side;
109
- const leftNode = ctx.takeLeftOperand();
107
+ // 箭头指向宿主:`1>2>3` 是 `{1>2}>3`,所以 `>` 登记 chain 左结合;`1<2<3` 是 `1<{2<3}`,`<` 保持右结合
108
+ const chain = side === "pre" ? GraceFunction : undefined;
109
+ const leftNode = ctx.takeLeftOperand(chain);
110
110
  if (!leftNode) {
111
111
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 左边没有找到目标", n.span);
112
112
  }
113
- const next = ctx.consumeRightOperand(nodes, at, right =>
114
- // '<' 的倚音在右侧,右结合的解析结果本来就是嵌套语义,不必像 '>' 那样重排
115
- side === "pre"
116
- ? GraceFunction.attachPre(leftNode, right, n.span, ctx)
117
- : GraceFunction.create(ctx, n.span, "post", leftNode, right));
118
- if (next !== null)
119
- return next;
120
- throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
113
+ const size = ctx.variables.fontsize; // 字号取算符所在处,不受右侧之后的 @set 影响
114
+ ctx.deferRightOperand(right => {
115
+ if (!right)
116
+ throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
117
+ const [host, grace] = side === "pre" ? [right, leftNode] : [leftNode, right];
118
+ const args = new Map([[0, host], [1, grace], ["side", side]]);
119
+ return Object.assign(new GraceFunction(n.span, args, ctx), { size });
120
+ }, chain);
121
+ return at;
121
122
  }
122
123
  host;
123
124
  grace;
124
125
  side = "pre";
125
126
  size;
126
- /**
127
- * `A > B`:前倚音必须左结合,而右操作数是把后续全部解析完才取的,
128
- * 所以 `1>2>3` 到这里已经成了 `1>(2>3)`。把 A 插回链条最深处就能恢复为 `(1>2)>3`
129
- */
130
- static attachPre(left, right, span, ctx) {
131
- if (right instanceof GraceFunction && right.side === "pre") {
132
- // 找到最深层的 pre
133
- let deepest = right;
134
- let depth = 1;
135
- while (deepest.grace instanceof GraceFunction && deepest.grace.side === "pre") {
136
- deepest = deepest.grace;
137
- depth++;
138
- }
139
- const scale = GRACE_SCALE ** depth;
140
- const inner = GraceFunction.create(ctx, span, "pre", deepest.grace, left, GRACE_SCALE * scale);
141
- inner.size *= scale;
142
- deepest.setGrace(inner, 1); // inner 内部已按深度缩放,不能再缩
143
- return right;
144
- }
145
- return GraceFunction.create(ctx, span, "pre", right, left);
146
- }
147
- static create(ctx, span, side, host, grace, scale = GRACE_SCALE) {
148
- const argMap = new Map();
149
- argMap.set(0, host);
150
- argMap.set(1, grace);
151
- argMap.set("side", side);
152
- return new GraceFunction(span, argMap, ctx, null, scale);
153
- }
154
127
  get children() {
155
128
  return [this.host, this.grace];
156
129
  }
157
130
  timeFlowModel() { return null; }
158
- constructor(span, args, ctx, parent = null, scale = GRACE_SCALE) {
131
+ constructor(span, args, ctx, parent = null) {
159
132
  super(span, parent);
160
133
  this.size = ctx.variables.fontsize;
161
134
  [this.host, this.grace, this.side] = this.getArgValue(args, ctx);
@@ -163,12 +136,8 @@ class GraceFunction extends ASTFunctionNode {
163
136
  throw new ErrorDiagnostic("E_GRACE_INVALID_SIDE", "@grace 的 side 参数必须是 'pre' 或 'post'", span);
164
137
  }
165
138
  this.adopt(this.host);
166
- this.setGrace(this.grace, scale);
167
- }
168
- setGrace(node, factor = GRACE_SCALE) {
169
- scaleFontSize(node, factor);
170
- this.grace = node;
171
- this.adopt(node);
139
+ this.adopt(this.grace);
140
+ scaleFontSize(this.grace, GRACE_SCALE);
172
141
  }
173
142
  adopt(node) {
174
143
  node.parent = this;
@@ -307,10 +276,13 @@ export class GraceTemporal extends TemporalNodeBase {
307
276
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
308
277
  this.host.T.copyFrom(this.T);
309
278
  let offset = undefined;
310
- for (const member of this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
279
+ const members = this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events];
280
+ const hostAt = members.indexOf(this.host);
281
+ for (const [index, member] of members.entries()) {
311
282
  member.t.copyFrom(this.t);
312
283
  member.layoutLine = this.layoutLine;
313
- const result = member.onTimeState?.(state);
284
+ // 宿主与同列其他音同时,前倚音依次在它之前,后倚音依次在它之后
285
+ const result = state.accidentals.at(index - hostAt, () => member.onTimeState?.(state));
314
286
  if (member === this.host) {
315
287
  this.T.copyFrom(member.T);
316
288
  offset = result;
@@ -103,6 +103,7 @@ class KeyTemporalNode extends TemporalNodeBase {
103
103
  }
104
104
  onTimeState(state) {
105
105
  state.keySignature = this.ast.tonality;
106
+ state.accidentals.clear();
106
107
  }
107
108
  prepareLayout(context) {
108
109
  const size = this.ast.size;
@@ -2,6 +2,9 @@ import { SourceSpan, ASTFunctionClass } from "../ASTtypes.js";
2
2
  import type { LoweringResult } from "../../lowering/types.js";
3
3
  import { type NoteTransform, type SourceEdit } from "./source-transform.js";
4
4
  export type { NoteTransform, SourceEdit } from "./source-transform.js";
5
- /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
6
- export declare function transformNotes(source: string, lowering: LoweringResult, operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
5
+ /**
6
+ * 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符。
7
+ * 乐谱中有开启 carry 的数字音名时,升降半音需要 relower 重新降级比对并补记
8
+ */
9
+ export declare function transformNotes(source: string, lowering: LoweringResult, operation: NoteTransform, ranges?: readonly SourceSpan[], relower?: (source: string) => LoweringResult): SourceEdit[];
7
10
  export declare const NoteNode: ASTFunctionClass;
@@ -3,9 +3,21 @@ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { parseNoteName } from "./noteName.js";
4
4
  import { getLayoutBounds } from "../../layout/engine.js";
5
5
  import { paintAccidental, placeAccidentals } from "./accidentals.js";
6
- import { rewriteNotes } from "./source-transform.js";
7
- /** 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符 */
8
- export function transformNotes(source, lowering, operation, ranges) {
6
+ import { rewriteNotes, selects } from "./source-transform.js";
7
+ /**
8
+ * 根据同一源码的 lowering 生成局部修改;传入 ranges 时只处理完整落入任一选区的音符。
9
+ * 乐谱中有开启 carry 的数字音名时,升降半音需要 relower 重新降级比对并补记
10
+ */
11
+ export function transformNotes(source, lowering, operation, ranges, relower) {
12
+ const notes = transformableNotes(lowering);
13
+ const carried = notes.find(note => note.ast.carry && /^[1-7]$/.test(note.ast.name));
14
+ if (!operation.startsWith("semitone") || !carried)
15
+ return rewriteNotes(source, notes, operation, ranges);
16
+ if (!relower)
17
+ throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "乐谱开启了 carry,升降半音需要重新降级", carried.ast.sourceSpan);
18
+ return pinnedSemitone(source, notes, operation, ranges, relower);
19
+ }
20
+ function transformableNotes(lowering) {
9
21
  const error = lowering.diagnostics.find(item => item instanceof ErrorDiagnostic);
10
22
  if (error)
11
23
  throw error;
@@ -14,7 +26,77 @@ export function transformNotes(source, lowering, operation, ranges) {
14
26
  const invalid = lowering.diagnostics.find(item => notes.some(note => item.span.start < note.ast.sourceSpan.end && item.span.end > note.ast.sourceSpan.start));
15
27
  if (invalid)
16
28
  throw invalid;
17
- return rewriteNotes(source, notes, operation, ranges);
29
+ return notes;
30
+ }
31
+ /** 按 AST 分组并按源码位置排序;同一 AST 的多个实例保持降级顺序 */
32
+ function byAst(notes) {
33
+ const groups = new Map();
34
+ for (const note of notes)
35
+ groups.set(note.ast, [...groups.get(note.ast) ?? [], note]);
36
+ return [...groups.values()].sort((a, b) => a[0].ast.sourceSpan.start - b[0].ast.sourceSpan.start);
37
+ }
38
+ /**
39
+ * 升降半音后重新降级,给读法变了的音补写显式记号,直到除选中音 ±1 之外所有音高不变。
40
+ * 每轮只补每个 (小节, 键) 中读谱顺序第一个不一致的音,后面的音可能因此恢复,所以补记最少。
41
+ * 补记的音只读自己的记号,每轮至少新增一个固定点,最多 音符数 + 1 轮。
42
+ */
43
+ function pinnedSemitone(source, notes, operation, ranges, relower) {
44
+ const delta = operation === "semitone-up" ? 1 : -1;
45
+ const old = byAst(notes);
46
+ const want = old.map(group => group.map(note => note.resolvedMidi === null ? null : note.resolvedMidi + (selects(ranges, note.ast.sourceSpan) ? delta : 0)));
47
+ function fail(span = old[0][0].ast.sourceSpan) {
48
+ throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "无法在保持其他音高不变的前提下升降半音", span);
49
+ }
50
+ const pins = new Map();
51
+ for (let round = 0; round <= old.length; round++) {
52
+ const edits = rewriteNotes(source, notes, operation, ranges, pins);
53
+ let fresh;
54
+ try {
55
+ fresh = byAst(transformableNotes(relower(applyEdits(source, edits))));
56
+ }
57
+ catch {
58
+ return fail();
59
+ }
60
+ if (fresh.length !== old.length)
61
+ fail();
62
+ const misses = [];
63
+ for (const [index, group] of fresh.entries()) {
64
+ const ast = old[index][0].ast;
65
+ if (group.length !== want[index].length)
66
+ fail(ast.sourceSpan);
67
+ for (const [instance, node] of group.entries()) {
68
+ const target = want[index][instance];
69
+ if (node.resolvedMidi === target)
70
+ continue;
71
+ // 已补记的音只读自己的记号,仍不一致就无解
72
+ if (target === null || !node.carrySlot || !/^[1-7]$/.test(node.ast.name) || pins.has(ast))
73
+ fail(ast.sourceSpan);
74
+ misses.push([ast, node, target, node.carrySlot]);
75
+ }
76
+ }
77
+ if (!misses.length)
78
+ return edits;
79
+ // 按读谱顺序:显式 @grace(1, {1 1}, side=pre) 的宿主写在前、读在后
80
+ const firsts = new Map();
81
+ for (const [ast, node, target, { bar, key }] of misses.sort((a, b) => a[3].seq - b[3].seq)) {
82
+ const keys = firsts.get(bar) ?? new Set();
83
+ if (keys.has(key))
84
+ continue;
85
+ firsts.set(bar, keys.add(key));
86
+ const offset = target - resolveNoteMidi(node.name, "", node.octave, node.keySignature);
87
+ const acc = offsetToAccidental(offset) || "n";
88
+ // 同一 AST 的多个实例要求不同记号时无解
89
+ if (Math.abs(offset) > 2 || (pins.get(ast) ?? acc) !== acc)
90
+ fail(ast.sourceSpan);
91
+ pins.set(ast, acc);
92
+ }
93
+ }
94
+ return fail();
95
+ }
96
+ function applyEdits(source, edits) {
97
+ for (const edit of [...edits].reverse())
98
+ source = source.slice(0, edit.span.start) + edit.text + source.slice(edit.span.end);
99
+ return source;
18
100
  }
19
101
  const JE_OCTAVE_OFFSET = "note.jeOctaveOffset";
20
102
  class NoteFunction extends ASTFunctionNode {
@@ -30,12 +112,13 @@ class NoteFunction extends ASTFunctionNode {
30
112
  - \`A#3\` 等价于 \`@note(A, #, 3)\`,默认 \`acc\` 为空时也等价于 \`@note(A#3)\`
31
113
  - \`#1'\` 等价于 \`@note(1, #, 1)\`,默认 \`acc\` 为空时也等价于 \`@note("#1'")\`
32
114
  - 支持组合升降号,如 \`A##bn99\`;无歧义时也接受后置写法,如 \`A3#\`、\`6#,,\`
33
- - 升降号后紧跟数字时归入下一音符:\`6#3\` 解析为 \`6\` 和 \`#3\``,
115
+ - 升降号后紧跟数字时归入下一音符:\`6#3\` 解析为 \`6\` 和 \`#3\`
116
+ - 末尾加 \`!\` 等价于 \`force=true\`:\`C4!\` 等价于 \`@note(C, "", 4, force=true)\``,
34
117
  allowExtraArgs: false,
35
118
  args: [
36
119
  {
37
120
  name: "name",
38
- description: "数字音名或大写字母音名,可自带升降号与八度;`0` / `Z` 为休止符,`8` 为隐形占位,`9` / `X` 为节拍记号,后三类不显示升降号和八度点",
121
+ description: "数字音名或大写字母音名,可自带升降号与八度,末尾的 `!` 等价于 `force=true`;`0` / `Z` 为休止符,`8` 为隐形占位,`9` / `X` 为节拍记号,后三类不显示升降号和八度点",
39
122
  type: "string",
40
123
  default: null,
41
124
  },
@@ -56,7 +139,20 @@ class NoteFunction extends ASTFunctionNode {
56
139
  description: "音符颜色,使用 CSS 颜色值",
57
140
  type: "string",
58
141
  default: "#000",
59
- }
142
+ },
143
+ {
144
+ name: "carry",
145
+ namedOnly: true,
146
+ description: "小节内变音延续:数字音名按本小节前文读谱,字母音名自动省略或补记变音号",
147
+ type: "boolean",
148
+ default: false,
149
+ },
150
+ {
151
+ name: "force",
152
+ description: "强制显示实际生效的变音号,不改变音高,没有变音时显示还原号;简写为音名末尾的 `!`",
153
+ type: "boolean",
154
+ default: false,
155
+ },
60
156
  ]
61
157
  };
62
158
  static deSugarAtom(source, start, end) {
@@ -86,20 +182,25 @@ class NoteFunction extends ASTFunctionNode {
86
182
  const parseResult = parseNoteName(source, start, end, false);
87
183
  if (!parseResult)
88
184
  return null;
185
+ // 末尾的 `!` 是 force=true 的简写;没写时继承 @set(note.force=...)
186
+ const force = parseResult.next < end && source[parseResult.next] === "!";
187
+ const next = parseResult.next + (force ? 1 : 0);
89
188
  const argMap = new Map();
90
189
  argMap.set("name", parseResult.name);
91
190
  if (parseResult.octave !== null)
92
191
  argMap.set("octave", parseResult.octave);
93
192
  argMap.set("acc", parseResult.acc ?? ""); // 必须覆盖不然会用到 set 的默认值
193
+ if (force)
194
+ argMap.set("force", true);
94
195
  const node = {
95
196
  kind: "call",
96
197
  typed: true,
97
198
  name: "note",
98
199
  args: argMap,
99
- span: { start, end: parseResult.next },
200
+ span: { start, end: next },
100
201
  syntaxKind: "atom",
101
202
  };
102
- return { next: parseResult.next, node };
203
+ return { next, node };
103
204
  }
104
205
  static deSugarRelation(ctx, nodes, at) {
105
206
  const node = nodes[at];
@@ -120,6 +221,8 @@ class NoteFunction extends ASTFunctionNode {
120
221
  octave;
121
222
  acc;
122
223
  color;
224
+ carry;
225
+ force;
123
226
  size;
124
227
  font;
125
228
  weight;
@@ -127,14 +230,27 @@ class NoteFunction extends ASTFunctionNode {
127
230
  jeOctaveOffset;
128
231
  // 源码改写时判断是否需要覆盖默认升降号
129
232
  hasDefaultAcc;
233
+ // 去糖时判断是否需要写明 carry、force
234
+ hasDefaultCarry;
235
+ hasDefaultForce;
130
236
  constructor(sourceSpan, args, ctx, parent = null) {
131
237
  super(sourceSpan, parent);
132
238
  this.hasDefaultAcc = Boolean(ctx.variables["note.acc"]);
133
- [this.name, this.acc, this.octave, this.color] = this.getArgValue(args, ctx);
239
+ this.hasDefaultCarry = Boolean(ctx.variables["note.carry"]);
240
+ this.hasDefaultForce = Boolean(ctx.variables["note.force"]);
241
+ [this.name, this.acc, this.octave, this.color, this.carry, this.force] =
242
+ this.getArgValue(args, ctx);
134
243
  this.font = ctx.variables.numberfont;
135
244
  this.weight = ctx.variables.numberweight;
136
245
  this.size = ctx.variables.fontsize;
137
246
  // 创建时就固化参数值
247
+ // name 末尾的 `!` 同简写,等价于 force=true;carry 仅命名,所以 force 的位置下标是 4
248
+ if (this.name.endsWith("!")) {
249
+ if ((args.get("force") ?? args.get(4)) === false)
250
+ throw new ErrorDiagnostic("E_NOTE_FORCE_CONFLICT", '函数 @note 的参数 "force=false" 与音符名称末尾的 "!" 冲突', sourceSpan);
251
+ this.name = this.name.slice(0, -1);
252
+ this.force = true;
253
+ }
138
254
  // 校验 note name
139
255
  const parseResult = parseNoteName(this.name);
140
256
  if (parseResult instanceof Diagnostic) {
@@ -163,12 +279,15 @@ class NoteFunction extends ASTFunctionNode {
163
279
  this.acc = parseResult.acc + this.acc;
164
280
  }
165
281
  toString() {
166
- return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color})`;
282
+ // 外层开启过时写明,避免 false 去糖后继承外层的 true
283
+ const carry = this.carry || this.hasDefaultCarry ? `, carry=${this.carry}` : "";
284
+ const force = this.force || this.hasDefaultForce ? `, force=${this.force}` : "";
285
+ return `@n(${this.name}, ${this.acc || '""'}, ${this.octave}, ${this.color}${carry}${force})`;
167
286
  }
168
287
  }
169
288
  export const NoteNode = NoteFunction;
170
289
  import { DEFAULT_KEY, DEFAULT_TONALITY, DEFAULT_VELOCITY, TemporalNodeBase } from "../temporal.js";
171
- import { createDiatonicTranspose, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
290
+ import { acc2Offset, createDiatonicTranspose, offsetToAccidental, resolveLetterNameToJianpu, resolveNoteMidi, } from "../../parser/parse-utils/note-utils.js";
172
291
  // 8 是隐形占位,9 是固定打击音的节拍记号,空串表示不绘制
173
292
  const NOTE_GLYPH = { "8": "", "9": "X" };
174
293
  class NoteTemporalNode extends TemporalNodeBase {
@@ -179,6 +298,8 @@ class NoteTemporalNode extends TemporalNodeBase {
179
298
  name; // 数字
180
299
  acc; // 升降号
181
300
  octave; // 绝对值为点的个数
301
+ displayAcc; // carry 开启的字母音名或 force 推导出的显示记号;undefined 表示按 acc 显示
302
+ carrySlot; // 本音在变音记忆中的位置
182
303
  /** prepareLayout 生成的局部升降号位置 */
183
304
  accidentals = [];
184
305
  /** 字号和颜色在解析时已经固化,样式随之不再变 */
@@ -206,7 +327,7 @@ class NoteTemporalNode extends TemporalNodeBase {
206
327
  const mainMetrics = context.textMeasurer.measureText("0", this.numberStyle);
207
328
  this.numberY = mainMetrics.baseline;
208
329
  // 升降号盒直接紧挨数字盒左缘,按同一 baseline 排在数字左侧
209
- const { placed, right: mainX } = placeAccidentals(this.acc, size, 0, this.numberY);
330
+ const { placed, right: mainX } = placeAccidentals(this.displayAcc ?? this.acc, size, 0, this.numberY);
210
331
  this.accidentals = placed;
211
332
  this.box.w = mainX + mainMetrics.w;
212
333
  this.box.h = mainMetrics.h;
@@ -290,6 +411,30 @@ class NoteTemporalNode extends TemporalNodeBase {
290
411
  }
291
412
  }
292
413
  this.transposeDiatonic = createDiatonicTranspose(this.name, this.octave, keySignature);
414
+ this.applyAccidentals(state.accidentals);
415
+ }
416
+ /**
417
+ * 以显示出来的记号写入记忆;carry 下数字音名没写记号时沿用前文,字母音名按前文省略或补记。
418
+ * force 只改显示:写出实际生效的记号,没有变音时显示还原号。前文要到列末按时间先后结算
419
+ */
420
+ applyAccidentals(memory) {
421
+ const midi = this.resolvedMidi;
422
+ if (midi === null || !/^[1-7]$/.test(this.name))
423
+ return;
424
+ memory.read(this.track, `${this.name}:${this.octave}`, reading => {
425
+ const { prior } = this.carrySlot = reading;
426
+ const digit = /^[1-7]$/.test(this.ast.name);
427
+ const carried = this.ast.carry && digit && !this.acc;
428
+ const offset = carried ? prior : acc2Offset(this.acc);
429
+ if (carried)
430
+ this.resolvedMidi = midi + prior;
431
+ const shown = offsetToAccidental(offset) || "n";
432
+ if (this.ast.force)
433
+ this.displayAcc = shown;
434
+ else if (this.ast.carry && !digit)
435
+ this.displayAcc = offset === prior ? "" : shown;
436
+ return this.displayAcc ?? this.acc ? offset : undefined;
437
+ });
293
438
  }
294
439
  /** 发布完整音段或无声区间,实际 NoteOn/NoteOff 留到声音展开完成后生成 */
295
440
  emitPlayback(emitter) {
@@ -16,7 +16,10 @@ interface NoteSource {
16
16
  };
17
17
  resolvedMidi: number | null;
18
18
  keySignature: string;
19
+ displayAcc?: string;
19
20
  }
21
+ /** 未传 ranges 视为全选;否则音符须完整落入任一选区 */
22
+ export declare function selects(ranges: readonly SourceSpan[] | undefined, span: SourceSpan): boolean;
20
23
  /**
21
24
  * 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装。
22
25
  * 沿 AST 父链定位最近一层显式函数调用 `@call(...)` 及目标音符所属实参,
@@ -31,6 +34,9 @@ export interface NotePitch {
31
34
  }
32
35
  /** 改写显式 `@note(...)` 的音高:已有实参只改值,缺失的追加为命名参数;存在默认 acc 时显式写出 acc 以覆盖它 */
33
36
  export declare function rewriteNoteCall(source: string, masked: string, call: CallInfo, pitch: NotePitch, hasDefaultAcc: boolean, edits?: SourceEdit[]): SourceEdit[];
34
- /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
35
- export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[]): SourceEdit[];
37
+ /**
38
+ * edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符。
39
+ * pins 给指定音符强制写出升降号(升降半音后为保持 carry 下其他音高不变而补记)
40
+ */
41
+ export declare function rewriteNotes(source: string, notes: readonly NoteSource[], operation: NoteTransform, ranges?: readonly SourceSpan[], pins?: ReadonlyMap<ASTNodeBase, string>): SourceEdit[];
36
42
  export {};