jpfun 0.3.0 → 0.4.1

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 (129) hide show
  1. package/README.md +73 -1
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/functions/ASTtypes.d.ts +30 -26
  23. package/dist/functions/ASTtypes.js +25 -23
  24. package/dist/functions/adjust/index.js +13 -6
  25. package/dist/functions/arpeggio/index.d.ts +2 -0
  26. package/dist/functions/arpeggio/index.js +184 -0
  27. package/dist/functions/arpeggio/shape.d.ts +7 -0
  28. package/dist/functions/arpeggio/shape.js +122 -0
  29. package/dist/functions/bar/index.js +30 -23
  30. package/dist/functions/beam/auto.d.ts +1 -1
  31. package/dist/functions/beam/auto.js +1 -1
  32. package/dist/functions/beam/index.js +6 -1
  33. package/dist/functions/beam/layout.d.ts +3 -3
  34. package/dist/functions/beam/layout.js +5 -3
  35. package/dist/functions/box/index.js +10 -3
  36. package/dist/functions/br/index.js +10 -6
  37. package/dist/functions/dash/index.js +12 -9
  38. package/dist/functions/default.js +6 -2
  39. package/dist/functions/div/index.d.ts +4 -1
  40. package/dist/functions/div/index.js +8 -7
  41. package/dist/functions/dot/index.js +18 -25
  42. package/dist/functions/dyn/index.d.ts +2 -0
  43. package/dist/functions/dyn/index.js +242 -0
  44. package/dist/functions/grace/index.d.ts +1 -1
  45. package/dist/functions/grace/index.js +17 -11
  46. package/dist/functions/head/index.js +168 -159
  47. package/dist/functions/key/index.js +12 -7
  48. package/dist/functions/meter/index.js +14 -6
  49. package/dist/functions/note/index.js +73 -31
  50. package/dist/functions/note/noteNameFSM.js +52 -63
  51. package/dist/functions/page/index.d.ts +5 -1
  52. package/dist/functions/page/index.js +38 -16
  53. package/dist/functions/program/index.d.ts +2 -0
  54. package/dist/functions/program/index.js +39 -0
  55. package/dist/functions/set/index.js +13 -8
  56. package/dist/functions/stack/index.js +7 -5
  57. package/dist/functions/symbol/index.d.ts +13 -3
  58. package/dist/functions/symbol/index.js +71 -22
  59. package/dist/functions/symbol/shape.d.ts +2 -0
  60. package/dist/functions/symbol/shape.js +14 -10
  61. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  62. package/dist/functions/symbol/symbols/dc.js +82 -0
  63. package/dist/functions/symbol/symbols/{f.d.ts → ds.d.ts} +1 -1
  64. package/dist/functions/symbol/symbols/ds.js +93 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  66. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  67. package/dist/functions/symbol/symbols/{p.d.ts → fine.d.ts} +1 -1
  68. package/dist/functions/symbol/symbols/fine.js +12 -0
  69. package/dist/functions/symbol/symbols/mordent.js +44 -31
  70. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/prall.js +42 -0
  72. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  73. package/dist/functions/symbol/symbols/segno.js +82 -0
  74. package/dist/functions/symbol/symbols/tr.js +0 -4
  75. package/dist/functions/tempo/index.js +12 -4
  76. package/dist/functions/temporal.d.ts +138 -0
  77. package/dist/functions/temporal.js +101 -0
  78. package/dist/functions/text/index.js +25 -10
  79. package/dist/functions/tie/index.js +45 -30
  80. package/dist/functions/tuplet/index.js +21 -8
  81. package/dist/functions/up/index.js +38 -33
  82. package/dist/functions/voice/index.js +153 -68
  83. package/dist/functions/volta/index.js +62 -55
  84. package/dist/iife/core.d.ts +1 -0
  85. package/dist/iife/core.js +3 -0
  86. package/dist/iife/from-midi.d.ts +1 -0
  87. package/dist/iife/from-midi.js +15 -0
  88. package/dist/iife/from-musicxml.d.ts +1 -0
  89. package/dist/iife/from-musicxml.js +3 -0
  90. package/dist/iife/full.d.ts +1 -0
  91. package/dist/iife/full.js +3 -0
  92. package/dist/index.d.ts +3 -21
  93. package/dist/index.js +3 -21
  94. package/dist/jpfun.core.min.js +119 -0
  95. package/dist/jpfun.from-midi.min.js +9 -0
  96. package/dist/jpfun.from-musicxml.min.js +12 -0
  97. package/dist/jpfun.min.js +111 -122
  98. package/dist/layout/default.js +2 -3
  99. package/dist/layout/engine.d.ts +2 -1
  100. package/dist/layout/engine.js +71 -26
  101. package/dist/layout/model.d.ts +4 -4
  102. package/dist/layout/model.js +15 -12
  103. package/dist/layout/page.js +5 -4
  104. package/dist/layout/path.js +3 -3
  105. package/dist/layout/types.d.ts +20 -2
  106. package/dist/lowering/loweringContext.d.ts +3 -1
  107. package/dist/lowering/loweringContext.js +28 -14
  108. package/dist/lowering/track.d.ts +4 -8
  109. package/dist/lowering/track.js +6 -1
  110. package/dist/lowering/types.d.ts +5 -128
  111. package/dist/lowering/types.js +1 -98
  112. package/dist/parser/parse-utils/string-utils.d.ts +2 -0
  113. package/dist/parser/parse-utils/string-utils.js +4 -0
  114. package/dist/parser/parserContext.d.ts +7 -8
  115. package/dist/parser/parserContext.js +41 -36
  116. package/dist/pipeline.d.ts +6 -5
  117. package/dist/pipeline.js +4 -5
  118. package/dist/playback/compile.d.ts +1 -1
  119. package/dist/playback/compile.js +15 -2
  120. package/dist/playback/event.d.ts +17 -3
  121. package/dist/playback/event.js +30 -12
  122. package/dist/playback/time.js +1 -1
  123. package/dist/playback/types.d.ts +5 -4
  124. package/dist/render/text.d.ts +6 -1
  125. package/dist/render/text.js +8 -1
  126. package/grammar.md +111 -57
  127. package/package.json +11 -2
  128. package/dist/functions/symbol/symbols/f.js +0 -55
  129. package/dist/functions/symbol/symbols/p.js +0 -61
