jpfun 1.0.0 → 1.2.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 (83) hide show
  1. package/README.md +1 -1
  2. package/dist/diagnostic.d.ts +1 -0
  3. package/dist/diagnostic.js +1 -0
  4. package/dist/functions/ASTtypes.d.ts +2 -3
  5. package/dist/functions/ASTtypes.js +2 -3
  6. package/dist/functions/adjust/index.js +15 -67
  7. package/dist/functions/bar/index.js +11 -7
  8. package/dist/functions/beam/auto.js +15 -11
  9. package/dist/functions/beam/layout.js +22 -48
  10. package/dist/functions/br/index.d.ts +9 -3
  11. package/dist/functions/br/index.js +20 -16
  12. package/dist/functions/dash/index.js +13 -11
  13. package/dist/functions/default.js +2 -1
  14. package/dist/functions/div/index.d.ts +2 -2
  15. package/dist/functions/div/index.js +5 -9
  16. package/dist/functions/dot/index.js +5 -9
  17. package/dist/functions/dyn/index.js +125 -53
  18. package/dist/functions/gliss/index.js +81 -7
  19. package/dist/functions/grace/index.d.ts +3 -10
  20. package/dist/functions/grace/index.js +25 -57
  21. package/dist/functions/head/index.js +6 -7
  22. package/dist/functions/key/index.js +1 -0
  23. package/dist/functions/meter/index.js +7 -5
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +162 -19
  26. package/dist/functions/note/source-transform.d.ts +8 -2
  27. package/dist/functions/note/source-transform.js +25 -11
  28. package/dist/functions/ottava/index.js +8 -7
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +11 -15
  31. package/dist/functions/pagebreak/index.js +2 -1
  32. package/dist/functions/rest/index.js +5 -5
  33. package/dist/functions/set/index.js +2 -2
  34. package/dist/functions/stack/index.js +7 -7
  35. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  36. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  37. package/dist/functions/tempo/index.js +8 -3
  38. package/dist/functions/temporal.d.ts +21 -6
  39. package/dist/functions/temporal.js +1 -1
  40. package/dist/functions/text/index.js +3 -5
  41. package/dist/functions/up/index.js +37 -34
  42. package/dist/functions/voice/connections.js +2 -2
  43. package/dist/functions/voice/lyrics.d.ts +2 -0
  44. package/dist/functions/voice/lyrics.js +4 -4
  45. package/dist/functions/voice/voice.d.ts +2 -1
  46. package/dist/functions/voice/voice.js +9 -15
  47. package/dist/functions/voice/voices.d.ts +6 -4
  48. package/dist/functions/voice/voices.js +10 -10
  49. package/dist/index.d.ts +6 -34
  50. package/dist/index.js +6 -34
  51. package/dist/jpfun.min.js +49 -46
  52. package/dist/layout/engine.js +237 -232
  53. package/dist/layout/model.d.ts +1 -1
  54. package/dist/layout/page.d.ts +2 -2
  55. package/dist/layout/page.js +8 -22
  56. package/dist/layout/types.d.ts +4 -5
  57. package/dist/lowering/accidentalMemory.d.ts +33 -0
  58. package/dist/lowering/accidentalMemory.js +84 -0
  59. package/dist/lowering/loweringContext.d.ts +12 -7
  60. package/dist/lowering/loweringContext.js +54 -51
  61. package/dist/lowering/types.d.ts +2 -3
  62. package/dist/parser/grammarType.d.ts +10 -4
  63. package/dist/parser/parse-utils/brace-utils.js +4 -3
  64. package/dist/parser/parse-utils/call-utils.js +7 -7
  65. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  66. package/dist/parser/parse-utils/string-utils.js +1 -1
  67. package/dist/parser/parserContext.d.ts +30 -34
  68. package/dist/parser/parserContext.js +77 -181
  69. package/dist/parser/preprocess.js +10 -23
  70. package/dist/parser/syntax.d.ts +9 -0
  71. package/dist/parser/syntax.js +109 -0
  72. package/dist/parser/types.d.ts +2 -1
  73. package/dist/pipeline.js +3 -2
  74. package/dist/playback/compile.js +26 -18
  75. package/dist/playback/event.d.ts +1 -2
  76. package/dist/playback/event.js +2 -3
  77. package/dist/playback/types.d.ts +0 -1
  78. package/dist/render/index.d.ts +1 -0
  79. package/dist/render/index.js +1 -0
  80. package/grammar.md +8 -6
  81. package/package.json +2 -2
  82. package/dist/functions/voice/index.d.ts +0 -2
  83. package/dist/functions/voice/index.js +0 -2
