jpfun 0.7.0 → 0.9.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 (152) 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 +0 -10
  5. package/dist/converter/midi/convert.js +19 -56
  6. package/dist/converter/musicxml/features.d.ts +16 -8
  7. package/dist/converter/musicxml/features.js +88 -19
  8. package/dist/converter/musicxml/index.js +88 -50
  9. package/dist/converter/musicxml/model.d.ts +9 -0
  10. package/dist/converter/source.d.ts +4 -7
  11. package/dist/converter/source.js +11 -9
  12. package/dist/core.d.ts +1 -0
  13. package/dist/core.js +1 -0
  14. package/dist/diagnostic.d.ts +7 -1
  15. package/dist/diagnostic.js +40 -88
  16. package/dist/fraction.js +3 -2
  17. package/dist/functions/ASTtypes.d.ts +3 -32
  18. package/dist/functions/ASTtypes.js +5 -52
  19. package/dist/functions/adjust/index.js +45 -33
  20. package/dist/functions/arpeggio/index.js +50 -55
  21. package/dist/functions/arpeggio/shape.d.ts +2 -3
  22. package/dist/functions/arpeggio/shape.js +20 -50
  23. package/dist/functions/bar/index.d.ts +8 -0
  24. package/dist/functions/bar/index.js +105 -8
  25. package/dist/functions/beam/auto.d.ts +1 -2
  26. package/dist/functions/beam/auto.js +80 -135
  27. package/dist/functions/beam/index.js +6 -12
  28. package/dist/functions/beam/layout.d.ts +1 -1
  29. package/dist/functions/beam/layout.js +1 -1
  30. package/dist/functions/box/index.js +0 -6
  31. package/dist/functions/br/index.d.ts +34 -2
  32. package/dist/functions/br/index.js +5 -4
  33. package/dist/functions/dash/index.js +9 -10
  34. package/dist/functions/default.js +2 -1
  35. package/dist/functions/div/index.d.ts +3 -4
  36. package/dist/functions/div/index.js +18 -14
  37. package/dist/functions/dot/index.js +5 -11
  38. package/dist/functions/dyn/index.js +55 -57
  39. package/dist/functions/gliss/index.js +131 -103
  40. package/dist/functions/grace/index.d.ts +3 -12
  41. package/dist/functions/grace/index.js +52 -102
  42. package/dist/functions/head/index.js +10 -7
  43. package/dist/functions/key/index.js +13 -15
  44. package/dist/functions/meter/index.d.ts +56 -1
  45. package/dist/functions/meter/index.js +15 -10
  46. package/dist/functions/note/index.js +6 -6
  47. package/dist/functions/note/noteName.d.ts +16 -0
  48. package/dist/functions/note/noteName.js +88 -0
  49. package/dist/functions/note/source-transform.js +8 -10
  50. package/dist/functions/ottava/index.js +35 -40
  51. package/dist/functions/page/index.d.ts +1 -0
  52. package/dist/functions/page/index.js +27 -21
  53. package/dist/functions/pagebreak/index.js +2 -2
  54. package/dist/functions/rest/index.js +5 -5
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.js +0 -1
  57. package/dist/functions/stack/index.js +8 -57
  58. package/dist/functions/symbol/index.d.ts +21 -2
  59. package/dist/functions/symbol/index.js +69 -24
  60. package/dist/functions/symbol/ornament.d.ts +1 -2
  61. package/dist/functions/symbol/shape.d.ts +6 -0
  62. package/dist/functions/symbol/shape.js +16 -3
  63. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  64. package/dist/functions/symbol/symbols/coda.js +56 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  66. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  67. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  69. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  70. package/dist/functions/symbol/symbols/marcato.js +22 -0
  71. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/staccato.js +24 -0
  73. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  74. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  75. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  76. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  77. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  78. package/dist/functions/symbol/symbols/turn.js +50 -0
  79. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  80. package/dist/functions/symbol/symbols/wheel.js +36 -0
  81. package/dist/functions/temporal.d.ts +3 -2
  82. package/dist/functions/temporal.js +8 -0
  83. package/dist/functions/text/index.js +38 -35
  84. package/dist/functions/tie/index.js +44 -43
  85. package/dist/functions/tremolo/index.d.ts +2 -0
  86. package/dist/functions/tremolo/index.js +318 -0
  87. package/dist/functions/tuplet/index.js +4 -14
  88. package/dist/functions/up/index.js +81 -85
  89. package/dist/functions/voice/connections.d.ts +2 -1
  90. package/dist/functions/voice/connections.js +48 -10
  91. package/dist/functions/voice/index.d.ts +2 -3
  92. package/dist/functions/voice/index.js +2 -963
  93. package/dist/functions/voice/lyrics.d.ts +30 -0
  94. package/dist/functions/voice/lyrics.js +289 -0
  95. package/dist/functions/voice/voice.d.ts +63 -0
  96. package/dist/functions/voice/voice.js +373 -0
  97. package/dist/functions/voice/voices.d.ts +106 -0
  98. package/dist/functions/voice/voices.js +423 -0
  99. package/dist/functions/volta/index.js +5 -23
  100. package/dist/jpfun.core.min.js +76 -59
  101. package/dist/jpfun.from-midi.min.js +5 -5
  102. package/dist/jpfun.from-musicxml.min.js +8 -8
  103. package/dist/jpfun.min.js +81 -64
  104. package/dist/layout/default.d.ts +0 -1
  105. package/dist/layout/default.js +0 -1
  106. package/dist/layout/engine.js +30 -18
  107. package/dist/layout/model.d.ts +0 -1
  108. package/dist/layout/model.js +1 -4
  109. package/dist/layout/page.d.ts +2 -1
  110. package/dist/layout/page.js +14 -14
  111. package/dist/layout/range.d.ts +7 -6
  112. package/dist/layout/range.js +23 -14
  113. package/dist/layout/types.d.ts +9 -28
  114. package/dist/lowering/loweringContext.d.ts +18 -23
  115. package/dist/lowering/loweringContext.js +33 -46
  116. package/dist/lowering/track.d.ts +8 -1
  117. package/dist/lowering/types.d.ts +13 -11
  118. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  119. package/dist/parser/parse-utils/call-utils.js +6 -34
  120. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  121. package/dist/parser/parse-utils/note-utils.js +21 -33
  122. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  123. package/dist/parser/parse-utils/string-utils.js +20 -5
  124. package/dist/parser/parserContext.d.ts +9 -9
  125. package/dist/parser/parserContext.js +62 -11
  126. package/dist/pipeline.js +2 -3
  127. package/dist/playback/compile.js +131 -82
  128. package/dist/playback/event.d.ts +6 -6
  129. package/dist/playback/event.js +13 -49
  130. package/dist/playback/time.js +42 -31
  131. package/dist/playback/types.d.ts +3 -1
  132. package/dist/render/canvas.js +4 -22
  133. package/dist/render/recording.js +1 -4
  134. package/dist/render/svg.d.ts +0 -1
  135. package/dist/render/svg.js +33 -31
  136. package/dist/render/text.d.ts +36 -1
  137. package/dist/render/text.js +134 -0
  138. package/dist/render/translate.d.ts +0 -1
  139. package/dist/render/translate.js +6 -23
  140. package/dist/render/types.d.ts +0 -2
  141. package/grammar.md +39 -30
  142. package/package.json +3 -3
  143. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  144. package/dist/functions/note/noteNameFSM.js +0 -181
  145. package/dist/iife/core.d.ts +0 -1
  146. package/dist/iife/core.js +0 -3
  147. package/dist/iife/from-midi.d.ts +0 -1
  148. package/dist/iife/from-midi.js +0 -15
  149. package/dist/iife/from-musicxml.d.ts +0 -1
  150. package/dist/iife/from-musicxml.js +0 -3
  151. package/dist/iife/full.d.ts +0 -1
  152. package/dist/iife/full.js +0 -3