@@ -1,34 +1,18 @@
1
- import { ASTNodeBase } from "../functions/ASTtypes.js";
1
+ import type { ASTNodeBase } from "../functions/ASTtypes.js";
2
+ import type { TemporalNodeBase } from "../functions/temporal.js";
2
3
  import type { Diagnostic } from "../diagnostic.js";
3
4
  import type { SourceSpan } from "../parser/types.js";
4
- import { Fraction } from "../fraction.js";
5
- import type { HorizontalSpringConfig, LayoutBox, LayoutDecoration, LayoutHost, PageConfig, LayoutPoint, LayoutPrepareContext, HorizontalLineView, TimeLineEvent } from "../layout/types.js";
6
- import type { Painter } from "../render/types.js";
7
- import type { PlaybackEmitter, PlaybackState } from "../playback/types.js";
5
+ import type { Fraction } from "../fraction.js";
6
+ import type { PageConfig } from "../layout/types.js";
8
7
  import type { Track, TrackArrangement } from "./track.js";
9
8
  /** lowering 产生的不推进时间的附属对象;具体能力由 layout/playback 子协议声明 */
10
9
  export interface LoweringAttachment {
11
10
  readonly sourceSpan?: SourceSpan;
12
11
  }
13
- /** 时间流固化后生成额外 attachment;所有 augmenter 读取同一份输入快照 */
12
+ /** 时间流固化后生成额外 attachment;读取统一追加前的结果,不直接修改结果 */
14
13
  export type LoweringAugmenter = (result: LoweringResult) => Iterable<LoweringAttachment>;
15
14
  /** 所有 augmenter 结果追加完成后的最终处理;按注册顺序执行,可修改完整结果或抛出语义错误 */
16
15
  export type LoweringFinalizer = (result: LoweringResult) => void;