@@ -42,36 +42,32 @@ class DotFunction extends ASTFunctionNode {
42
42
  }
43
43
  if (dotCnt === 0)
44
44
  return null;
45
- // 对前一个节点的探查放到 deSugarRelation 中
45
+ // 对前一个节点的探查放到 relation 中
46
46
  const node = {
47
47
  kind: "sugar",
48
- data: {
49
- class: DotFunction,
50
- n: dotCnt,
51
- },
48
+ data: dotCnt,
52
49
  span: { start, end: pos },
50
+ relation: DotFunction.deSugarRelation,
53
51
  };
54
52
  return { next: pos, node };
55
53
  }
56
54
  ;
57
55
  static deSugarRelation(ctx, nodes, at) {
58
56
  const n = nodes[at++];
59
- if (n.data?.class !== DotFunction)
60
- return null;
61
57
  const prevIndex = ctx.findLastOperandIndex();
62
58
  if (prevIndex < 0)
63
59
  return at; // 没有了 直接当作无效文本跳过
64
60
  const prev = ctx.nodes[prevIndex];
65
61
  if (prev instanceof DotFunction) {
66
62
  // 已经是dot了 继续加深
67
- prev.n += n.data.n;
63
+ prev.n += n.data;
68
64
  prev.sourceSpan.end = Math.max(prev.sourceSpan.end, n.span.end);
69
65
  return at;
70
66
  }
71
67
  // 参数数量不校验 在构造函数里写
72
68
  const argMap = new Map();
73
69
  argMap.set(0, prev);
74
- argMap.set("n", n.data.n);
70
+ argMap.set("n", n.data);
75
71
  const spanPrev = prev.sourceSpan;
76
72
  ctx.nodes[prevIndex] = new DotFunction({
77
73
  start: Math.min(spanPrev.start, n.span.start),
@@ -1,7 +1,9 @@
1
1
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { lineEntryX, lineRightX } from "../../layout/range.js";
3
3
  import { isVisualTemporalNode, } from "../temporal.js";
4
+ import { dynamicMarkVelocity } from "../symbol/symbols/dynamics.js";
4
5
  import { ASTFunctionNode, } from "../ASTtypes.js";
6
+ const clampVelocity = (velocity) => Math.max(1, Math.min(127, velocity));
5
7
  function findRecordBoundary(records, time, after = false) {
6
8
  let low = 0;
7
9
  let high = records.length;
@@ -15,6 +17,33 @@ function findRecordBoundary(records, time, after = false) {
15
17
  }
16
18
  return low;
17
19
  }
20
+ function addIncrement(track, start, end, offset, slope = 0) {
21
+ if (start >= end)
22
+ return;
23
+ track.offset[start] += offset;
24
+ track.offset[end] -= offset;
25
+ track.slope[start] += slope;
26
+ track.slope[end] -= slope;
27
+ }
28
+ /** 在 [from, endStart) 的音符上叠加从 0 线性变化到 delta 的增量 */
29
+ function addRamp(track, dynamic, endStart, delta) {
30
+ const from = dynamic.fromHost.t;
31
+ const slope = delta / dynamic.toHost.t.clone().sub(from).toNumber();
32
+ addIncrement(track, findRecordBoundary(track.records, from), endStart, -slope * from.toNumber(), slope);
33
+ }
34
+ /** 把差分数组结算进 increments,并按可听范围限幅 */
35
+ function settle({ records, times, increments, offset, slope }) {
36
+ let a = 0;
37
+ let k = 0;
38
+ for (let i = 0; i < records.length; i++) {
39
+ a += offset[i];
40
+ k += slope[i];
41
+ const velocity = records[i].velocity;
42
+ increments[i] = clampVelocity(velocity + increments[i] + a + k * times[i]) - velocity;
43
+ }
44
+ offset.fill(0);
45
+ slope.fill(0);
46
+ }
18
47
  class DynFunction extends ASTFunctionNode {
19
48
  static def = {
20
49
  name: ["dyn"],
@@ -24,7 +53,9 @@ class DynFunction extends ASTFunctionNode {
24
53
  1 ^ $p 2@a 3 4@b
25
54
  @dyn(a, b, 24)
26
55
  ~~~
27
- 端点须位于同一音轨、不同时间;变化量沿区间线性增加,叠加在每个音符原有力度上。本例从 \`a\` 到 \`b\` 渐强,终点增加 24 的力度。
56
+ 端点须位于同一音轨、不同时间;变化量沿区间线性增加,叠加在每个音符原有力度上,并保持到下一个力度记号。本例从 \`a\` 到 \`b\` 渐强,终点增加 24 的力度。
57
+
58
+ 终点同一时刻有力度记号时,以该记号为目标线性过渡,不再叠加 \`dv\`。
28
59
 
29
60
  端点也可标在增时线上。终点没有力度时,取同轨、不晚于终点的最后一个原始力度作为保持基准;找不到时给出警告并仅绘制。增时线延续的音符保持起音时的力度。`,
30
61
  allowExtraArgs: false,
@@ -35,61 +66,91 @@ class DynFunction extends ASTFunctionNode {
35
66
  ],
36
67
  };
37
68
  static loweringFinalize(result) {
38
- const dynamics = result.attachments.filter((attachment) => attachment instanceof DynAttachment);
69
+ const dynamics = result.attachments.filter((attachment) => attachment instanceof DynAttachment && attachment.orient());
39
70
  if (dynamics.length === 0)
40
71
  return;
41
72
  // 仅收集存在 @dyn 的音轨上的记录,避免无关声部也分配包装对象与排序
42
- const recordsByTrack = new Map(dynamics.map(d => [d.track, []]));
73
+ const lists = new Map(dynamics.map(d => [d.track, { records: [], marks: [] }]));
43
74
  for (const nodes of result.astToTemporal.values()) {
44
75
  for (const node of nodes) {
45
- const velocity = node.playbackState?.velocity;
46
- if (velocity === undefined)
47
- continue;
48
76
  const host = node.rootHost;
49
- recordsByTrack.get(host.track)?.push({ node, host, velocity, increment: 0 });
77
+ const list = lists.get(host.track);
78
+ if (!list)
79
+ continue;
80
+ const velocity = node.playbackState?.velocity;
81
+ if (velocity !== undefined)
82
+ list.records.push({ node, host, velocity });
83
+ const mark = dynamicMarkVelocity(node);
84
+ if (mark !== undefined)
85
+ list.marks.push({ node, host, velocity: mark });
50
86
  }
51
87
  }
52
- for (const list of recordsByTrack.values()) {
53
- list.sort((left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order);
88
+ const byTime = (left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order;
89
+ const tracks = new Map();
90
+ for (const [track, { records, marks }] of lists) {
91
+ records.sort(byTime);
92
+ marks.sort(byTime);
93
+ const length = records.length;
94
+ const runEnd = new Int32Array(length);
95
+ for (let i = length - 1; i >= 0; i--) {
96
+ runEnd[i] = i + 1 < length && records[i + 1].velocity === records[i].velocity ? runEnd[i + 1] : i + 1;
97
+ }
98
+ tracks.set(track, {
99
+ records,
100
+ marks,
101
+ runEnd,
102
+ times: Float64Array.from(records, record => record.host.t.toNumber()),
103
+ increments: new Float64Array(length),
104
+ offset: new Float64Array(length + 1),
105
+ slope: new Float64Array(length + 1),
106
+ });
54
107
  }
55
- // 先累计全部 dyn 的贡献,最后统一写回,避免声明顺序改变后续 dyn 读取的原始力度
108
+ // 先结算没有终点记号的渐变;以记号为目标的渐变要从这些增量生效后的力度出发
109
+ const targeted = [];
56
110
  for (const dynamic of dynamics) {
57
- const records = recordsByTrack.get(dynamic.track);
58
- const endStart = findRecordBoundary(records, dynamic.toHost.t);
59
- const afterEnd = findRecordBoundary(records, dynamic.toHost.t, true);
60
- let endVelocity = dynamic.end.playbackState?.velocity;
61
- for (let i = endStart; endVelocity === undefined && i < afterEnd; i++) {
62
- if (records[i].host === dynamic.toHost)
63
- endVelocity = records[i].velocity;
64
- }
65
- endVelocity ??= records[afterEnd - 1]?.velocity;
66
- if (endVelocity === undefined) {
111
+ const track = tracks.get(dynamic.track);
112
+ const { records, marks, runEnd } = track;
113
+ const to = dynamic.toHost.t;
114
+ const endStart = findRecordBoundary(records, to);
115
+ const afterEnd = findRecordBoundary(records, to, true);
116
+ if (afterEnd === 0) {
67
117
  result.diagnostics.push(new WarningDiagnostic("W_DYN_NO_VELOCITY", "@dyn 终点及此前同轨没有可用的力度基准,仅绘制渐变线", dynamic.sourceSpan));
68
118
  continue;
69
119
  }
70
- // 终点后保持完整增量,直到原始力度相对终点再次发生变化
71
- let stopIndex = records.length;
72
- for (let i = afterEnd; i < records.length; i++) {
73
- if (records[i].velocity !== endVelocity) {
74
- stopIndex = findRecordBoundary(records, records[i].host.t);
75
- break;
76
- }
77
- }
78
- const startIndex = findRecordBoundary(records, dynamic.fromHost.t);
79
- const duration = dynamic.toHost.t.clone().sub(dynamic.fromHost.t);
80
- for (let i = startIndex; i < stopIndex; i++) {
81
- const progress = i >= endStart ? 1
82
- : records[i].host.t.clone().sub(dynamic.fromHost.t).div(duration).toNumber();
83
- records[i].increment += dynamic.dv * progress;
120
+ const mark = marks[findRecordBoundary(marks, to, true) - 1];
121
+ if (mark?.host.t.equals(to)) {
122
+ // 同刻的记号与折叠成员先后不定,以终点最后取样的力度为目标
123
+ const sampled = records[afterEnd - 1];
124
+ targeted.push([dynamic, sampled.host.t.equals(to) ? sampled.velocity : mark.velocity]);
125
+ continue;
84
126
  }
127
+ // 保持到下一个力度记号(同值重写也算)或原始力度变化(兼顾其他写入力度的函数)
128
+ let stopIndex = runEnd[afterEnd - 1];
129
+ if (stopIndex < records.length)
130
+ stopIndex = findRecordBoundary(records, records[stopIndex].host.t);
131
+ const nextMark = marks[findRecordBoundary(marks, to, true)];
132
+ if (nextMark)
133
+ stopIndex = Math.min(stopIndex, findRecordBoundary(records, nextMark.host.t));
134
+ addRamp(track, dynamic, endStart, dynamic.dv);
135
+ addIncrement(track, endStart, stopIndex, dynamic.dv);
85
136
  }
86
- for (const records of recordsByTrack.values()) {
87
- for (const record of records) {
88
- if (record.increment === 0)
89
- continue;
90
- const velocity = Math.max(1, Math.min(127, record.velocity + record.increment));
91
- record.node.playbackState = { ...record.node.playbackState, velocity };
92
- }
137
+ for (const track of tracks.values())
138
+ settle(track);
139
+ for (const [dynamic, target] of targeted) {
140
+ const track = tracks.get(dynamic.track);
141
+ const last = findRecordBoundary(track.records, dynamic.toHost.t) - 1;
142
+ if (last < 0)
143
+ continue;
144
+ addRamp(track, dynamic, last + 1, target - track.records[last].velocity - track.increments[last]);
145
+ }
146
+ for (const track of tracks.values()) {
147
+ settle(track);
148
+ track.records.forEach((record, i) => {
149
+ // 容差吸收差分累加的浮点误差,避免半整数被算成略小于 .5
150
+ const velocity = Math.round(record.velocity + track.increments[i] + 1e-9);
151
+ if (velocity !== record.velocity)
152
+ record.node.playbackState = { ...record.node.playbackState, velocity };
153
+ });
93
154
  }
94
155
  }
95
156
  from;
@@ -112,15 +173,11 @@ class DynFunction extends ASTFunctionNode {
112
173
  if (fromHost.track !== toHost.track) {
113
174
  throw new ErrorDiagnostic("E_DYN_CROSS_TRACK", "@dyn 的两个端点必须位于同一音轨", this.sourceSpan);
114
175
  }
115
- if (fromHost.t.equals(toHost.t)) {
116
- throw new ErrorDiagnostic("E_DYN_ZERO_SPAN", "@dyn 的两个端点必须位于不同时间", this.sourceSpan);
117
- }
118
- if (fromHost.t.compare(toHost.t) < 0) {
119
- ctx.addAttachment(new DynAttachment(this, to, fromHost, toHost));
120
- }
121
- else {
122
- ctx.addAttachment(new DynAttachment(this, from, toHost, fromHost));
123
- }
176
+ // 此时的先后已可信(插入偏移只推后后续列);同刻端点留到时间固化后再判断
177
+ const order = fromHost.t.compare(toHost.t);
178
+ ctx.addAttachment(order > 0
179
+ ? new DynAttachment(this, toHost, fromHost, false)
180
+ : new DynAttachment(this, fromHost, toHost, order === 0));
124
181
  ctx.deferFinalize(DynFunction.loweringFinalize);
125
182
  return [];
126
183
  }
@@ -148,16 +205,31 @@ class DynFunction extends ASTFunctionNode {
148
205
  export const DynNode = DynFunction;
149
206
  class DynAttachment {
150
207
  ast;
151
- end;
152
208
  fromHost;
153
209
  toHost;
210
+ unordered;
154
211
  kind = "dyn";
155
212
  layer = "foreground";
156
- constructor(ast, end, fromHost, toHost) {
213
+ constructor(ast, fromHost, toHost,
214
+ /** lowering 时两端同刻,方向要等时间固化后才能确定 */
215
+ unordered) {
157
216
  this.ast = ast;
158
- this.end = end;
159
217
  this.fromHost = fromHost;
160
218
  this.toHost = toHost;
219
+ this.unordered = unordered;
220
+ }
221
+ /**
222
+ * 按最终时间确定方向,返回是否影响播放
223
+ * 倚音序列等局部时间轴上的渐变会投影到同一宿主时刻,只绘制
224
+ */
225
+ orient() {
226
+ const cmp = this.fromHost.t.compare(this.toHost.t);
227
+ if (cmp === 0 && this.unordered) {
228
+ throw new ErrorDiagnostic("E_DYN_ZERO_SPAN", "@dyn 的两个端点必须位于不同时间", this.sourceSpan);
229
+ }
230
+ if (cmp > 0)
231
+ [this.fromHost, this.toHost] = [this.toHost, this.fromHost];
232
+ return cmp !== 0;
161
233
  }
162
234
  get sourceSpan() { return this.ast.sourceSpan; }
163
235
  get endPoints() { return [this.fromHost, this.toHost]; }
@@ -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);
@@ -4,7 +4,7 @@ import type { LoweringAttachment } from "../../lowering/types.js";
4
4
  import { Fraction } from "../../fraction.js";
5
5
  import { Track } from "../../lowering/track.js";
6
6
  import { TemporalNodeBase, type TimeState, type VisualTemporalNode } from "../temporal.js";
7
- import { GrammarNode, GrammarSugarNode } from "../../parser/grammarType.js";
7
+ import { GrammarSugarNode } from "../../parser/grammarType.js";
8
8
  import { ParserContext } from "../../parser/parserContext.js";
9
9
  import type { Painter } from "../../render/types.js";
10
10
  import type { PlaybackEmitter } from "../../playback/types.js";
@@ -17,21 +17,14 @@ declare class GraceFunction extends ASTFunctionNode {
17
17
  next: number;
18
18
  node: GrammarSugarNode;
19
19
  } | null;
20
- static deSugarRelation(ctx: ParserContext, nodes: (GrammarNode | number)[], at: number): number | null;
20
+ private static deSugarRelation;
21
21
  host: ASTNodeBase;
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;
@@ -92,70 +90,41 @@ class GraceFunction extends ASTFunctionNode {
92
90
  next: start + 1,
93
91
  node: {
94
92
  kind: "sugar",
95
- data: {
96
- class: GraceFunction,
97
- side: char
98
- },
99
- span: { start, end: start + 1 }
93
+ data: char,
94
+ span: { start, end: start + 1 },
95
+ relation: GraceFunction.deSugarRelation,
100
96
  }
101
97
  };
102
98
  }
103
99
  // 取左右操作数的流程同 stack / up
104
100
  static deSugarRelation(ctx, nodes, at) {
105
101
  const n = nodes[at++];
106
- if (n.kind !== "sugar" || n.data?.class !== GraceFunction)
107
- return null;
108
- const side = n.data.side;
109
- const leftNode = ctx.takeLeftOperand();
102
+ const side = n.data;
103
+ // 箭头指向宿主:`1>2>3` 是 `{1>2}>3`,所以 `>` 登记 chain 左结合;`1<2<3` 是 `1<{2<3}`,`<` 保持右结合
104
+ const chain = side === "pre" ? GraceFunction : undefined;
105
+ const leftNode = ctx.takeLeftOperand(chain);
110
106
  if (!leftNode) {
111
107
  throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 左边没有找到目标", n.span);
112
108
  }
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);
109
+ const size = ctx.variables.fontsize; // 字号取算符所在处,不受右侧之后的 @set 影响
110
+ ctx.deferRightOperand(right => {
111
+ if (!right)
112
+ throw new ErrorDiagnostic("E_GRACE_NO_TARGET", "@grace语法糖错误: 右边没有找到目标", n.span);
113
+ const [host, grace] = side === "pre" ? [right, leftNode] : [leftNode, right];
114
+ const args = new Map([[0, host], [1, grace], ["side", side]]);
115
+ return Object.assign(new GraceFunction(n.span, args, ctx), { size });
116
+ }, chain);
117
+ return at;
121
118
  }
122
119
  host;
123
120
  grace;
124
121
  side = "pre";
125
122
  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
123
  get children() {
155
124
  return [this.host, this.grace];
156
125
  }
157
126
  timeFlowModel() { return null; }
158
- constructor(span, args, ctx, parent = null, scale = GRACE_SCALE) {
127
+ constructor(span, args, ctx, parent = null) {
159
128
  super(span, parent);
160
129
  this.size = ctx.variables.fontsize;
161
130
  [this.host, this.grace, this.side] = this.getArgValue(args, ctx);
@@ -163,12 +132,8 @@ class GraceFunction extends ASTFunctionNode {
163
132
  throw new ErrorDiagnostic("E_GRACE_INVALID_SIDE", "@grace 的 side 参数必须是 'pre' 或 'post'", span);
164
133
  }
165
134
  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);
135
+ this.adopt(this.grace);
136
+ scaleFontSize(this.grace, GRACE_SCALE);
172
137
  }
173
138
  adopt(node) {
174
139
  node.parent = this;
@@ -200,7 +165,7 @@ class GraceFunction extends ASTFunctionNode {
200
165
  throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
201
166
  }
202
167
  const events = columns.flat();
203
- if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
168
+ if (!events.some(isVisualTemporalNode) || events.some(event => event.addon?.breakBefore)) {
204
169
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
205
170
  }
206
171
  return [new GraceTemporal(this, hostNode, columns, root, attachments, ctx)];
@@ -307,10 +272,13 @@ export class GraceTemporal extends TemporalNodeBase {
307
272
  // 同步时间的修改。比如tuplet修改的是GraceTemporal.T,这里要把它传给成员
308
273
  this.host.T.copyFrom(this.T);
309
274
  let offset = undefined;
310
- for (const member of this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events]) {
275
+ const members = this.ast.side === "pre" ? [...this.events, this.host] : [this.host, ...this.events];
276
+ const hostAt = members.indexOf(this.host);
277
+ for (const [index, member] of members.entries()) {
311
278
  member.t.copyFrom(this.t);
312
279
  member.layoutLine = this.layoutLine;
313
- const result = member.onTimeState?.(state);
280
+ // 宿主与同列其他音同时,前倚音依次在它之前,后倚音依次在它之后
281
+ const result = state.accidentals.at(index - hostAt, () => member.onTimeState?.(state));
314
282
  if (member === this.host) {
315
283
  this.T.copyFrom(member.T);
316
284
  offset = result;
@@ -57,7 +57,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
57
57
  members = [];
58
58
  slots = [];
59
59
  titleBottom = 0;
60
- aligned = false; // 侧栏横向重排在一轮布局中只执行一次,避免二次 onPlaced 把成员微调后的 box.x 当成未偏移基准
60
+ aligned = false; // 侧栏横向重排在一轮布局中只执行一次:后置平移后的 onPlaced 里成员已含各自平移,不能再作为基准
61
61
  sideExtents = { left: null, right: null };
62
62
  constructor(ast) {
63
63
  super();
@@ -158,7 +158,7 @@ class HeadBoundaryTemporal extends TemporalNodeBase {
158
158
  cells.set(cell, [member]);
159
159
  }
160
160
  const [left, , right] = this.slots;
161
- this.packRows(left.ast, left.start.box.x - (left.start.placementOffset?.x ?? 0), cells);
161
+ this.packRows(left.ast, left.start.box.x, cells);
162
162
  this.packRows(right.ast, right.end.box.x, cells);
163
163
  }
164
164
  stretch(node, side) {
@@ -352,8 +352,9 @@ H.tempo: 94
352
352
  next: explicitContent ? pos : lineEnd,
353
353
  node: {
354
354
  kind: "sugar",
355
- data: { class: HeadFunction, field, contentSpan },
355
+ data: { field, contentSpan },
356
356
  span: { start, end: pos },
357
+ relation: HeadFunction.deSugarRelation,
357
358
  syntaxKind: contentSpan && field !== "signature" && field !== "tempo" && contentSpan.start < contentSpan.end
358
359
  ? [{ kind: "operator", span: { start, end: pos } }, { kind: "string", span: contentSpan }]
359
360
  : undefined,
@@ -362,8 +363,6 @@ H.tempo: 94
362
363
  }
363
364
  static deSugarRelation(ctx, nodes, at) {
364
365
  const sugar = nodes[at++];
365
- if (sugar.data?.class !== HeadFunction)
366
- return null;
367
366
  const field = sugar.data.field;
368
367
  let breakAt = at;
369
368
  let span = sugar.data.contentSpan;
@@ -373,7 +372,7 @@ H.tempo: 94
373
372
  const node = nodes[breakAt];
374
373
  if (typeof node === "number" && (ctx.source[node] === "\r" || ctx.source[node] === "\n"))
375
374
  break;
376
- if (typeof node !== "number" && node.kind === "sugar" && node.data?.class === HeadFunction)
375
+ if (typeof node !== "number" && node.kind === "sugar" && node.relation === HeadFunction.deSugarRelation)
377
376
  break;
378
377
  }
379
378
  const sub = new ParserContext(ctx);
@@ -462,7 +461,7 @@ H.tempo: 94
462
461
  // 此时 rest 等延迟时值已固化,只检查当前 Head 的成员,无须再扫描全谱索引
463
462
  head.slots[2].end.onTimeState = () => head.validateDuration();
464
463
  for (const node of head.members) {
465
- if ((node.addon?.breakBefore ?? 0) > 0) {
464
+ if (node.addon?.breakBefore) {
466
465
  throw new ErrorDiagnostic("E_HEAD_INTERNAL_BREAK", "@head 的内部不能换行或换页;第一层内容已经表示视觉行", node.ast.sourceSpan);
467
466
  }
468
467
  }
@@ -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;
@@ -110,7 +110,7 @@ class MeterFunction extends ASTFunctionNode {
110
110
  measureStart.copyFrom(end);
111
111
  };
112
112
  for (const column of result.columns) {
113
- const time = column[0].t;
113
+ const time = column.t;
114
114
  for (const node of column) {
115
115
  const change = changesByPosition.get(node);
116
116
  if (!change)
@@ -120,10 +120,10 @@ class MeterFunction extends ASTFunctionNode {
120
120
  measureStart.copyFrom(time);
121
121
  sourceStart = change.end;
122
122
  }
123
- const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
124
- if (anchor) {
125
- closeMeasure(time, anchor.ast.sourceSpan.end);
126
- sourceStart = anchor.ast.sourceSpan.end;
123
+ if (column.mergeKey === ANCHOR_KEY) {
124
+ const end = column[0].ast.sourceSpan.end;
125
+ closeMeasure(time, end);
126
+ sourceStart = end;
127
127
  validationStarted = true;
128
128
  }
129
129
  }
@@ -157,6 +157,8 @@ class MeterTemporal extends TemporalNodeBase {
157
157
  }
158
158
  onTimeState(state) {
159
159
  state.meter = this.ast.measureDuration;
160
+ const { measureDuration, numerator, denominator } = this.ast;
161
+ state.timeSignature = measureDuration && { numerator, denominator };
160
162
  recordMeasureChange(this, this.ast);
161
163
  }
162
164
  emitPlayback(emitter) {