@@ -7,22 +7,19 @@ import { Track } from "./track.js";
7
7
  *
8
8
  * 标准用法:
9
9
  * 1. 创建 LoweringContext
10
- * 2. 调用 registerFunctions,传入与 parser 相同的函数类列表
11
- * 3. 调用 lowerDocument(root),得到 LoweringResult
12
- * 4. 把结果交给 layoutDocument
10
+ * 2. 调用 lowerDocument(root),得到 LoweringResult
11
+ * 3. 把结果交给 layoutDocument
13
12
  *
14
13
  * 大多数 AST 函数通过以下入口参与 lowering(按时间顺序):
15
14
  * - [hook] loweringEnter/loweringExit:进入或离开节点时生成 TemporalNode、管理作用域
16
15
  * - [API] LoweringContext.beginLoweringGroup/endLoweringGroup:通常在 enter/exit 中被调用,以栈方式观察当前子树产生的 TemporalNode 和 attachment
17
16
  * - [API] LoweringContext.addAttachment:注册不推进时间的附属对象;当前外层分组会收到该对象
17
+ * - [API] LoweringContext.deferFinalize:在 enter/exit 中按需登记本轮收尾回调,支持通过 order 指定执行优先级
18
18
  * - [config] timeFlowModel:声明子节点按 sequence 或 parallel 推进时间;parallel 还要声明音轨复用键与纵向排列策略
19
19
  * - [hook] Temporal.onTimeState:锚点归并后固化调性、速度等状态
20
- * - [hook] loweringAugment:最终列和 layoutLine 固化后扫描结果并生成要追加的 attachment
21
- * - [hook] loweringFinalize:所有派生 attachment 追加完成后,按注册顺序处理完整结果
22
20
  */