17
- /**
18
- * 沿记谱顺序流动的时间状态
19
- *
20
- * 速度、力度、调性是系统级字段:有确定的类型和初值,任何时刻都能直接读,不用写兼容分支。
21
- * 其余键由具体函数自行约定,核心不认识。
22
- */
23
- export interface TimeState {
24
- bpm: number;
25
- velocity: number;
26
- keySignature: string;
27
- [key: string]: any;
28
- }
29
- export declare const DEFAULT_BPM = 120;
30
- export declare const DEFAULT_VELOCITY = 80;
31
- export declare const DEFAULT_TONALITY = "C4";
32
16
  /**
33
17
  * lowering 的输出
34
18
  *
@@ -81,110 +65,3 @@ export type TimeFlowModel = {
81
65
  children: ASTNodeBase[];
82
66
  tracks: TrackArrangement;
83
67
  };
84
- /**
85
- * 事件的合并组:同一时刻 mergeKey 相等的事件归并成一列
86
- *
87
- * 缺省取事件自身的 order,因而互不相等、各自独占一列;需要合并的显式取相同的值。
88
- * 数值同时决定同时刻的列先后,越小越靠左。已占用的共享常量:-1 br,-2 声部名
89
- */
90
- /** 时间对齐点(小节线);必须是最小值,最先出队 */
91
- export declare const ANCHOR_KEY: number;
92
- /** 普通事件的公共组 */
93
- export declare const DEFAULT_KEY: number;
94
- /**
95
- * 时间线事件
96
- *
97
- * 由 AST 节点在 lowering 阶段产生,负责得到时间、设置布局参数
98
- */
99
- export declare class TemporalNodeBase implements TimeLineEvent {
100
- readonly t: Fraction;
101
- readonly T: Fraction;
102
- track: Track;
103
- ast: ASTNodeBase;
104
- order: number;
105
- addon?: Record<string, any>;
106
- mergeKey: number;
107
- /**
108
- * 被折叠进哪个宿主的盒子(由宿主自己设置)
109
- *
110
- * 折叠成员不进入全局 columns,在时间流里没有独立位置,
111
- * 按全局事件工作的消费者可以沿链上溯到宿主。
112
- */
113
- foldedInto?: TemporalNodeBase;
114
- /**
115
- * 请求在自己所在时间列之前换几行,默认 0
116
- */
117
- breakBefore: number;
118
- /** 由 LoweringContext 在列归并后固化的谱面行号 */
119
- layoutLine: number;
120
- /** 不可见状态事件保持 undefined */
121
- box?: LayoutBox;
122
- /**
123
- * 横向弹簧布局参数
124
- * 大部分对象使用空对象即可采用布局器默认值
125
- */
126
- springConfig: HorizontalSpringConfig;
127
- /**
128
- * 关系函数可使用的命名局部坐标
129
- * prepareLayout 每次执行时由具体节点和装饰函数重新生成
130
- */
131
- ports: Record<string, LayoutPoint>;
132
- /**
133
- * 当前一次 layout 已经实例化并完成测量的装饰对象
134
- *
135
- * 起因:addon 只保存 lowering 阶段冻结的语义值,例如 `@div: 2`,它没有字号、局部坐标,也不能表达 note 自身生成的下八度点。
136
- * 布局需要把这些语义统一转换成可排序、可占高、可绘制的 LayoutDecoration 实例。
137
- *
138
- * 生命周期:
139
- * 1. layout 的 prepareLayoutHost 开始时创建或清空数组;
140
- * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
141
- * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
142
- * 4. arrangeBelowDecorations 按 below.order 分配主体下方空间并调用 below.place;
143
- * 5. 最终 paintLayout 在主体 paint 后依次调用 decoration.paint。
144
- *
145
- * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
146
- * prepare 阶段生成、place 后冻结、paint 后失效
147
- */
148
- decorations: LayoutDecoration[];
149
- /**
150
- * 创建并返回当前事件唯一的 LayoutBox
151
- * 可见子类应在构造函数中调用一次(或自行填写)
152
- */
153
- protected initLayoutBox(): LayoutBox;
154
- /**
155
- * 时间状态 修改&冻结 入口
156
- * 调用时机在时间位置已经确定之后,处理“调性、速度、拍号”等时间信息的固化
157
- */
158
- onTimeState?(state: TimeState): void;
159
- /** 把已固化的音乐语义声明为播放事件;不执行实时播放 */
160
- emitPlayback?(emitter: PlaybackEmitter): void;
161
- /** 给自己所在的时间列贴播放标记,供控制流游标查询 */
162
- playbackMarks?(): readonly string[];
163
- /** 向播放系统告知自己这个记谱位置上的速度与力度 */
164
- playbackState?: PlaybackState;
165
- /**
166
- * 根据已经固化的语义生成固有尺寸
167
- * 一般为测量函数自有图形或使用 LayoutPrepareContext.textMeasurer 测量文本,填写 box.w/h/anchor/visualAxis
168
- * 此时 x 和 y 仍然没有最终含义
169
- */
170
- prepareLayout(_ctx: LayoutPrepareContext): void;
171
- /** 横向拓扑建立后调整弹簧参数或注册横向布局 hook */
172
- prepareHorizontal?(_line: HorizontalLineView): void;
173
- /**
174
- * 得到了最终的 box 后被调用(和 prepareLayout 之间隔了 decoration 的布局计算)
175
- * 可在这里发布依赖最终 box.w/box.h 的端口
176
- */
177
- finalizeLayout?(_ctx: LayoutPrepareContext): void;
178
- /**
179
- * 布局器每次改变 x 或 y 后调用
180
- * 普通叶节点不需要处理,具有内部几何的复合节点可用它同步子对象坐标
181
- */
182
- onPlaced?(): void;
183
- /**
184
- * 只执行绘制,不允许在这里重新测量或改变 LayoutBox
185
- */
186
- paint(_painter: Painter): void;
187
- }
188
- /** 可以进入视觉布局的 Temporal,同时满足 decoration 所需的 LayoutHost 协议 */
189
- export type VisualTemporalNode = TemporalNodeBase & LayoutHost;
190
- export declare function isVisualTemporalNode(node: TemporalNodeBase): node is VisualTemporalNode;
@@ -1,98 +1 @@
1
- import { Fraction } from "../fraction.js";
2
- export const DEFAULT_BPM = 120;
3
- export const DEFAULT_VELOCITY = 80;
4
- export const DEFAULT_TONALITY = "C4";
5
- /**
6
- * 事件的合并组:同一时刻 mergeKey 相等的事件归并成一列
7
- *
8
- * 缺省取事件自身的 order,因而互不相等、各自独占一列;需要合并的显式取相同的值。
9
- * 数值同时决定同时刻的列先后,越小越靠左。已占用的共享常量:-1 br,-2 声部名
10
- */
11
- /** 时间对齐点(小节线);必须是最小值,最先出队 */
12
- export const ANCHOR_KEY = -Infinity;
13
- /** 普通事件的公共组 */
14
- export const DEFAULT_KEY = Infinity;
15
- /**
16
- * 时间线事件
17
- *
18
- * 由 AST 节点在 lowering 阶段产生,负责得到时间、设置布局参数
19
- */
20
- export class TemporalNodeBase {
21
- // 下面这批字段统一由 LoweringContext.initEvent 原地补全
22
- // 横向 layout 要用的三个属性
23
- t = new Fraction(); // 事件发生的时间点
24
- T = new Fraction(); // 事件的持续时间
25
- track; // 所在的纵向音轨;同轨判断使用引用相等
26
- ast; // 对应的 AST 节点
27
- order; // 事件创建序号,作为id。可用于区分同时发生的父子、排序同一时刻发生的事件
28
- addon; // 其他任意字段,仅在存在已固化的函数语义时创建,比如存储 div 和 dot 的数目
29
- mergeKey; // 时间列合并组
30
- /**
31
- * 被折叠进哪个宿主的盒子(由宿主自己设置)
32
- *
33
- * 折叠成员不进入全局 columns,在时间流里没有独立位置,
34
- * 按全局事件工作的消费者可以沿链上溯到宿主。
35
- */
36
- foldedInto;
37
- /**
38
- * 请求在自己所在时间列之前换几行,默认 0
39
- */
40
- breakBefore = 0;
41
- /** 由 LoweringContext 在列归并后固化的谱面行号 */
42
- layoutLine = 0;
43
- /** 不可见状态事件保持 undefined */
44
- box;
45
- /**
46
- * 横向弹簧布局参数
47
- * 大部分对象使用空对象即可采用布局器默认值
48
- */
49
- springConfig;
50
- /**
51
- * 关系函数可使用的命名局部坐标
52
- * prepareLayout 每次执行时由具体节点和装饰函数重新生成
53
- */
54
- ports;
55
- /**
56
- * 当前一次 layout 已经实例化并完成测量的装饰对象
57
- *
58
- * 起因:addon 只保存 lowering 阶段冻结的语义值,例如 `@div: 2`,它没有字号、局部坐标,也不能表达 note 自身生成的下八度点。
59
- * 布局需要把这些语义统一转换成可排序、可占高、可绘制的 LayoutDecoration 实例。
60
- *
61
- * 生命周期:
62
- * 1. layout 的 prepareLayoutHost 开始时创建或清空数组;
63
- * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
64
- * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
65
- * 4. arrangeBelowDecorations 按 below.order 分配主体下方空间并调用 below.place;
66
- * 5. 最终 paintLayout 在主体 paint 后依次调用 decoration.paint。
67
- *
68
- * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
69
- * prepare 阶段生成、place 后冻结、paint 后失效
70
- */
71
- decorations;
72
- /**
73
- * 创建并返回当前事件唯一的 LayoutBox
74
- * 可见子类应在构造函数中调用一次(或自行填写)
75
- */
76
- initLayoutBox() {
77
- return this.box = {
78
- x: 0, y: 0,
79
- w: 0, h: 0,
80
- anchor: 0, visualAxis: 0,
81
- };
82
- }
83
- /** 向播放系统告知自己这个记谱位置上的速度与力度 */
84
- playbackState;
85
- /**
86
- * 根据已经固化的语义生成固有尺寸
87
- * 一般为测量函数自有图形或使用 LayoutPrepareContext.textMeasurer 测量文本,填写 box.w/h/anchor/visualAxis
88
- * 此时 x 和 y 仍然没有最终含义
89
- */
90
- prepareLayout(_ctx) { }
91
- /**
92
- * 只执行绘制,不允许在这里重新测量或改变 LayoutBox
93
- */
94
- paint(_painter) { }
95
- }
96
- export function isVisualTemporalNode(node) {
97
- return node.box !== undefined;
98
- }
1
+ export {};
@@ -6,3 +6,5 @@
6
6
  export declare function findClosingQuote(source: string, quotePos: number, end: number): number;
