jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -1,4 +1,3 @@
1
- import { Diagnostic } from "../../diagnostic.js";
2
1
  export const SHARP_NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
3
2
  export const FLAT_NOTE_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
4
3
  /** 同一音高的两种拼写升在前、降在后,反查拼写时依赖这个顺序 */
@@ -25,9 +24,9 @@ export const NoteNameMap = {
25
24
  };
26
25
  const LETTER_ORDER = ["C", "D", "E", "F", "G", "A", "B"];
27
26
  const MAJOR_SCALE_OFFSETS = [0, 2, 4, 5, 7, 9, 11];
28
- // 输入 C4 D#3 B3b G, A 等音符字符串,输出 MIDI 数值
29
- // 要求非常严格:必须 [大写字母][升降号#bn只能一个][绝对八度]
30
- export function tonality2Midi(tonality, defaultOctave) {
27
+ // 输入 C4 D#3 B3b G, A 等音符字符串,输出 MIDI 数值;格式不合法返回 null
28
+ // 要求非常严格:必须 [大写字母或数字][升降号#bn只能一个][绝对八度]
29
+ export function tonality2Midi(tonality, defaultOctave = 4) {
31
30
  // 解析音名
32
31
  const note = tonality[0];
33
32
  let acc = "";
@@ -40,13 +39,13 @@ export function tonality2Midi(tonality, defaultOctave) {
40
39
  // 组合音名和升降号
41
40
  let noteValue = NoteNameMap[note + acc];
42
41
  if (noteValue === undefined)
43
- throw Diagnostic.error.InvalidTonality(tonality, { start: 0, end: i });
42
+ return null;
44
43
  // 解析八度
45
44
  if (i < tonality.length) {
46
45
  const octave = tonality.slice(i);
47
46
  defaultOctave = Number(octave);
48
47
  if (!/^-?\d+$/.test(octave) || !Number.isSafeInteger(defaultOctave)) {
49
- throw Diagnostic.error.InvalidTonality(tonality, { start: i, end: tonality.length });
48
+ return null;
50
49
  }
51
50
  }
52
51
  return (defaultOctave + 1) * 12 + noteValue;
@@ -70,7 +69,7 @@ export function resolveNoteMidi(name, acc, octave, keySignature) {
70
69
  return null;
71
70
  const offset = acc2Offset(acc);
72
71
  if (name >= "1" && name <= "7") {
73
- return tonality2Midi(keySignature, 4) + noteValue + offset + octave * 12;
72
+ return tonality2Midi(keySignature) + noteValue + offset + octave * 12;
74
73
  }
75
74
  return (octave + 1) * 12 + noteValue + offset;
76
75
  }
@@ -94,7 +93,7 @@ export function createDiatonicTranspose(name, acc, octave, keySignature) {
94
93
  degreeIndex = Number(relative.renderName) - 1;
95
94
  relativeOctave = relative.renderOctave;
96
95
  }
97
- const tonicMidi = tonality2Midi(keySignature, 4);
96
+ const tonicMidi = tonality2Midi(keySignature);
98
97
  const base = relativeOctave * 7 + degreeIndex;
99
98
  return steps => {
100
99
  const total = base + steps;
@@ -124,7 +123,7 @@ export function resolveLetterNameToJianpu(name, acc, octave, keySignature) {
124
123
  const actualMidi = resolveNoteMidi(name, acc, octave, keySignature);
125
124
  if (tonicIndex < 0 || noteIndex < 0 || actualMidi === null)
126
125
  return null;
127
- const tonicMidi = tonality2Midi(keySignature, 4);
126
+ const tonicMidi = tonality2Midi(keySignature);
128
127
  const degreeIndex = (noteIndex - tonicIndex + LETTER_ORDER.length) % LETTER_ORDER.length;
129
128
  const expectedPitchClass = wrapPitchClass(tonicMidi + MAJOR_SCALE_OFFSETS[degreeIndex]);
130
129
  const accidentalOffset = normalizeAccidentalOffset(wrapPitchClass(actualMidi) - expectedPitchClass);
@@ -2,9 +2,10 @@
2
2
  * 字符串字面量的唯一规则来源:预处理、`@text` 糖、`L:` 歌词糖共用
3
3
  * 扫描与反转义必须互为镜像,否则会出现“扫得对、还原错”
4
4
  */
5
+ import { Diagnostic } from "../../diagnostic.js";
5
6
  /** 找与 quotePos 处开引号配对的闭引号;找不到返回 -1 */
6
7
  export declare function findClosingQuote(source: string, quotePos: number, end: number): number;
7
- /** 剥掉成对的双引号并反转义 `\X` -> `X`;裸参数没走转义扫描,原样返回 */
8
- export declare function removeQuote(source: string): string;
8
+ /** 剥掉成对的双引号并反转义;解码失败时返回相对 source 的诊断,裸参数原样返回 */
9
+ export declare function parseString(source: string): string | Diagnostic;
9
10
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
10
11
  export declare function quote(value: string): string;
@@ -2,6 +2,7 @@
2
2
  * 字符串字面量的唯一规则来源:预处理、`@text` 糖、`L:` 歌词糖共用
3
3
  * 扫描与反转义必须互为镜像,否则会出现“扫得对、还原错”
4
4
  */
5
+ import { Diagnostic } from "../../diagnostic.js";
5
6
  /** 找与 quotePos 处开引号配对的闭引号;找不到返回 -1 */
6
7
  export function findClosingQuote(source, quotePos, end) {
7
8
  for (let i = quotePos + 1; i < end; i++) {
@@ -12,11 +13,23 @@ export function findClosingQuote(source, quotePos, end) {
12
13
  }
13
14
  return -1;
14
15
  }
15
- /** 剥掉成对的双引号并反转义 `\X` -> `X`;裸参数没走转义扫描,原样返回 */
16
- export function removeQuote(source) {
16
+ /** 剥掉成对的双引号并反转义;解码失败时返回相对 source 的诊断,裸参数原样返回 */
17
+ export function parseString(source) {
17
18
  if (source.length < 2 || !source.startsWith('"') || !source.endsWith('"'))
18
19
  return source;
19
- return source.slice(1, -1).replace(/\\(.)/gs, "$1");
20
+ let diagnostic;
21
+ // 连同不完整转义一起匹配以便诊断;替换结果不会被再次扫描
22
+ const text = source.slice(1, -1).replace(/\\(u.{0,4}|.)/gs, (escape, body, offset) => {
23
+ if (body[0] !== "u")
24
+ return body;
25
+ if (!/^u[0-9a-f]{4}$/i.test(body)) {
26
+ const start = offset + 1;
27
+ diagnostic ??= Diagnostic.warning.InvalidUnicodeEscape({ start, end: start + escape.length });
28
+ return escape;
29
+ }
30
+ return String.fromCharCode(Number.parseInt(body.slice(1), 16));
31
+ });
32
+ return diagnostic ?? text;
20
33
  }
21
34
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
22
35
  export function quote(value) {
@@ -16,6 +16,8 @@ export declare class ParserContext {
16
16
  readonly source: string;
17
17
  /** 词法层产物,只由 parseSyntax 填充;所有子上下文共享 */
18
18
  readonly syntax: SyntaxAnalysis;
19
+ /** syntax.tokens 前缀注释区间的扫描游标 */
20
+ private commentIndex;
19
21
  /** 解析过程中产生的诊断信息,包含错误和警告 */
20
22
  diagnostics: Diagnostic[];
21
23
  /** 变量表,存储 `@set` 定义的变量,供解析过程中查询和修改,具有局部作用域 */
@@ -1,7 +1,7 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
2
  import { DEFAULT_TEXT_FONT, JIANPU_NUMBER_FONT } from "../render/text.js";
3
3
  import { readCall, trimRange } from "./parse-utils/call-utils.js";
4
- import { removeQuote } from "./parse-utils/string-utils.js";
4
+ import { parseString } from "./parse-utils/string-utils.js";
5
5
  import { readBrace } from "./parse-utils/brace-utils.js";
6
6
  import { readLabel } from "./parse-utils/label-utils.js";
7
7
  import { parseLength } from "./parse-utils/length-utils.js";
@@ -39,6 +39,8 @@ export class ParserContext {
39
39
  source;
40
40
  /** 词法层产物,只由 parseSyntax 填充;所有子上下文共享 */
41
41
  syntax;
42
+ /** syntax.tokens 前缀注释区间的扫描游标 */
43
+ commentIndex;
42
44
  /** 解析过程中产生的诊断信息,包含错误和警告 */
43
45
  diagnostics;
44
46
  /** 变量表,存储 `@set` 定义的变量,供解析过程中查询和修改,具有局部作用域 */
@@ -62,6 +64,7 @@ export class ParserContext {
62
64
  this.source = ctx.source;
63
65
  this.diagnostics = ctx.diagnostics; // 诊断信息全局共享
64
66
  this.syntax = ctx.syntax;
67
+ this.commentIndex = ctx.commentIndex;
65
68
  this.variables = { ...ctx.variables }; // 继承但不修改父上下文的变量
66
69
  this.functions = ctx.functions; // 函数定义全局共享
67
70
  this.deSugarAtomFns = ctx.deSugarAtomFns; // 去糖方法全局共享
@@ -78,6 +81,7 @@ export class ParserContext {
78
81
  tokens: (ctx.commentSpans ?? []).map(span => ({ kind: "comment", span })),
79
82
  calls: [],
80
83
  };
84
+ this.commentIndex = 0;
81
85
  this.variables = Object.fromEntries(Object.entries(ParserContext.systemVariables).map(([name, definition]) => [name, definition.default]));
82
86
  Object.assign(this.variables, ctx.variables);
83
87
  this.functions = ctx.functions ?? new Map();
@@ -159,10 +163,27 @@ export class ParserContext {
159
163
  }
160
164
  return this.syntax;
161
165
  }
162
- // syntax 路径独占这些 span,AST 路径不会读取或改写它们
166
+ // syntax 路径独占这些 span,AST 路径不会读取或改写它们;跨注释区间按前缀 comment token 切开以保证互不重叠
163
167
  addSyntax(kind, span) {
164
- if (span && span.start < span.end) {
165
- this.syntax.tokens.push({ kind, span });
168
+ if (!span || span.start >= span.end)
169
+ return;
170
+ let start = span.start;
171
+ const tokens = this.syntax.tokens;
172
+ while (tokens[this.commentIndex]?.kind === "comment" && tokens[this.commentIndex].span.end <= start) {
173
+ this.commentIndex++;
174
+ }
175
+ for (let i = this.commentIndex; i < tokens.length; i++) {
176
+ const token = tokens[i];
177
+ if (token.kind !== "comment" || token.span.start >= span.end)
178
+ break;
179
+ if (start < token.span.start) {
180
+ tokens.push({ kind, span: { start, end: token.span.start } });
181
+ }
182
+ start = token.span.end;
183
+ this.commentIndex = i + 1;
184
+ }
185
+ if (start < span.end) {
186
+ tokens.push({ kind, span: { start, end: span.end } });
166
187
  }
167
188
  }
168
189
  /** 把已识别的 GrammarNode 映射为源码 token;content/brace 在这里继续递归 */
@@ -170,9 +191,9 @@ export class ParserContext {
170
191
  if (node.kind === "brace") {
171
192
  this.addSyntax("punctuation", { start: node.span.start, end: node.span.start + 1 });
172
193
  const close = Math.min(this.source.length, node.span.end - 1);
194
+ new ParserContext(this).parseSyntax(node.span.start + 1, close);
173
195
  if (this.source[close] === "}")
174
196
  this.addSyntax("punctuation", { start: close, end: close + 1 });
175
- new ParserContext(this).parseSyntax(node.span.start + 1, close);
176
197
  return;
177
198
  }
178
199
  if (node.kind === "label") {
@@ -188,13 +209,11 @@ export class ParserContext {
188
209
  this.syntax.calls.push(call);
189
210
  this.addSyntax("function", call.nameSpan);
190
211
  this.addSyntax("punctuation", call.openParenSpan);
191
- this.addSyntax("punctuation", call.closeParenSpan);
192
212
  const def = this.functions.get(call.name.toLowerCase())?.def;
193
213
  for (let index = 0; index < call.args.length; index++) {
194
214
  const arg = call.args[index];
195
215
  this.addSyntax("property", arg.nameSpan);
196
216
  this.addSyntax("punctuation", arg.equalsSpan);
197
- this.addSyntax("punctuation", arg.commaSpan);
198
217
  const name = arg.nameSpan
199
218
  ? this.source.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase()
200
219
  : void 0;
@@ -208,7 +227,9 @@ export class ParserContext {
208
227
  if (kind)
209
228
  this.addSyntax(kind, arg.valueSpan);
210
229
  }
230
+ this.addSyntax("punctuation", arg.commaSpan);
211
231
  }
232
+ this.addSyntax("punctuation", call.closeParenSpan);
212
233
  }
213
234
  /**
214
235
  * 第二轮去糖 & 函数节点创建
@@ -508,7 +529,14 @@ export class ParserContext {
508
529
  return l;
509
530
  // 其他类型一律视为string
510
531
  default:
511
- return removeQuote(text);
532
+ const s = parseString(text);
533
+ if (s instanceof Diagnostic) {
534
+ s.span.start += start;
535
+ s.span.end += start;
536
+ this.diagnostics.push(s);
537
+ return text.slice(1, -1);
538
+ }
539
+ return s;
512
540
  }
513
541
  }
514
542
  length2px(length) {
package/dist/pipeline.js CHANGED
@@ -20,7 +20,6 @@ export function compileScore(source, options = {}) {
20
20
  parser.registerFunctions(functions);
21
21
  const ast = new ASTBraceNode({ start: 0, end: source.length }, parser.parse());
22
22
  const loweringContext = new LoweringContext(parser.diagnostics);
23
- loweringContext.registerFunctions(functions);
24
23
  const lowering = loweringContext.lowerDocument(ast);
25
24
  const layoutContext = createLayoutPrepareContext(functions, { textMeasurer });
26
25
  const layout = layoutDocument(lowering, layoutContext, layoutOptions);
@@ -13,19 +13,30 @@ import { isPlaybackRelation } from "./types.js";
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
15
15
  const columns = lowering.columns;
16
- const columnOf = new Map();
17
- // 先建立时间流内的 TemporalNode 的列索引
18
- for (let index = 0; index < columns.length; index++) {
19
- for (const node of columns[index])
20
- columnOf.set(node, index);
21
- }
16
+ let columnOf;
22
17
  // 折叠成员不单独占列,沿 foldedInto 找到最近的已入列宿主
23
18
  // 标记和关系端点都使用这个映射,保持控制流与实际时间列一致
24
- const resolveColumn = (node) => {
19
+ const resolveColumn = (node, edge) => {
20
+ if (!columnOf) {
21
+ columnOf = new Map();
22
+ for (let index = 0; index < columns.length; index++) {
23
+ for (const item of columns[index])
24
+ columnOf.set(item, index);
25
+ }
26
+ }
25
27
  for (let at = node; at; at = at.foldedInto) {
26
28
  const index = columnOf.get(at);
27
- if (index !== void 0)
29
+ if (index === undefined)
30
+ continue;
31
+ if (edge !== "end" || at.T.compare(0) <= 0)
28
32
  return index;
33
+ // 一个被标签引用的事件,其完整时值覆盖了多个时间列;终点查询不包含结束时刻的列。
34
+ const finish = at.t.clone().add(at.T);
35
+ let end = index;
36
+ // 用顺序向后找而不是二分因为基本就在后一个(@rest除外)
37
+ while (end + 1 < columns.length && columns[end + 1][0].t.compare(finish) < 0)
38
+ end++;
39
+ return end;
29
40
  }
30
41
  return void 0;
31
42
  };
@@ -40,7 +51,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
40
51
  const [from, to] = hook.range ?? [0, columns.length - 1];
41
52
  if (hook.range && (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
42
53
  || from < 0 || to < from || to >= columns.length)) {
43
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", `播放控制流范围 [${from}, ${to}] 超出时间列边界`, sourceSpan);
54
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", "播放控制流范围 [{from}, {to}] 超出时间列边界", sourceSpan, { from, to });
44
55
  }
45
56
  const registered = { hook, sourceSpan };
46
57
  // 预先按范围分发,执行时只检查当前列相关的声明。
@@ -57,7 +68,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
57
68
  for (const node of nodes) {
58
69
  addHook(node, node.ast.sourceSpan);
59
70
  const marks = node.playbackMarks?.();
60
- if (!marks)
71
+ if (!marks?.length)
61
72
  continue;
62
73
  const at = resolveColumn(node);
63
74
  if (at === void 0)
@@ -104,7 +115,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
104
115
  // 先记录到达,再决定本列去留;跳过的列也算一次到达,但不会发布声音
105
116
  while (index < columns.length) {
106
117
  if (++steps > maxFlowSteps) {
107
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", `播放控制流访问超过 ${maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算`, columns[index][0].ast.sourceSpan);
118
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", "播放控制流访问超过 {maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算", columns[index][0].ast.sourceSpan, { maxFlowSteps });
108
119
  }
109
120
  visits[index]++;
110
121
  let jumpTo;
@@ -119,7 +130,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
119
130
  return order;
120
131
  if (!Number.isSafeInteger(action.column)
121
132
  || action.column < 0 || action.column > columns.length) {
122
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", `播放控制流跳转目标 ${action.column} 超出时间列边界`, registered.sourceSpan);
133
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", "播放控制流跳转目标 {column} 超出时间列边界", registered.sourceSpan, { column: action.column });
123
134
  }
124
135
  // 取最小的跳转目标到最前面
125
136
  jumpTo = Math.min(jumpTo ?? Infinity, action.column);
@@ -131,11 +142,11 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
131
142
  index++;
132
143
  }
133
144
  }
134
- // 正常走到文末才报告从未演奏的列;连续缺失区间只报第一列
145
+ // 正常走到文末才报告从未演奏的正时值列;换行、声部头、回跳小节线等零时值列不算未演奏
135
146
  const played = new Set(order);
136
147
  let previousMissing = false;
137
148
  for (let index = 0; index < columns.length; index++) {
138
- const missing = !played.has(index);
149
+ const missing = !played.has(index) && columns[index].some(node => !node.T.isZero());
139
150
  if (missing && !previousMissing) {
140
151
  diagnostics.push(new WarningDiagnostic("W_PLAYBACK_COLUMN_NEVER_PLAYED", "这里在任何一遍里都不会演奏", columns[index][0].ast.sourceSpan));
141
152
  }
@@ -166,7 +177,18 @@ export function compilePlayback(lowering, options) {
166
177
  const changes = [{ kind: "initial", at: new Fraction(), origins: [] }];
167
178
  const factors = new Map();
168
179
  const spanScales = new Map();
169
- const structureContext = { spans, notes, diagnostics };
180
+ const structureContext = {
181
+ spans,
182
+ notes,
183
+ diagnostics,
184
+ transform(note, transform) {
185
+ if (notes.lastIndexOf(note) < 0) {
186
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_TARGET", "声音变换目标必须属于当前计划的已发布音段", note.sourceSpans?.[0] ?? { start: 0, end: 0 });
187
+ }
188
+ const list = transforms.get(note);
189
+ transforms.set(note, list ? [...list, transform] : [transform]);
190
+ },
191
+ };
170
192
  /** 固化控制的演奏时刻和来源,回调留到最终状态扫描时统一执行 */
171
193
  const scheduleControl = (at, origins, apply) => {
172
194
  if (!Number.isFinite(at.toNumber()) || at.compare(0) < 0) {
@@ -178,13 +200,15 @@ export function compilePlayback(lowering, options) {
178
200
  function play(node, activeTransforms, activeScales, start, duration, ancestors = [],
179
201
  // 折叠成员沿用正文事件的轨发声,倚音各声部的私有轨因此并入宿主轨
180
202
  track = node.track) {
203
+ if (!node.playbackState && !node.emitPlayback)
204
+ return;
181
205
  const lineage = [...ancestors, { node }];
182
- // 当前目标使用进入时的效果快照;子节点序列使用副本,内部新增效果不会回灌外层
183
- const childTransforms = [...activeTransforms];
184
- const inheritedTransforms = [...activeTransforms];
185
- const childScales = [...activeScales];
186
- const inheritedScales = [...activeScales];
187
- const deferred = [];
206
+ // 当前目标使用进入时的效果快照;子节点序列按需复制,内部新增效果不会回灌外层
207
+ const inheritedTransforms = activeTransforms.length ? [...activeTransforms] : undefined;
208
+ const inheritedScales = activeScales.length ? [...activeScales] : undefined;
209
+ let childTransforms;
210
+ let childScales;
211
+ let deferred;
188
212
  /** 复制可变的时间和源码位置,避免结构修改影响输入或另一遍访问 */
189
213
  function publishSpan(input) {
190
214
  const span = {
@@ -196,7 +220,7 @@ export function compilePlayback(lowering, options) {
196
220
  sourceSpans: [{ ...node.ast.sourceSpan }],
197
221
  };
198
222
  spans.push(span);
199
- if (inheritedScales.length)
223
+ if (inheritedScales)
200
224
  spanScales.set(span, inheritedScales);
201
225
  return span;
202
226
  }
@@ -219,12 +243,13 @@ export function compilePlayback(lowering, options) {
219
243
  note(input) {
220
244
  const note = publishSpan(input);
221
245
  notes.push(note);
222
- if (inheritedTransforms.length)
246
+ if (inheritedTransforms)
223
247
  transforms.set(note, inheritedTransforms);
224
248
  },
225
249
  /** 延长原区间,并把当前访问携带的效果定位到新增部分 */
226
250
  extend(span) {
227
- if (!spans.includes(span) || !span.end.equals(start) || duration.compare(0) <= 0) {
251
+ // 待延长目标总在已发布末尾附近,反向查找无需额外 Set 即可 O(1) 命中
252
+ if (spans.lastIndexOf(span) < 0 || !span.end.equals(start) || duration.compare(0) <= 0) {
228
253
  throw new ErrorDiagnostic("E_PLAYBACK_EXTEND_RANGE", "扩展必须接续当前计划内的区间且时值为正", node.ast.sourceSpan);
229
254
  }
230
255
  const previousDuration = span.end.clone().sub(span.start);
@@ -234,8 +259,10 @@ export function compilePlayback(lowering, options) {
234
259
  ? { ...scale, startRatio: scale.startRatio.clone().mul(previousDuration).div(extendedDuration) }
235
260
  : scale);
236
261
  // 新效果从旧终点开始;保存比例后,后续整体结构缩放仍能同步移动它的起点
237
- for (const scale of inheritedScales) {
238
- scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
262
+ if (inheritedScales) {
263
+ for (const scale of inheritedScales) {
264
+ scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
265
+ }
239
266
  }
240
267
  if (scales.length)
241
268
  spanScales.set(span, scales);
@@ -260,12 +287,13 @@ export function compilePlayback(lowering, options) {
260
287
  origins: lineage });
261
288
  },
262
289
  affectFollowing: transform => activeTransforms.push(transform),
263
- defer: hook => deferred.push(hook),
264
- play: (child, childStart, childDuration) => play(child, childTransforms, childScales, childStart ?? start, childDuration ?? duration, lineage, track),
290
+ defer: hook => (deferred ??= []).push(hook),
291
+ play: (child, childStart, childDuration) => play(child, childTransforms ??= [...activeTransforms], childScales ??= [...activeScales], childStart ?? start, childDuration ?? duration, lineage, track),
265
292
  });
266
293
  // 当前节点发布完成就执行结构处理,因此 hook 只能看到当前位置此前的目标
267
- for (const hook of deferred)
268
- hook(structureContext);
294
+ if (deferred)
295
+ for (const hook of deferred)
296
+ hook(structureContext);
269
297
  }
270
298
  const order = linearizeColumns(lowering, diagnostics, maxFlowSteps);
271
299
  const firstScore = lowering.columns[order[0]]?.[0]?.t.clone() ?? new Fraction();
@@ -280,6 +308,8 @@ export function compilePlayback(lowering, options) {
280
308
  const index = order[step];
281
309
  // 同列各顶层访问共享演奏坐标,但分别建立自己的效果作用域
282
310
  for (const node of lowering.columns[index]) {
311
+ if (!node.playbackState && !node.emitPlayback)
312
+ continue;
283
313
  play(node, [], [], node.t.clone().add(shift), node.T.clone());
284
314
  }
285
315
  const boundary = lowering.columns[index + 1]?.[0]?.t ?? lowering.duration; // 当前列的控制终点
@@ -317,7 +347,7 @@ export function compilePlayback(lowering, options) {
317
347
  Object.freeze(span.sourceSpans);
318
348
  Object.freeze(span);
319
349
  }
320
- const noteSet = new Set(notes);
350
+ let noteSet;
321
351
  const connections = new Map();
322
352
  const predecessors = new Map();
323
353
  const relationContext = {
@@ -325,6 +355,7 @@ export function compilePlayback(lowering, options) {
325
355
  diagnostics,
326
356
  /** 只建立一进一出的逻辑连接,保留两个音段各自的边界和修饰 */
327
357
  connect(from, to) {
358
+ noteSet ??= new Set(notes);
328
359
  if (!noteSet.has(from) || !noteSet.has(to) || !from.end.equals(to.start)) {
329
360
  throw new ErrorDiagnostic("E_PLAYBACK_CONNECTION", "音段连接必须属于当前计划且时间相接", from.sourceSpans[0]);
330
361
  }
@@ -341,23 +372,19 @@ export function compilePlayback(lowering, options) {
341
372
  if (isPlaybackRelation(attachment))
342
373
  attachment.applyPlayback(relationContext);
343
374
  }
344
- const reverseNotes = [...notes].sort((left, right) => right.start.compare(left.start));
345
- const connectedEnds = new Map();
346
- // 连接严格向未来推进;逆序处理保证后继的链尾已知,一次算出所有逻辑终点
347
- for (const note of reverseNotes) {
348
- const next = connections.get(note);
349
- const end = next ? connectedEnds.get(next) : note.end;
350
- connectedEnds.set(note, end);
351
- }
352
375
  // 将有声、无声区间上的效果转换为进入和退出边界,交给同一条全局状态时间线
353
- for (const span of spans) {
354
- const end = connectedEnds.get(span) ?? span.end;
376
+ for (const [span, scales] of spanScales) {
377
+ let tail = span;
378
+ if (scales.some(scale => scale.followConnections)) {
379
+ while (connections.has(tail))
380
+ tail = connections.get(tail);
381
+ }
355
382
  // 连接只可能延续效果终点;每个效果仍从自己在原区间内的位置开始
356
- for (const scale of spanScales.get(span) ?? []) {
383
+ for (const scale of scales) {
357
384
  const start = scale.startRatio
358
385
  ? span.start.clone().add(span.end.clone().sub(span.start).mul(scale.startRatio))
359
386
  : span.start;
360
- changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? end : span.end,
387
+ changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? tail.end : span.end,
361
388
  origins: scale.origins, scale, delta: -1 });
362
389
  }
363
390
  }
@@ -436,57 +463,89 @@ export function compilePlayback(lowering, options) {
436
463
  return { ...snapshot, bpmScale: snapshot.bpmScale.clone() };
437
464
  },
438
465
  };
466
+ const canAbsorb = (from, to) => !transforms.has(to)
467
+ && from.track === to.track && from.midi === to.midi && from.percussion === to.percussion;
439
468
  const realized = new Map();
440
- // 每个逻辑音段独立展开声音,连接不会让后一段继承前一段的装饰
469
+ // 后继无独立变换时直接并入前驱音段,使首段装饰与奏法覆盖连续连音;有新变换时从该处分段并在交界处合并同音
441
470
  for (const note of notes) {
442
- let owned = [{ ...note, start: note.start.clone(), end: note.end.clone() }];
443
- // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
444
- for (const transform of transforms.get(note) ?? []) {
445
- owned = transform(transformContext, owned) ?? owned;
471
+ const previous = predecessors.get(note);
472
+ if (previous && canAbsorb(previous, note))
473
+ continue;
474
+ let tail = note;
475
+ let next = connections.get(tail);
476
+ let mergedSpans;
477
+ while (next && canAbsorb(tail, next)) {
478
+ connections.delete(tail);
479
+ mergedSpans ??= [...note.sourceSpans];
480
+ mergedSpans.push(...next.sourceSpans);
481
+ tail = next;
482
+ next = connections.get(tail);
446
483
  }
447
- let first;
448
- let last;
449
- // 各子音必须留在原区间内;同时收集整体边界,防止声音阶段改写已确定的结构范围
450
- for (const sound of owned) {
451
- if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
452
- || sound.start.compare(note.start) < 0 || sound.end.compare(note.end) > 0
453
- || sound.end.compare(sound.start) <= 0) {
454
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
484
+ if (tail !== note) {
485
+ connections.delete(tail);
486
+ if (next)
487
+ connections.set(note, next);
488
+ }
489
+ const segmentEnd = tail.end;
490
+ const segmentSpans = mergedSpans ? Object.freeze(mergedSpans) : note.sourceSpans;
491
+ const noteTransforms = transforms.get(note);
492
+ let owned;
493
+ if (noteTransforms) {
494
+ owned = [{ ...note, start: note.start.clone(), end: segmentEnd.clone(), sourceSpans: segmentSpans }];
495
+ // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
496
+ for (const transform of noteTransforms) {
497
+ owned = transform(transformContext, owned) ?? owned;
498
+ }
499
+ let first;
500
+ // 各子音必须留在原区间内;同时收集整体起点,防止声音阶段延迟起音或返回空结果
501
+ for (const sound of owned) {
502
+ if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
503
+ || sound.start.compare(note.start) < 0 || sound.end.compare(segmentEnd) > 0
504
+ || sound.end.compare(sound.start) <= 0) {
505
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
506
+ }
507
+ if (!first || sound.start.compare(first) < 0)
508
+ first = sound.start;
509
+ }
510
+ if (!first?.equals(note.start)) {
511
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起点", note.sourceSpans[0]);
455
512
  }
456
- if (!first || sound.start.compare(first) < 0)
457
- first = sound.start;
458
- if (!last || sound.end.compare(last) > 0)
459
- last = sound.end;
460
513
  }
461
- if (!first?.equals(note.start) || !last?.equals(note.end)) {
462
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起止边界", note.sourceSpans[0]);
514
+ else {
515
+ owned = [tail === note ? note : { ...note, end: segmentEnd, sourceSpans: segmentSpans }];
463
516
  }
464
- // 现在才分配实际音符身份;变换专用字段不再进入点事件,配对留给边界合并使用
465
- realized.set(note, owned.map(sound => {
517
+ // 现在才分配实际音符身份;仅分段后仍存在跨段连接的音段需要记录事件对供边界合并
518
+ const pairs = (next !== undefined || previous !== undefined)
519
+ ? []
520
+ : undefined;
521
+ for (const sound of owned) {
466
522
  const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
467
523
  const noteId = nextNoteId++;
468
524
  const on = {
469
525
  kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
470
526
  track, midi, velocity, percussion,
471
- origins: [...origins], sourceSpans: sourceSpans.map(span => ({ ...span })),
527
+ origins, sourceSpans: [...sourceSpans],
472
528
  };
473
529
  const off = {
474
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins: [...origins],
530
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins,
475
531
  };
476
532
  events.push(on, off);
477
- return { on, off };
478
- }));
533
+ pairs?.push({ on, off });
534
+ }
535
+ if (pairs)
536
+ realized.set(note, pairs);
479
537
  }
480
538
  const removed = new Set();
481
539
  const joinedSources = new Map();
540
+ const connectedNotes = connections.size > 1
541
+ ? [...connections.keys()].sort((left, right) => right.start.compare(left.start))
542
+ : connections.keys();
482
543
  // 后继先完成合并,前驱便可直接接到它更新后的终点;仅合并连接处实际同音的事件
483
- for (const note of reverseNotes) {
544
+ for (const note of connectedNotes) {
484
545
  const next = connections.get(note);
485
- if (!next)
486
- continue;
487
546
  // 只有到达原音段末端的子音可以跨边界连接,中间子音保留自己的起止
488
547
  for (const tail of realized.get(note)) {
489
- if (!tail.off.at.equals(note.end))
548
+ if (!tail.off.at.equals(next.start))
490
549
  continue;
491
550
  const head = realized.get(next).find(pair => !removed.has(pair.on)
492
551
  && pair.on.at.equals(next.start) && pair.on.track === tail.on.track
@@ -46,7 +46,7 @@ export interface PlaybackOrigin {
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
48
  order: number;
49
- origins: PlaybackOrigin[];
49
+ origins: readonly PlaybackOrigin[];
50
50
  }
51
51
  /** 声音展开后生成的点事件;最终输出前会校验并剥离内部字段 */
52
52
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
@@ -30,7 +30,8 @@ export function finalizePlaybackEvents(events, trackOrder) {
30
30
  noteOffs.set(event.noteId, event);
31
31
  }
32
32
  }
33
- // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源
33
+ const audible = new Set();
34
+ // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源;同时收集实际发声轨道
34
35
  for (const [noteId, on] of noteOns) {
35
36
  const off = noteOffs.get(noteId);
36
37
  if (!off)
@@ -39,16 +40,15 @@ export function finalizePlaybackEvents(events, trackOrder) {
39
40
  throw new Error(`Note ${noteId} has a non-positive duration`);
40
41
  if (on.origins.length === 0 || off.origins.length === 0)
41
42
  throw new Error(`Note ${noteId} has no origin`);
43
+ audible.add(on.track);
42
44
  }
43
- // 再从关音侧反查,避免只检查开音时漏掉孤立的 NoteOff
44
- for (const noteId of noteOffs.keys()) {
45
- if (!noteOns.has(noteId))
46
- throw new Error(`NoteOff ${noteId} has no NoteOn`);
45
+ // 仅当关音数量多于开音时反查孤立的 NoteOff
46
+ if (noteOffs.size !== noteOns.size) {
47
+ for (const noteId of noteOffs.keys()) {
48
+ if (!noteOns.has(noteId))
49
+ throw new Error(`NoteOff ${noteId} has no NoteOn`);
50
+ }
47
51
  }
48
- const audible = new Set();
49
- // 只从实际 NoteOn 收集轨道,无声区间和纯布局轨道不占输出编号
50
- for (const on of noteOns.values())
51
- audible.add(on.track);
52
52
  // 保留 lowering 的稳定轨道顺序,只过滤未实际发声的轨道
53
53
  const trackIds = new Map();
54
54
  for (const track of trackOrder) {