23
21
  export class LoweringContext {
24
- loweringAugmenters = [];
25
- loweringFinalizers = [];
22
+ activeFinalizers = new Map();
26
23
  cnt = 0; // 生成唯一id的计数器
27
24
  usedTracks = new Set();
28
25
  /** 不推进时间的附属对象 */
@@ -40,22 +37,7 @@ export class LoweringContext {
40
37
  */
41
38
  activeLoweringGroups = [];
42
39
  /** 收集本轮 lowering 产生的诊断信息 */
43
- diagnostics;
44
- constructor(diagnostics = []) {
45
- this.diagnostics = diagnostics;
46
- }
47
- /** 供外部调用: 初始化 hook */
48
- registerFunctions(functionClasses) {
49
- const augmenters = this.loweringAugmenters = [];
50
- const finalizers = this.loweringFinalizers = [];
51
- for (const functionClass of functionClasses) {
52
- if (functionClass.loweringAugment)
53
- augmenters.push(functionClass.loweringAugment);
54
- const finalize = functionClass.loweringFinalize;
55
- if (finalize && !finalizers.includes(finalize))
56
- finalizers.push(finalize); // 判重是因为pb直接引用了br的实现
57
- }
58
- }
40
+ diagnostics = [];
59
41
  /** 供 page 函数调用 */
60
42
  setPageConfig(page) {
61
43
  this.page = page;
@@ -63,16 +45,17 @@ export class LoweringContext {
63
45
  /**
64
46
  * 完整 lowering 入口
65
47
  *
66
- * 每次调用都会重置本轮产生的数据
67
- * 已注册的后处理 hook 会保留,可以复用同一个 LoweringContext
48
+ * 每次调用都会重置本轮产生的数据,可以复用同一个 LoweringContext
68
49
  */
69
- lowerDocument(node) {
50
+ lowerDocument(node, diagnostics = []) {
70
51
  this.cnt = 0;
71
52
  this.usedTracks.clear();
53
+ this.activeFinalizers.clear();
72
54
  this.attachments = [];
73
55
  this.page = void 0;
74
56
  this.astToTemporal = new Map();
75
57
  this.activeLoweringGroups = [];
58
+ this.diagnostics = diagnostics;
76
59
  const rootTrack = new Track();
77
60
  const duration = new Fraction();
78
61
  const columns = this.trackedEvents(node, duration, rootTrack);
@@ -123,7 +106,6 @@ export class LoweringContext {
123
106
  column.shiftTime(timeOffset);
124
107
  let insertion;
125
108
  for (const node of column) {
126
- state.currentEvent = node;
127
109
  state.velocity = velocityOf(node.track);
128
110
  state.program = programOf(node.track);
129
111
  const offset = node.onTimeState?.(state);
@@ -160,14 +142,14 @@ export class LoweringContext {
160
142
  }
161
143
  /**
162
144
  * 开始一个 lowering 分组作用域
163
- * group 可以收集并提交新增 temporal,也可以观察成员并携带一个 attachment
145
+ * group 可以观察当前子树产生的 TemporalNode 和 attachment
164
146
  */
165
147
  beginLoweringGroup(owner, group) {
166
148
  this.activeLoweringGroups.push({ owner, group });
167
149
  }
168
150
  /**
169
- * 结束最近的分组并注册其辅助排版对象
170
- * 嵌套分组按退出顺序注册,因此天然是由内向外计算边界
151
+ * 结束最近的分组并返回它
152
+ * 调用方可在退出分组后按需注册自身 attachment,天然实现由内向外计算边界
171
153
  */
172
154
  endLoweringGroup(owner) {
173
155
  const active = this.activeLoweringGroups.pop();
@@ -175,26 +157,32 @@ export class LoweringContext {
175
157
  throw new Error("No active lowering group to end");
176
158
  if (active.owner !== owner)
177
159
  throw new Error("Lowering groups must end in reverse order");
178
- if (active.group.attachment)
179
- this.addAttachment(active.group.attachment);
180
160
  return active.group;
181
161
  }
182
- /** 先统一生成派生 attachment,再按注册顺序执行最终处理 */
162
+ /** 按显式 order 升序执行本轮登记的收尾回调 */
183
163
  postprocessResult(result) {
184
164
  if (this.activeLoweringGroups.length > 0)
185
165
  throw new Error("Lowering groups must be closed before post-processing");
186
- const additions = [];
187
- for (const augment of this.loweringAugmenters) {
188
- for (const attachment of augment(result))
189
- additions.push(attachment);
166
+ const size = this.activeFinalizers.size;
167
+ if (size === 0)
168
+ return result;
169
+ if (size === 1) {
170
+ this.activeFinalizers.keys().next().value(result);
171
+ return result;
190
172
  }
191
- for (const attachment of additions)
192
- this.addAttachment(attachment);
193
- // 进行校验或者其他动作
194
- for (const finalize of this.loweringFinalizers)
173
+ const scheduled = [...this.activeFinalizers.entries()]
174
+ .sort((left, right) => left[1] - right[1]);
175
+ for (const [finalize] of scheduled)
195
176
  finalize(result);
196
177
  return result;
197
178
  }
179
+ /** 登记本轮需要执行的收尾回调;order 越小越先执行,默认 0 */
180
+ deferFinalize(finalize, order = 0) {
181
+ const current = this.activeFinalizers.get(finalize);
182
+ if (current === undefined || order < current) {
183
+ this.activeFinalizers.set(finalize, order);
184
+ }
185
+ }
198
186
  /**
199
187
  * 注册不推进时间的排版对象
200
188
  * 被 tie、beam、box 等函数使用
@@ -242,9 +230,9 @@ export class LoweringContext {
242
230
  * 递归展开一棵子树,得到它的时间列与结束时间
243
231
  * @param timeOffset 当前节点的时间偏移量(单位QN) 由父节点传入,会被原地修改
244
232
  * @param track 当前所在的纵向音轨
233
+ * @param columns 当前时间列数组,会被原地修改
245
234
  */
246
- trackedEvents(node, timeOffset, track) {
247
- const columns = [];
235
+ trackedEvents(node, timeOffset, track, columns = []) {
248
236
  this.appendEvents(node.loweringEnter(this, track), node, timeOffset, track, columns);
249
237
  // 处理子元素
250
238
  const model = node.timeFlowModel(this);
@@ -253,8 +241,7 @@ export class LoweringContext {
253
241
  case "sequence":
254
242
  {
255
243
  for (const c of model.children) {
256
- for (const column of this.trackedEvents(c, timeOffset, track))
257
- columns.push(column);
244
+ this.trackedEvents(c, timeOffset, track, columns);
258
245
  }
259
246
  }
260
247
  break;
@@ -346,7 +333,7 @@ export class LoweringContext {
346
333
  return tracks[0];
347
334
  const result = [];
348
335
  // 归并多个轨道
349
- const p = new Uint16Array(l); // 当前指向第几个
336
+ const p = new Uint32Array(l); // 当前指向第几个
350
337
  const dt = Array.from({ length: l }, () => new Fraction()); // 每个轨道的偏移量
351
338
  const anchorBuffer = [];
352
339
  const heap = new HeapSort(l); // 保证每个轨在堆里最多一个
@@ -1,4 +1,11 @@
1
- import type { Extent } from "../layout/types.js";
1
+ /**
2
+ * 相对某条基线的纵向占用
3
+ * 约定 top <= 0 <= bottom
4
+ */
5
+ export interface Extent {
6
+ top: number;
7
+ bottom: number;
8
+ }
2
9
  /** measure 给出的单个成员的局部位置 */
3
10
  export interface TrackPlacement {
4
11
  /**
@@ -3,8 +3,19 @@ import type { TemporalNodeBase } from "../functions/temporal.js";
3
3
  import type { Diagnostic } from "../diagnostic.js";
4
4
  import type { SourceSpan } from "../parser/types.js";
5
5
  import type { Fraction } from "../fraction.js";
6
- import type { PageConfig } from "../layout/types.js";
7
6
  import type { Track, TrackArrangement } from "./track.js";
7
+ /** 文档页面的固化尺寸,所有值均为 px */
8
+ export interface PageConfig {
9
+ width: number;
10
+ height: number;
11
+ marginTop: number;
12
+ marginBottom: number;
13
+ marginLeft: number;
14
+ marginRight: number;
15
+ lineGap: number;
16
+ minLineGap: number;
17
+ fillRatio: number;
18
+ }
8
19
  /** lowering 产生的不推进时间的附属对象;具体能力由 layout/playback 子协议声明 */
9
20
  export interface LoweringAttachment {
10
21
  readonly sourceSpan?: SourceSpan;
@@ -14,9 +25,7 @@ export interface LoweringContent {
14
25
  nodes: TemporalNodeBase[];
15
26
  attachments: LoweringAttachment[];
16
27
  }
17
- /** 时间流固化后生成额外 attachment;读取统一追加前的结果,不直接修改结果 */
18
- export type LoweringAugmenter = (result: LoweringResult) => Iterable<LoweringAttachment>;
19
- /** 所有 augmenter 结果追加完成后的最终处理;按注册顺序执行,可修改完整结果或抛出语义错误 */
28
+ /** 收尾阶段回调;按显式 order 升序执行,可追加派生 attachment、修改结果或抛出语义错误 */
20
29
  export type LoweringFinalizer = (result: LoweringResult) => void;
21
30
  /**
22
31
  * lowering 的输出
@@ -42,13 +51,6 @@ export interface LoweringResult {
42
51
  * 回调按当前作用域栈由内向外执行;onTemporal 在事件加入时间列、推进时间游标前调用。
43
52
  */
44
53
  export interface LoweringGroup {
45
- /**
46
- * 当前分组退出后会自动注册的 attachment
47
- *
48
- * attachment 在 layout 的时候会按照顺序求解,对于 box 这样的必须让子元素先被测量,才能确定尺寸,所以需要最后加入
49
- * 之所以有这个字段(而不是在 endLoweringGroup 之后手动 push)是为了收集到的信息可以直接传递,参考 box
50
- */
51
- attachment?: LoweringAttachment;
52
54
  /** 观察组内生成的事件 */
53
55
  onTemporal?(node: TemporalNodeBase): void;
54
56
  /** 观察组内注册的附属对象 */
@@ -13,10 +13,9 @@ import type { CallInfo } from "../grammarType.js";
13
13
  * - 正确处理字符串字面量(支持转义)
14
14
  * - 支持嵌套小括号 `(...)`,但被大括号 `{...}` 包裹的小括号不会影响外层匹配
15
15
  * - 忽略大括号内的小括号深度变化
16
- * - 在顶层小括号内以逗号分割参数,记录每个参数的原始文本及其在 `source` 中的起始/结束位置
16
+ * - 在顶层小括号内以逗号分割参数,同时记录每个参数的首个顶层 `=` 及其在 `source` 中的起始/结束位置
17
17
  * - 若找到匹配右括号,记录 closeParenSpan;否则在 end 处结束,让上层决定诊断/恢复策略
18
18
  */
19
19
  export declare function readCall(source: string, atPos: number, end: number): CallInfo | null;
20
20
  export declare function trimRange(source: string, start: number, end: number): SourceSpan;
21
- export declare function findTopLevelEquals(text: string, start?: number, end?: number): number;
22
21
  export declare function findRightParen(source: string, start: number, end: number): number;
@@ -13,7 +13,7 @@ const CALL_NAME_CHAR_RE = /[A-Za-z0-9_./-]/;
13
13
  * - 正确处理字符串字面量(支持转义)
14
14
  * - 支持嵌套小括号 `(...)`,但被大括号 `{...}` 包裹的小括号不会影响外层匹配
15
15
  * - 忽略大括号内的小括号深度变化
16
- * - 在顶层小括号内以逗号分割参数,记录每个参数的原始文本及其在 `source` 中的起始/结束位置
16
+ * - 在顶层小括号内以逗号分割参数,同时记录每个参数的首个顶层 `=` 及其在 `source` 中的起始/结束位置
17
17
  * - 若找到匹配右括号,记录 closeParenSpan;否则在 end 处结束,让上层决定诊断/恢复策略
18
18
  */
19
19
  export function readCall(source, atPos, end) {
@@ -35,13 +35,13 @@ export function readCall(source, atPos, end) {
35
35
  // 参数相关
36
36
  const argInfo = [];
37
37
  let lastCommaPos = openPos + 1;
38
+ let equals = -1;
38
39
  // 按照 `key = value` 或者 `value` 的模式匹配各个token的span
39
40
  // keepEmpty=true 用于保留 @func(,key=val) 这种情况的空参数
40
41
  const pushArg = (end, commaPos, keepEmpty = false) => {
41
42
  const span = trimRange(source, lastCommaPos, end);
42
43
  if (!keepEmpty && span.start >= span.end)
43
44
  return;
44
- const equals = findTopLevelEquals(source, span.start, span.end);
45
45
  const nameSpan = equals > span.start ? trimRange(source, span.start, equals) : undefined;
46
46
  const valueSpan = equals > span.start ? trimRange(source, equals + 1, span.end) : span;
47
47
  argInfo.push({
@@ -95,6 +95,10 @@ export function readCall(source, atPos, end) {
95
95
  pushArg(i, i, true); // 即使为空也有位置信息
96
96
  // 跳过逗号
97
97
  lastCommaPos = i + 1;
98
+ equals = -1;
99
+ }
100
+ else if (ch === "=" && equals === -1 && parenDepth === 1 && braceDepth === 0) {
101
+ equals = i;
98
102
  }
99
103
  }
100
104
  // 未闭合调用仍保留已有结构;ParserContext 根据 closeParenSpan 生成诊断
@@ -111,38 +115,6 @@ export function trimRange(source, start, end) {
111
115
  e -= 1;
112
116
  return { start: s, end: e };
113
117
  }
114
- export function findTopLevelEquals(text, start = 0, end = text.length) {
115
- let parenDepth = 0;
116
- let braceDepth = 0;
117
- let quote = null;
118
- let escaped = false;
119
- for (let i = start; i < end; i++) {
120
- const ch = text[i];
121
- if (quote) {
122
- if (escaped)
123
- escaped = false;
124
- else if (ch === "\\")
125
- escaped = true;
126
- else if (ch === quote)
127
- quote = null;
128
- continue;
129
- }
130
- if (ch === '"')
131
- quote = ch;
132
- // 依旧忽略大括号里面的小括号
133
- else if (ch === "(" && braceDepth === 0)
134
- parenDepth++;
135
- else if (ch === ")" && braceDepth === 0)
136
- parenDepth = Math.max(0, parenDepth - 1);
137
- else if (ch === "{")
138
- braceDepth++;
139
- else if (ch === "}")
140
- braceDepth = Math.max(0, braceDepth - 1);
141
- else if (ch === "=" && parenDepth === 0 && braceDepth === 0)
142
- return i;
143
- }
144
- return -1;
145
- }
146
118
  // 不管大括号 适用于小括号里传递字符串但没加引号的情况
147
119
  export function findRightParen(source, start, end) {
148
120
  let parenDepth = 1;
@@ -7,14 +7,14 @@ export interface RelativeJianpuPitch {
7
7
  renderAcc: string;
8
8
  renderOctave: number;
9
9
  }
10
- export declare function tonality2Midi(tonality: string, defaultOctave: number): number;
10
+ export declare function tonality2Midi(tonality: string): number | null;
11
11
  export declare function acc2Offset(acc: string, ignoreNatural?: boolean, initOffset?: number): number;
12
12
  export declare function resolveNoteMidi(name: string, acc: string, octave: number, keySignature: string): number | null;
13
13
  /**
14
14
  * 固化音符在当前大调中的位置,返回“沿调内音级移动”的闭包
15
15
  *
16
16
  * 交出闭包而不是数据结构,播放层因此无需认识任何调性模型。
17
- * 基准位置不包含主体的临时升降号。
17
+ * 基准位置基于已归一化的简谱级数与相对八度,不包含主体的临时升降号。
18
18
  */
19
- export declare function createDiatonicTranspose(name: string, acc: string, octave: number, keySignature: string): ((steps: number) => number) | undefined;
19
+ export declare function createDiatonicTranspose(name: string, octave: number, keySignature: string): ((steps: number) => number) | undefined;
20
20
  export declare function resolveLetterNameToJianpu(name: string, acc: string, octave: number, keySignature: string): RelativeJianpuPitch | null;
@@ -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,31 +24,31 @@ 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 Bb3 等调性字符串,输出 MIDI 数值;格式不合法返回 null
28
+ // 要求非常严格:必须 [大写字母][最多一个 #b][绝对八度]
29
+ export function tonality2Midi(tonality) {
31
30
  // 解析音名
32
31
  const note = tonality[0];
32
+ if (!note || note < "A" || note > "G")
33
+ return null;
33
34
  let acc = "";
34
35
  let i = 1;
35
36
  // 解析升降号
36
- if (i < tonality.length && (tonality[i] === '#' || tonality[i] === 'b' || tonality[i] === 'n')) {
37
+ if (i < tonality.length && (tonality[i] === "#" || tonality[i] === "b")) {
37
38
  acc = tonality[i];
38
39
  i++;
39
40
  }
40
41
  // 组合音名和升降号
41
- let noteValue = NoteNameMap[note + acc];
42
+ const noteValue = NoteNameMap[note + acc];
42
43
  if (noteValue === undefined)
43
- throw Diagnostic.error.InvalidTonality(tonality, { start: 0, end: i });
44
+ return null;
44
45
  // 解析八度
45
- if (i < tonality.length) {
46
- const octave = tonality.slice(i);
47
- defaultOctave = Number(octave);
48
- if (!/^-?\d+$/.test(octave) || !Number.isSafeInteger(defaultOctave)) {
49
- throw Diagnostic.error.InvalidTonality(tonality, { start: i, end: tonality.length });
50
- }
46
+ const octaveText = tonality.slice(i);
47
+ const octave = Number(octaveText);
48
+ if (!/^-?\d+$/.test(octaveText) || !Number.isSafeInteger(octave)) {
49
+ return null;
51
50
  }
52
- return (defaultOctave + 1) * 12 + noteValue;
51
+ return (octave + 1) * 12 + noteValue;
53
52
  }
54
53
  // ignoreNatural: 是否忽略还原号对升降号的重置作用。默认为true,即默认自然音符不重置acc
55
54
  // initOffset: 该小节累加的升降号偏移量 仅在ignoreNatural=false时有意义
@@ -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
  }
@@ -78,24 +77,13 @@ export function resolveNoteMidi(name, acc, octave, keySignature) {
78
77
  * 固化音符在当前大调中的位置,返回“沿调内音级移动”的闭包
79
78
  *
80
79
  * 交出闭包而不是数据结构,播放层因此无需认识任何调性模型。
81
- * 基准位置不包含主体的临时升降号。
80
+ * 基准位置基于已归一化的简谱级数与相对八度,不包含主体的临时升降号。
82
81
  */
83
- export function createDiatonicTranspose(name, acc, octave, keySignature) {
84
- let degreeIndex;
85
- let relativeOctave;
86
- if (name >= "1" && name <= "7") {
87
- degreeIndex = Number(name) - 1;
88
- relativeOctave = octave;
89
- }
90
- else {
91
- const relative = resolveLetterNameToJianpu(name, acc, octave, keySignature);
92
- if (!relative)
93
- return undefined;
94
- degreeIndex = Number(relative.renderName) - 1;
95
- relativeOctave = relative.renderOctave;
96
- }
97
- const tonicMidi = tonality2Midi(keySignature, 4);
98
- const base = relativeOctave * 7 + degreeIndex;
82
+ export function createDiatonicTranspose(name, octave, keySignature) {
83
+ if (name < "1" || name > "7")
84
+ return undefined;
85
+ const tonicMidi = tonality2Midi(keySignature);
86
+ const base = octave * 7 + Number(name) - 1;
99
87
  return steps => {
100
88
  const total = base + steps;
101
89
  const shift = Math.floor(total / 7);
@@ -124,7 +112,7 @@ export function resolveLetterNameToJianpu(name, acc, octave, keySignature) {
124
112
  const actualMidi = resolveNoteMidi(name, acc, octave, keySignature);
125
113
  if (tonicIndex < 0 || noteIndex < 0 || actualMidi === null)
126
114
  return null;
127
- const tonicMidi = tonality2Midi(keySignature, 4);
115
+ const tonicMidi = tonality2Midi(keySignature);
128
116
  const degreeIndex = (noteIndex - tonicIndex + LETTER_ORDER.length) % LETTER_ORDER.length;
129
117
  const expectedPitchClass = wrapPitchClass(tonicMidi + MAJOR_SCALE_OFFSETS[degreeIndex]);
130
118
  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
+ /** 剥掉成对的双引号(若有)并解码编码/定界级转义(`\"`、`\\`、`\uXXXX`);其余 `\X` 原样保留给具体函数解析 */
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,25 @@ export function findClosingQuote(source, quotePos, end) {
12
13
  }
13
14
  return -1;
14
15
  }
15
- /** 剥掉成对的双引号并反转义 `\X` -> `X`;裸参数没走转义扫描,原样返回 */
16
- export function removeQuote(source) {
17
- if (source.length < 2 || !source.startsWith('"') || !source.endsWith('"'))
18
- return source;
19
- return source.slice(1, -1).replace(/\\(.)/gs, "$1");
16
+ /** 剥掉成对的双引号(若有)并解码编码/定界级转义(`\"`、`\\`、`\uXXXX`);其余 `\X` 原样保留给具体函数解析 */
17
+ export function parseString(source) {
18
+ const quoted = source.length >= 2 && source.startsWith('"') && source.endsWith('"');
19
+ const raw = quoted ? source.slice(1, -1) : source;
20
+ let diagnostic;
21
+ // 连同不完整转义一起匹配以便诊断;替换结果不会被再次扫描
22
+ const text = raw.replace(/\\(u.{0,4}|.)/gs, (escape, body, offset) => {
23
+ if (body === '"' || body === "\\")
24
+ return body;
25
+ if (body[0] !== "u")
26
+ return escape;
27
+ if (!/^u[0-9a-f]{4}$/i.test(body)) {
28
+ const start = offset + (quoted ? 1 : 0);
29
+ diagnostic ??= Diagnostic.warning.InvalidUnicodeEscape({ start, end: start + escape.length });
30
+ return escape;
31
+ }
32
+ return String.fromCharCode(Number.parseInt(body.slice(1), 16));
33
+ });
34
+ return diagnostic ?? text;
20
35
  }
21
36
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
22
37
  export function quote(value) {
@@ -3,7 +3,6 @@ import { Diagnostic } from "../diagnostic.js";
3
3
  import { GrammarCallNode, GrammarNode, type SyntaxAnalysis } from "./grammarType.js";
4
4
  import { ASTFunctionClass, ASTFunctionNode, ASTNodeBase, paramType, paramValue } from "../functions/ASTtypes.js";
5
5
  export declare const DEFAULT_FONT_SIZE = 22;
6
- export declare const DEFAULT_OCTAVE = 4;
7
6
  export declare class ParserContext {
8
7
  /** 系统变量,供 `@set` 读取 */
9
8
  static systemVariables: Record<string, {
@@ -62,17 +61,18 @@ export declare class ParserContext {
62
61
  private addSyntax;
63
62
  /** 把已识别的 GrammarNode 映射为源码 token;content/brace 在这里继续递归 */
64
63
  private recordSyntax;
64
+ /**
65
+ * 向前寻找最后一个非文本节点下标;
66
+ * 若末尾是标签,则将“被标注节点..标签”原位打包为 ASTBraceNode
67
+ */
68
+ findLastOperandIndex(): number;
69
+ /** 摘出末尾最后一个操作数(含其后置标签) */
70
+ takeLeftOperand(): ASTNodeBase | null;
71
+ /** 解析右侧剩余序列,将首个非文本节点交给 combine 合成后连同后续节点写回 this.nodes */
72
+ consumeRightOperand(nodes: (GrammarNode | number)[], at: number, combine: (right: ASTNodeBase) => ASTNodeBase): number | null;
65
73
  /**
66
74
  * 第二轮去糖 & 函数节点创建
67
75
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
68
- * 对于需要后面Node的语法糖(没有终止符),可以调用此函数,具体做法为:
69
- * 1. 先用构造函数开启子上下文
70
- * 2. 再用新的上下文解析剩余的nodes
71
- * 3. 选取需要的,利用老的ctx构建函数节点
72
- * 4. 将新ctx的有用信息合并回老的ctx
73
- * 之所以这么麻烦,是因为创建语法糖对应节点时需要保留当前上下文
74
- *
75
- * 对于有终止符的直接搜索后面的终止符即可。扫过的地方普通文本会再次被合并
76
76
  */
77
77
  makeNodes(nodes: (GrammarNode | number)[], i?: number, end?: number): number;
78
78
  /**
@@ -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";
@@ -23,7 +23,6 @@ function classifySyntaxValue(type, text) {
23
23
  return undefined;
24
24
  }
25
25
  export const DEFAULT_FONT_SIZE = 22;
26
- export const DEFAULT_OCTAVE = 4;
27
26
  // 解析上下文
28
27
  export class ParserContext {
29
28
  /** 系统变量,供 `@set` 读取 */
@@ -231,17 +230,62 @@ export class ParserContext {
231
230
  }
232
231
  this.addSyntax("punctuation", call.closeParenSpan);
233
232
  }
233
+ /**
234
+ * 向前寻找最后一个非文本节点下标;
235
+ * 若末尾是标签,则将“被标注节点..标签”原位打包为 ASTBraceNode
236
+ */
237
+ findLastOperandIndex() {
238
+ let left = this.nodes.length - 1;
239
+ while (left >= 0 && this.nodes[left] instanceof ASTTextNode)
240
+ left--;
241
+ if (left < 0)
242
+ return -1;
243
+ const node = this.nodes[left];
244
+ if (node instanceof ASTLabelNode) {
245
+ let tgt = node.target;
246
+ while (tgt.parent)
247
+ tgt = tgt.parent;
248
+ const j = this.nodes.lastIndexOf(tgt, left - 1);
249
+ if (j < 0)
250
+ return -1;
251
+ this.nodes.splice(j, left - j + 1, new ASTBraceNode({ start: tgt.sourceSpan.start, end: node.sourceSpan.end }, this.nodes.slice(j, left + 1), null));
252
+ return j;
253
+ }
254
+ return left;
255
+ }
256
+ /** 摘出末尾最后一个操作数(含其后置标签) */
257
+ takeLeftOperand() {
258
+ const index = this.findLastOperandIndex();
259
+ if (index < 0)
260
+ return null;
261
+ const node = this.nodes[index];
262
+ this.nodes.length = index;
263
+ return node;
264
+ }
265
+ /** 解析右侧剩余序列,将首个非文本节点交给 combine 合成后连同后续节点写回 this.nodes */
266
+ consumeRightOperand(nodes, at, combine) {
267
+ const storage = this.nodes;
268
+ this.nodes = [];
269
+ try {
270
+ this.makeNodes(nodes, at);
271
+ for (let i = 0; i < this.nodes.length; i++) {
272
+ const right = this.nodes[i];
273
+ if (right instanceof ASTTextNode)
274
+ continue;
275
+ storage.push(combine(right));
276
+ while (++i < this.nodes.length)
277
+ storage.push(this.nodes[i]);
278
+ return nodes.length;
279
+ }
280
+ return null;
281
+ }
282
+ finally {
283
+ this.nodes = storage;
284
+ }
285
+ }
234
286
  /**
235
287
  * 第二轮去糖 & 函数节点创建
236
288
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
237
- * 对于需要后面Node的语法糖(没有终止符),可以调用此函数,具体做法为:
238
- * 1. 先用构造函数开启子上下文
239
- * 2. 再用新的上下文解析剩余的nodes
240
- * 3. 选取需要的,利用老的ctx构建函数节点
241
- * 4. 将新ctx的有用信息合并回老的ctx
242
- * 之所以这么麻烦,是因为创建语法糖对应节点时需要保留当前上下文
243
- *
244
- * 对于有终止符的直接搜索后面的终止符即可。扫过的地方普通文本会再次被合并
245
289
  */
246
290
  makeNodes(nodes, i = 0, end = nodes.length) {
247
291
  outer: for (; i < end; i++) {
@@ -529,7 +573,14 @@ export class ParserContext {
529
573
  return l;
530
574
  // 其他类型一律视为string
531
575
  default:
532
- return removeQuote(text);
576
+ const s = parseString(text);
577
+ if (s instanceof Diagnostic) {
578
+ s.span.start += start;
579
+ s.span.end += start;
580
+ this.diagnostics.push(s);
581
+ return text.length >= 2 && text.startsWith('"') && text.endsWith('"') ? text.slice(1, -1) : text;
582
+ }
583
+ return s;
533
584
  }
534
585
  }
535
586
  length2px(length) {
package/dist/pipeline.js CHANGED
@@ -19,9 +19,8 @@ export function compileScore(source, options = {}) {
19
19
  const parser = new ParserContext({ source: maskedSource, variables });
20
20
  parser.registerFunctions(functions);
21
21
  const ast = new ASTBraceNode({ start: 0, end: source.length }, parser.parse());
22
- const loweringContext = new LoweringContext(parser.diagnostics);
23
- loweringContext.registerFunctions(functions);
24
- const lowering = loweringContext.lowerDocument(ast);
22
+ const loweringContext = new LoweringContext();
23
+ const lowering = loweringContext.lowerDocument(ast, parser.diagnostics);
25
24
  const layoutContext = createLayoutPrepareContext(functions, { textMeasurer });
26
25
  const layout = layoutDocument(lowering, layoutContext, layoutOptions);
27
26
  return {