7
7
  /** 剥掉成对的双引号并反转义 `\X` -> `X`;裸参数没走转义扫描,原样返回 */
8
8
  export declare function removeQuote(source: string): string;
9
+ /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
10
+ export declare function quote(value: string): string;
@@ -18,3 +18,7 @@ export function removeQuote(source) {
18
18
  return source;
19
19
  return source.slice(1, -1).replace(/\\(.)/gs, "$1");
20
20
  }
21
+ /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
22
+ export function quote(value) {
23
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
24
+ }
@@ -4,9 +4,12 @@ import { GrammarCallNode, GrammarNode, type SyntaxAnalysis } from "./grammarType
4
4
  import { ASTFunctionClass, ASTFunctionNode, ASTNodeBase, paramType, paramValue } from "../functions/ASTtypes.js";
5
5
  export declare const DEFAULT_FONT_SIZE = 22;
6
6
  export declare const DEFAULT_OCTAVE = 4;
7
- /** 系统变量,供 `@set` 读取 */
8
- export declare const SYSTEM_VARIABLE_TYPES: Record<string, paramType>;
9
7
  export declare class ParserContext {
8
+ /** 系统变量,供 `@set` 读取 */
9
+ static systemVariables: Record<string, {
10
+ type: paramType;
11
+ default: paramValue;
12
+ }>;
10
13
  /** 根解析器为 0,内容参数和大括号子解析器依次加一 */
11
14
  readonly scopeDepth: number;
12
15
  /** 源代码 */
@@ -31,7 +34,7 @@ export declare class ParserContext {
31
34
  constructor(ctx: ParserContext | {
32
35
  source: string;
33
36
  diagnostics?: Diagnostic[];
34
- variables?: Map<string, any>;
37
+ variables?: Record<string, any>;
35
38
  functions?: Map<string, ASTFunctionClass>;
36
39
  labelableNodes?: (ASTFunctionNode | null)[];
37
40
  toConsume?: ASTNodeBase[];
@@ -42,11 +45,7 @@ export declare class ParserContext {
42
45
  deSugarRelationFunction[]
43
46
  ];
44
47
  pushNode(node: ASTNodeBase): void;
45
- get fontSize(): number;
46
- set fontSize(size: number);
47
- get strict(): boolean;
48
- set strict(value: boolean);
49
- setVariable(name: string, value: paramValue): void;
48
+ setVariable(name: string, value: paramValue | undefined): void;
50
49
  registerFunctions(functionClasses: ASTFunctionClass[]): void;
51
50
  /**
52
51
  * 扫描 GrammarNode 并构造 AST;不产出 syntax
@@ -1,4 +1,5 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
+ import { DEFAULT_TEXT_FONT, JIANPU_NUMBER_FONT } from "../render/text.js";
2
3
  import { readCall, trimRange } from "./parse-utils/call-utils.js";
3
4
  import { removeQuote } from "./parse-utils/string-utils.js";
4
5
  import { readBrace } from "./parse-utils/brace-utils.js";
@@ -22,15 +23,16 @@ function classifySyntaxValue(type, text) {
22
23
  return undefined;
23
24
  }
24
25
  export const DEFAULT_FONT_SIZE = 22;
25
- const DEFAULT_STRICT_MODE = false;
26
26
  export const DEFAULT_OCTAVE = 4;
27
- /** 系统变量,供 `@set` 读取 */
28
- export const SYSTEM_VARIABLE_TYPES = {
29
- fontsize: "length",
30
- strict: "boolean",
31
- };
32
27
  // 解析上下文
33
28
  export class ParserContext {
29
+ /** 系统变量,供 `@set` 读取 */
30
+ static systemVariables = {
31
+ fontsize: { type: "length", default: DEFAULT_FONT_SIZE },
32
+ font: { type: "string", default: DEFAULT_TEXT_FONT },
33
+ numberfont: { type: "string", default: JIANPU_NUMBER_FONT },
34
+ strict: { type: "boolean", default: false },
35
+ };
34
36
  /** 根解析器为 0,内容参数和大括号子解析器依次加一 */
35
37
  scopeDepth;
36
38
  /** 源代码 */
@@ -76,7 +78,8 @@ export class ParserContext {
76
78
  tokens: (ctx.commentSpans ?? []).map(span => ({ kind: "comment", span })),
77
79
  calls: [],
78
80
  };
79
- this.variables = ctx.variables ?? {};
81
+ this.variables = Object.fromEntries(Object.entries(ParserContext.systemVariables).map(([name, definition]) => [name, definition.default]));
82
+ Object.assign(this.variables, ctx.variables);
80
83
  this.functions = ctx.functions ?? new Map();
81
84
  this.labelableNodes = ctx.labelableNodes ?? [];
82
85
  this.nodes = ctx.toConsume ?? [];
@@ -108,25 +111,15 @@ export class ParserContext {
108
111
  if (target !== undefined)
109
112
  this.labelableNodes.push(target);
110
113
  }
111
- get fontSize() {
112
- return this.variables["fontsize"] ?? DEFAULT_FONT_SIZE;
113
- }
114
- set fontSize(size) {
115
- this.variables["fontsize"] = size;
116
- }
117
- get strict() {
118
- return this.variables["strict"] ?? DEFAULT_STRICT_MODE;
119
- }
120
- set strict(value) {
121
- this.variables["strict"] = value;
122
- }
114
+ // 统一管理系统变量和函数私有变量
123
115
  setVariable(name, value) {
124
- if (name === "fontsize")
125
- this.fontSize = this.length2px(value);
126
- else if (name === "strict")
127
- this.strict = value;
128
- else
129
- this.variables[name] = value;
116
+ if (Object.hasOwn(ParserContext.systemVariables, name)) {
117
+ if (name === "fontsize" && value)
118
+ value = this.length2px(value);
119
+ if (value === undefined || value === "" || value === 0)
120
+ value = ParserContext.systemVariables[name].default;
121
+ }
122
+ this.variables[name] = value;
130
123
  }
131
124
  registerFunctions(functionClasses) {
132
125
  const map = this.functions;
@@ -196,7 +189,7 @@ export class ParserContext {
196
189
  this.addSyntax("function", call.nameSpan);
197
190
  this.addSyntax("punctuation", call.openParenSpan);
198
191
  this.addSyntax("punctuation", call.closeParenSpan);
199
- const def = this.functions.get(call.name.toLowerCase())?.prototype.def;
192
+ const def = this.functions.get(call.name.toLowerCase())?.def;
200
193
  for (let index = 0; index < call.args.length; index++) {
201
194
  const arg = call.args[index];
202
195
  this.addSyntax("property", arg.nameSpan);
@@ -391,10 +384,9 @@ export class ParserContext {
391
384
  }
392
385
  parseCallNode(callNode) {
393
386
  const callFNClass = this.functions.get(callNode.name.toLowerCase());
394
- const def = callFNClass?.prototype.def;
395
- const defArgs = def?.args;
396
- if (!callFNClass || !defArgs) {
397
- if (this.strict) {
387
+ const def = callFNClass?.def;
388
+ if (!callFNClass || !def) {
389
+ if (this.variables.strict) {
398
390
  throw Diagnostic.error.UnknownFunction(callNode.name, callNode.span);
399
391
  }
400
392
  else {
@@ -403,6 +395,7 @@ export class ParserContext {
403
395
  // 未知函数,保留位置,但直接跳过
404
396
  return new ASTFunctionNode(callNode.span, null);
405
397
  }
398
+ const defArgs = def.args;
406
399
  // 用实际传参查询定义
407
400
  if (!callNode.typed) {
408
401
  const args = new Map();
@@ -460,7 +453,13 @@ export class ParserContext {
460
453
  this.diagnostics.push(Diagnostic.warning.InvalidBoolean(text, r));
461
454
  return null;
462
455
  }
463
- case "content":
456
+ case "content": {
457
+ // 用于失败后恢复(撤销改动)
458
+ const candidates = this.labelableNodes;
459
+ const length = candidates.length;
460
+ const target = candidates.at(-1);
461
+ const label = target?.label;
462
+ const hadLabel = target && Object.hasOwn(target, "label");
464
463
  // 开启新的局部解析器
465
464
  try {
466
465
  const subParser = new ParserContext(this);
@@ -470,14 +469,20 @@ export class ParserContext {
470
469
  return new ASTBraceNode(r, n, null);
471
470
  }
472
471
  catch (e) {
473
- if (this.strict)
472
+ candidates.length = length;
473
+ if (target) {
474
+ if (hadLabel)
475
+ target.label = label;
476
+ else
477
+ delete target.label;
478
+ }
479
+ if (this.variables.strict || !(e instanceof Diagnostic))
474
480
  throw e;
475
481
  // 当前参数会被跳过,因此在恢复点记录被吞掉的具体错误
476
- if (e instanceof Diagnostic)
477
- this.diagnostics.push(e);
478
- this.diagnostics.push(Diagnostic.warning.InvalidContent(r));
482
+ this.diagnostics.push(e, Diagnostic.warning.InvalidContent(r));
479
483
  return null;
480
484
  }
485
+ }
481
486
  case "label":
482
487
  // 应对潜在的问题: 如果先解析了content会导致ctx.lavelableNodes被污染
483
488
  funcStart ??= span.start;
@@ -513,7 +518,7 @@ export class ParserContext {
513
518
  length2px(length) {
514
519
  // 不进行错误判断了: 来自 parseArgWithType 的不会出问题
515
520
  if (length.unit === "em")
516
- return length.value * this.fontSize;
521
+ return length.value * this.variables.fontsize;
517
522
  else
518
523
  return length.value;
519
524
  }
@@ -1,16 +1,17 @@
1
1
  import { ASTBraceNode, type ASTFunctionClass } from "./functions/ASTtypes.js";
2
2
  import { type DocumentLayoutOptions, type DocumentLayoutResult } from "./layout/engine.js";
3
3
  import type { LoweringResult } from "./lowering/types.js";
4
- import { ParserContext } from "./parser/parserContext.js";
4
+ import type { Diagnostic } from "./diagnostic.js";
5
5
  import type { TextMeasurer } from "./render/types.js";
6
6
  export interface CompileScoreOptions extends DocumentLayoutOptions {
7
7
  functions?: ASTFunctionClass[];
8
8
  textMeasurer?: TextMeasurer;
9
- fontSize?: number;
9
+ variables?: Record<string, any>;
10
10
  }
11
11
  export interface CompileScoreResult {
12
12
  lineStarts: number[];
13
- parser: ParserContext;
13
+ maskedSource: string;
14
+ diagnostics: Diagnostic[];
14
15
  ast: ASTBraceNode;
15
16
  lowering: LoweringResult;
16
17
  layout: DocumentLayoutResult;
@@ -31,6 +32,6 @@ export declare function compileScore(source: string, options?: CompileScoreOptio
31
32
  * 该入口会把这些问题记录到 diagnostics,并尽量返回已经识别的 call/token,供高亮和补全继续工作
32
33
  */
33
34
  export declare function analyzeScoreSyntax(source: string, functions?: ASTFunctionClass[]): {
34
- syntax: import("./index.js").SyntaxAnalysis;
35
- diagnostics: import("./diagnostic.js").Diagnostic[];
35
+ syntax: import("./core.js").SyntaxAnalysis;
36
+ diagnostics: Diagnostic[];
36
37
  };
package/dist/pipeline.js CHANGED
@@ -14,11 +14,9 @@ import { preprocessSource } from "./parser/preprocess.js";
14
14
  * 任意 Painter 后端可以直接消费 layout
15
15
  */
16
16
  export function compileScore(source, options = {}) {
17
- const { functions = defaultFunctions, textMeasurer, fontSize, ...layoutOptions } = options;
17
+ const { functions = defaultFunctions, textMeasurer, variables, ...layoutOptions } = options;
18
18
  const { maskedSource, lineStarts } = preprocessSource(source);
19
- const parser = new ParserContext({ source: maskedSource });
20
- if (fontSize)
21
- parser.fontSize = fontSize;
19
+ const parser = new ParserContext({ source: maskedSource, variables });
22
20
  parser.registerFunctions(functions);
23
21
  const ast = new ASTBraceNode({ start: 0, end: source.length }, parser.parse());
24
22
  const loweringContext = new LoweringContext(parser.diagnostics);
@@ -28,7 +26,8 @@ export function compileScore(source, options = {}) {
28
26
  const layout = layoutDocument(lowering, layoutContext, layoutOptions);
29
27
  return {
30
28
  lineStarts,
31
- parser,
29
+ maskedSource,
30
+ diagnostics: parser.diagnostics,
32
31
  ast,
33
32
  lowering,
34
33
  layout,
@@ -8,7 +8,7 @@ import type { PlaybackPlan } from "./types.js";
8
8
  * - [state] Temporal.playbackState:每次实际访问节点时,把 lowering 已固化的 BPM 登记到演奏轴;note、tempo 和正时值 dash 都用它恢复记谱位置的速度
9
9
  * - [hook] Temporal.emitPlayback:按展开后的列序逐次调用;note 登记 NoteOn/NoteOff,up/grace 通过 emitter.play 递归登记折叠成员
10
10
  * - [API] PlaybackEmitter.control:emit 时只登记控制;所有节点访问完成后按演奏时刻执行,同刻合并后生成 Tempo;fermata 用它修改 bpmScale
11
- * - [API] PlaybackEmitter.affectFollowing:把 transform 加入当前 play frame;后续目标音完整登记 NoteOn/NoteOff 后,将冻结的 transform 紧接着写入顺序流;accent、tr、mordent 使用它
11
+ * - [API] PlaybackEmitter.affectFollowing:把 transform 加入当前 play frame;后续目标音完整登记 NoteOn/NoteOff 后,将冻结的 transform 紧接着写入顺序流;accent、tr、波音使用它
12
12
  * - [API] PlaybackEmitter.defer:把 hook 写在当前节点之后;状态扫描完成后重放顺序流,走到该位置才执行,可见完整 Tempo 和此前音符;dash 用它延长前一组 NoteOff
13
13
  * - [hook] PlaybackRelation.applyPlayback:顺序流重放完并首次排序后执行,可观察和改写完整事件计划;tie 用它合并相距很远的端点
14
14
  * - comparePlaybackDraftEvents / finalizePlaybackEvents:最后稳定排序,再校验 NoteOn/NoteOff 配对并剥离 origins、order 等编译期字段
@@ -1,6 +1,6 @@
1
1
  import { ErrorDiagnostic, WarningDiagnostic } from "../diagnostic.js";
2
2
  import { Fraction } from "../fraction.js";
3
- import { DEFAULT_BPM } from "../lowering/types.js";
3
+ import { DEFAULT_BPM } from "../functions/temporal.js";
4
4
  import { comparePlaybackDraftEvents, finalizePlaybackEvents } from "./event.js";
5
5
  import { performanceTimeToSeconds } from "./time.js";
6
6
  import { isPlaybackRelation } from "./types.js";
@@ -142,7 +142,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
142
142
  * - [state] Temporal.playbackState:每次实际访问节点时,把 lowering 已固化的 BPM 登记到演奏轴;note、tempo 和正时值 dash 都用它恢复记谱位置的速度
143
143
  * - [hook] Temporal.emitPlayback:按展开后的列序逐次调用;note 登记 NoteOn/NoteOff,up/grace 通过 emitter.play 递归登记折叠成员
144
144
  * - [API] PlaybackEmitter.control:emit 时只登记控制;所有节点访问完成后按演奏时刻执行,同刻合并后生成 Tempo;fermata 用它修改 bpmScale
145
- * - [API] PlaybackEmitter.affectFollowing:把 transform 加入当前 play frame;后续目标音完整登记 NoteOn/NoteOff 后,将冻结的 transform 紧接着写入顺序流;accent、tr、mordent 使用它
145
+ * - [API] PlaybackEmitter.affectFollowing:把 transform 加入当前 play frame;后续目标音完整登记 NoteOn/NoteOff 后,将冻结的 transform 紧接着写入顺序流;accent、tr、波音使用它
146
146
  * - [API] PlaybackEmitter.defer:把 hook 写在当前节点之后;状态扫描完成后重放顺序流,走到该位置才执行,可见完整 Tempo 和此前音符;dash 用它延长前一组 NoteOff
147
147
  * - [hook] PlaybackRelation.applyPlayback:顺序流重放完并首次排序后执行,可观察和改写完整事件计划;tie 用它合并相距很远的端点
148
148
  * - comparePlaybackDraftEvents / finalizePlaybackEvents:最后稳定排序,再校验 NoteOn/NoteOff 配对并剥离 origins、order 等编译期字段
@@ -155,6 +155,7 @@ export function compilePlayback(lowering, options) {
155
155
  const diagnostics = [];
156
156
  const events = []; // 状态扫描先写 Tempo,顺序流再追加音符
157
157
  const sequence = [];
158
+ const activePrograms = new Map();
158
159
  // 同刻稳定次序与 NoteOn/NoteOff 配对各用独立的单调序号
159
160
  let nextEventOrder = 0;
160
161
  let nextId = 0;
@@ -183,6 +184,18 @@ export function compilePlayback(lowering, options) {
183
184
  // 同一个 Temporal 在反复中会走到这里多次;每次创建独立 origin 对象区分访问实例
184
185
  const origin = { node };
185
186
  const lineage = [...ancestors, origin]; // 来源链
187
+ const program = node.playbackState?.program;
188
+ if (program !== undefined && activePrograms.get(node.track) !== program) {
189
+ activePrograms.set(node.track, program);
190
+ sequence.push({
191
+ kind: "program-change",
192
+ at: start.clone(),
193
+ order: nextEventOrder++,
194
+ origins: [...lineage],
195
+ track: node.track,
196
+ program,
197
+ });
198
+ }
186
199
  // 每个实际访问到的 Temporal 把自己的记谱状态同步到演奏轴
187
200
  // 目前是无条件覆盖
188
201
  if (node.playbackState) {
@@ -1,6 +1,6 @@
1
1
  import type { Fraction } from "../fraction.js";
2
2
  import type { Track } from "../lowering/track.js";
3
- import type { TemporalNodeBase } from "../lowering/types.js";
3
+ import type { TemporalNodeBase } from "../functions/temporal.js";
4
4
  import type { SourceSpan } from "../parser/types.js";
5
5
  export type PlaybackNoteId = number;
6
6
  /** 最终可直接交给 MIDI 适配器的系统事件 */
@@ -15,6 +15,12 @@ export interface PlaybackTimeSignatureEvent {
15
15
  readonly numerator: number;
16
16
  readonly denominator: number;
17
17
  }
18
+ export interface PlaybackProgramChangeEvent {
19
+ readonly kind: "program-change";
20
+ readonly at: Fraction;
21
+ readonly track: number;
22
+ readonly program: number;
23
+ }
18
24
  export interface PlaybackNoteOnEvent {
19
25
  readonly kind: "note-on";
20
26
  readonly at: Fraction;
@@ -22,6 +28,7 @@ export interface PlaybackNoteOnEvent {
22
28
  readonly track: number;
23
29
  readonly midi: number;
24
30
  readonly velocity: number;
31
+ readonly percussion?: true;
25
32
  readonly sourceSpans: readonly SourceSpan[];
26
33
  }
27
34
  export interface PlaybackNoteOffEvent {
@@ -31,7 +38,7 @@ export interface PlaybackNoteOffEvent {
31
38
  readonly track: number;
32
39
  readonly midi: number;
33
40
  }
34
- export type PlaybackEvent = PlaybackTempoEvent | PlaybackTimeSignatureEvent | PlaybackNoteOnEvent | PlaybackNoteOffEvent;
41
+ export type PlaybackEvent = PlaybackTempoEvent | PlaybackTimeSignatureEvent | PlaybackProgramChangeEvent | PlaybackNoteOnEvent | PlaybackNoteOffEvent;
35
42
  /** 一次 `play(node)` 访问;对象身份区分同一节点在反复中的不同访问 */
36
43
  export interface PlaybackOrigin {
37
44
  readonly node: TemporalNodeBase;
@@ -48,6 +55,7 @@ export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
48
55
  track: Track;
49
56
  midi: number;
50
57
  velocity: number;
58
+ percussion?: true;
51
59
  transpose?: (steps: number) => number;
52
60
  sourceSpans: SourceSpan[];
53
61
  }
@@ -64,13 +72,19 @@ export interface PlaybackDraftTimeSignatureEvent extends PlaybackDraftEventBase
64
72
  numerator: number;
65
73
  denominator: number;
66
74
  }
67
- export type PlaybackDraftEvent = PlaybackDraftNoteOnEvent | PlaybackDraftNoteOffEvent | PlaybackDraftTempoEvent | PlaybackDraftTimeSignatureEvent;
75
+ export interface PlaybackDraftProgramChangeEvent extends PlaybackDraftEventBase {
76
+ kind: "program-change";
77
+ track: Track;
78
+ program: number;
79
+ }
80
+ export type PlaybackDraftEvent = PlaybackDraftNoteOnEvent | PlaybackDraftNoteOffEvent | PlaybackDraftTempoEvent | PlaybackDraftTimeSignatureEvent | PlaybackDraftProgramChangeEvent;
68
81
  export type PlaybackEventInput = {
69
82
  kind: "note-on";
70
83
  at: Fraction;
71
84
  noteId: PlaybackNoteId;
72
85
  midi: number;
73
86
  velocity: number;
87
+ percussion?: true;
74
88
  transpose?: (steps: number) => number;
75
89
  } | {
76
90
  kind: "note-off";