jpfun 0.2.0 → 0.3.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 (112) hide show
  1. package/README.md +69 -11
  2. package/dist/diagnostic.js +5 -2
  3. package/dist/fraction.d.ts +24 -0
  4. package/dist/fraction.js +132 -0
  5. package/dist/functions/ASTtypes.d.ts +24 -7
  6. package/dist/functions/ASTtypes.js +35 -16
  7. package/dist/functions/adjust/index.d.ts +2 -0
  8. package/dist/functions/adjust/index.js +193 -0
  9. package/dist/functions/bar/index.d.ts +8 -0
  10. package/dist/functions/bar/index.js +39 -10
  11. package/dist/functions/beam/auto.js +32 -15
  12. package/dist/functions/beam/index.js +10 -6
  13. package/dist/functions/beam/layout.d.ts +3 -2
  14. package/dist/functions/beam/layout.js +42 -64
  15. package/dist/functions/box/index.js +35 -34
  16. package/dist/functions/br/index.js +9 -7
  17. package/dist/functions/dash/index.js +33 -1
  18. package/dist/functions/default.js +14 -7
  19. package/dist/functions/div/index.d.ts +16 -0
  20. package/dist/functions/div/index.js +45 -17
  21. package/dist/functions/dot/index.js +11 -3
  22. package/dist/functions/grace/index.d.ts +8 -11
  23. package/dist/functions/grace/index.js +82 -76
  24. package/dist/functions/head/index.d.ts +2 -0
  25. package/dist/functions/head/index.js +492 -0
  26. package/dist/functions/key/index.js +97 -3
  27. package/dist/functions/meter/index.d.ts +2 -0
  28. package/dist/functions/meter/index.js +154 -0
  29. package/dist/functions/note/accidentals.d.ts +24 -3
  30. package/dist/functions/note/accidentals.js +31 -1
  31. package/dist/functions/note/index.js +45 -65
  32. package/dist/functions/page/index.d.ts +9 -2
  33. package/dist/functions/page/index.js +50 -4
  34. package/dist/functions/set/index.js +37 -29
  35. package/dist/functions/stack/index.js +26 -22
  36. package/dist/functions/symbol/index.d.ts +21 -0
  37. package/dist/functions/symbol/index.js +94 -0
  38. package/dist/functions/symbol/ornament.d.ts +15 -0
  39. package/dist/functions/symbol/ornament.js +73 -0
  40. package/dist/functions/symbol/shape.d.ts +22 -0
  41. package/dist/functions/symbol/shape.js +48 -0
  42. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  43. package/dist/functions/symbol/symbols/accent.js +24 -0
  44. package/dist/functions/symbol/symbols/f.d.ts +2 -0
  45. package/dist/functions/symbol/symbols/f.js +55 -0
  46. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  47. package/dist/functions/symbol/symbols/fermata.js +24 -0
  48. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  49. package/dist/functions/symbol/symbols/mordent.js +43 -0
  50. package/dist/functions/symbol/symbols/p.d.ts +2 -0
  51. package/dist/functions/symbol/symbols/p.js +61 -0
  52. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  53. package/dist/functions/symbol/symbols/tr.js +75 -0
  54. package/dist/functions/tempo/glyph.d.ts +12 -0
  55. package/dist/functions/tempo/glyph.js +30 -0
  56. package/dist/functions/tempo/index.js +53 -2
  57. package/dist/functions/text/index.js +76 -24
  58. package/dist/functions/tie/index.js +102 -127
  59. package/dist/functions/tuplet/index.d.ts +2 -0
  60. package/dist/functions/tuplet/index.js +211 -0
  61. package/dist/functions/up/index.d.ts +1 -0
  62. package/dist/functions/up/index.js +245 -171
  63. package/dist/functions/voice/index.js +86 -68
  64. package/dist/functions/volta/index.d.ts +2 -0
  65. package/dist/functions/volta/index.js +227 -0
  66. package/dist/index.d.ts +4 -0
  67. package/dist/index.js +4 -0
  68. package/dist/jpfun.min.js +143 -0
  69. package/dist/layout/engine.d.ts +4 -11
  70. package/dist/layout/engine.js +65 -59
  71. package/dist/layout/model.d.ts +8 -1
  72. package/dist/layout/model.js +16 -6
  73. package/dist/layout/path.d.ts +19 -0
  74. package/dist/layout/path.js +101 -0
  75. package/dist/layout/types.d.ts +51 -18
  76. package/dist/layout/types.js +3 -1
  77. package/dist/lowering/loweringContext.d.ts +18 -20
  78. package/dist/lowering/loweringContext.js +132 -94
  79. package/dist/lowering/track.d.ts +1 -1
  80. package/dist/lowering/track.js +1 -1
  81. package/dist/lowering/types.d.ts +49 -12
  82. package/dist/lowering/types.js +9 -3
  83. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  84. package/dist/parser/parse-utils/call-utils.js +0 -6
  85. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  86. package/dist/parser/parse-utils/note-utils.js +35 -13
  87. package/dist/parser/parse-utils/string-utils.d.ts +8 -0
  88. package/dist/parser/parse-utils/string-utils.js +20 -0
  89. package/dist/parser/parserContext.d.ts +8 -5
  90. package/dist/parser/parserContext.js +38 -33
  91. package/dist/parser/preprocess.js +17 -11
  92. package/dist/playback/compile.d.ts +18 -0
  93. package/dist/playback/compile.js +401 -0
  94. package/dist/playback/event.d.ts +91 -0
  95. package/dist/playback/event.js +87 -0
  96. package/dist/playback/time.d.ts +14 -0
  97. package/dist/playback/time.js +81 -0
  98. package/dist/playback/types.d.ts +128 -0
  99. package/dist/playback/types.js +3 -0
  100. package/dist/render/canvas.d.ts +4 -4
  101. package/dist/render/canvas.js +20 -5
  102. package/dist/render/index.d.ts +1 -0
  103. package/dist/render/index.js +1 -0
  104. package/dist/render/paint.d.ts +8 -0
  105. package/dist/render/paint.js +101 -0
  106. package/dist/render/svg.d.ts +3 -3
  107. package/dist/render/svg.js +10 -8
  108. package/dist/render/text.d.ts +17 -0
  109. package/dist/render/text.js +35 -0
  110. package/dist/render/types.d.ts +1 -1
  111. package/grammar.md +93 -10
  112. package/package.json +10 -6
package/README.md CHANGED
@@ -6,9 +6,9 @@ jpFun compiles a compact numbered-notation DSL into a reusable document layout t
6
6
 
7
7
  ## Features
8
8
 
9
- - Concise DSL with function-based extensibility
10
- - Numbered notes, rests, chords, lyrics, voices, grace notes, ties, and beams
11
- - Automatic spacing, line breaking, and pagination
9
+ - Compact DSL with syntax sugar and function-based extensibility
10
+ - Exact rational timing and composable score structures
11
+ - Automatic spacing, explicit system breaks, and page-aware pagination
12
12
  - Shared layout model for SVG and Canvas rendering
13
13
  - Structured diagnostics and source locations
14
14
  - Zero runtime dependencies
@@ -28,10 +28,32 @@ import { compileScore } from "jpfun";
28
28
 
29
29
  CommonJS `require("jpfun")` is not supported.
30
30
 
31
+ ## Browser via CDN
32
+
33
+ A bundled, minified build ships with the package, so no build step is needed for a plain web page. Load it with a `<script>` tag and use the `jpfun` global:
34
+
35
+ ```html
36
+ <script src="https://unpkg.com/jpfun"></script>
37
+ <script>
38
+ const { compileScore, renderLayoutPagesToSvg } = jpfun;
39
+ document.body.innerHTML = renderLayoutPagesToSvg(compileScore("1 2 3 | 4 -").layout)[0];
40
+ </script>
41
+ ```
42
+
43
+ For ES modules, jsDelivr bundles the package on the fly:
44
+
45
+ ```html
46
+ <script type="module">
47
+ import { compileScore } from "https://cdn.jsdelivr.net/npm/jpfun/+esm";
48
+ </script>
49
+ ```
50
+
51
+ Both URLs resolve to the latest published version. In production, append an exact version (`jpfun@x.y.z`) so that publishing a new release cannot change an existing page.
52
+
31
53
  ## Quick Start
32
54
 
33
55
  ```ts
34
- import { compileScore, renderLayoutToSvg } from "jpfun";
56
+ import { compileScore, renderLayoutPagesToSvg } from "jpfun";
35
57
 
36
58
  const source = `
37
59
  @1(C4)
@@ -41,25 +63,40 @@ const source = `
41
63
  `;
42
64
 
43
65
  const result = compileScore(source);
44
- const svg = renderLayoutToSvg(result.layout);
66
+ const pages = renderLayoutPagesToSvg(result.layout);
45
67
  ```
46
68
 
47
- `renderLayoutToSvg` returns an SVG string that can be written to a file, sent in an HTTP response, or inserted into a browser page.
69
+ `renderLayoutPagesToSvg` returns one SVG string per page. Even an infinite-height document produces one natural-height page. Each SVG can be written to a file, sent in an HTTP response, or inserted into a browser page.
48
70
 
49
71
  ## Canvas Rendering
50
72
 
51
73
  ```ts
52
- import { compileScore, renderLayoutToCanvas } from "jpfun";
74
+ import { compileScore, renderLayoutPagesToCanvas } from "jpfun";
53
75
 
54
76
  const result = compileScore("1 2 3 | 4");
55
77
  const canvas = document.querySelector("canvas");
56
78
  const context = canvas.getContext("2d");
57
79
 
58
80
  if (context) {
59
- renderLayoutToCanvas(result.layout, context);
81
+ renderLayoutPagesToCanvas(result.layout, [context]);
60
82
  }
61
83
  ```
62
84
 
85
+ ## Text Measurement
86
+
87
+ Layout depends on text widths, so `compileScore` needs a `TextMeasurer`. The default one estimates every character at a fixed fraction of the font size. That keeps results platform-independent, which is what tests and server-side rendering want, but it does not match the real glyph widths of a browser font — narrow letters are overestimated, so right-aligned text and `@box` bounds drift visibly.
88
+
89
+ In a browser, pass `CanvasTextMeasurer` so that measurement agrees with what the renderer draws:
90
+
91
+ ```ts
92
+ import { compileScore, CanvasTextMeasurer } from "jpfun";
93
+
94
+ const context = document.createElement("canvas").getContext("2d")!;
95
+ const result = compileScore(source, { textMeasurer: new CanvasTextMeasurer(context) });
96
+ ```
97
+
98
+ This applies to SVG output too, since measurement happens during layout rather than during painting. The context is only used for measuring and need not be the canvas you render into.
99
+
63
100
  ## Compilation Pipeline
64
101
 
65
102
  jpFun exposes the intermediate results of its compilation pipeline:
@@ -68,8 +105,9 @@ jpFun exposes the intermediate results of its compilation pipeline:
68
105
  Source
69
106
  -> Parser -> AST
70
107
  -> Lowering -> timed events and relations
71
- -> Layout -> document geometry
72
- -> Renderer -> SVG or Canvas
108
+ |-> Playback -> NoteOn / NoteOff / Tempo events
109
+ `-> Layout -> document geometry
110
+ -> Renderer -> SVG or Canvas
73
111
  ```
74
112
 
75
113
  ```ts
@@ -81,7 +119,27 @@ result.lowering;
81
119
  result.layout;
82
120
  ```
83
121
 
84
- This makes it possible to build editors, diagnostics, playback tools, and custom renderers on top of the same compilation result.
122
+ Playback is compiled independently from layout:
123
+
124
+ ```ts
125
+ import { compilePlayback } from "jpfun";
126
+
127
+ const playback = compilePlayback(result.lowering);
128
+ playback.events;
129
+ playback.scoreMap;
130
+ playback.tracks;
131
+ playback.durationSeconds;
132
+ ```
133
+
134
+ For scores with unusually large repeat expansion, raise the control-flow budget explicitly:
135
+
136
+ ```ts
137
+ const playback = compilePlayback(result.lowering, { maxFlowSteps: 200_000 });
138
+ ```
139
+
140
+ The default is 65,536 visited columns. Exceeding it throws instead of returning a partial playback plan.
141
+
142
+ The plan stores device-independent `note-on`, `note-off`, and `tempo` events. Its track number is the same channel identity used by the visual Track; Web Audio, Web MIDI, and Standard MIDI File adapters consume that identity and the exact `Fraction` timestamps at their boundary.
85
143
 
86
144
  ## Syntax Example
87
145
 
@@ -132,8 +132,11 @@ Diagnostic.warning = {
132
132
  LabelWithoutTarget: (labelName, span) => {
133
133
  return new WarningDiagnostic("W_LABEL_WITHOUT_TARGET", `标签 "${labelName}" 没有可绑定的目标;标签将被忽略`, span);
134
134
  },
135
- LabelAlreadyExists: (newLabel, oldLabel, span) => {
136
- return new WarningDiagnostic("W_LABEL_ALREADY_EXISTS", `标签 "${newLabel}" 已经存在(为 "${oldLabel}");新标签将覆盖旧标签`, span);
135
+ TargetAlreadyLabeled: (newLabel, oldLabel, span) => {
136
+ return new WarningDiagnostic("W_TARGET_ALREADY_LABELED", `目标已标注为 "${oldLabel}","${newLabel}" 将被忽略`, span);
137
+ },
138
+ UnresolvedEndpoint: (functionName, span) => {
139
+ return new WarningDiagnostic("W_UNRESOLVED_ENDPOINT", `@${functionName} 有端点找不到对应的谱面对象;该关系将被忽略`, span);
137
140
  },
138
141
  ZeroTimeTrack: (span, trackOrder) => {
139
142
  return new WarningDiagnostic("W_ZERO_TIME_TRACK", `第${trackOrder}个子轨道的时长为0`, span);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 分数类
3
+ * 为了性能没有做过多的类型检查,使用时请确保传入的参数是整数
4
+ */
5
+ export declare class Fraction {
6
+ private _numerator;
7
+ private _denominator;
8
+ constructor(numerator?: number, denominator?: number);
9
+ get numerator(): number;
10
+ get denominator(): number;
11
+ set(numerator: number, denominator?: number): this;
12
+ copyFrom(other: Fraction): this;
13
+ clone(): Fraction;
14
+ add(value: Fraction | number, denominator?: number): this;
15
+ sub(value: Fraction | number, denominator?: number): this;
16
+ mul(value: Fraction | number, denominator?: number): this;
17
+ div(value: Fraction | number, denominator?: number): this;
18
+ divPow2(power?: number): this;
19
+ compare(value: Fraction | number, denominator?: number): number;
20
+ equals(value: Fraction | number, denominator?: number): boolean;
21
+ isZero(): boolean;
22
+ toNumber(): number;
23
+ toString(): string;
24
+ }
@@ -0,0 +1,132 @@
1
+ // 认为输入为正数
2
+ function gcd(a, b) {
3
+ while (b !== 0) {
4
+ const r = a % b;
5
+ a = b;
6
+ b = r;
7
+ }
8
+ return a;
9
+ }
10
+ /**
11
+ * 分数类
12
+ * 为了性能没有做过多的类型检查,使用时请确保传入的参数是整数
13
+ */
14
+ export class Fraction {
15
+ _numerator = 0;
16
+ _denominator = 1;
17
+ constructor(numerator = 0, denominator = 1) {
18
+ this.set(numerator, denominator);
19
+ }
20
+ get numerator() {
21
+ return this._numerator;
22
+ }
23
+ get denominator() {
24
+ return this._denominator;
25
+ }
26
+ set(numerator, denominator = 1) {
27
+ if (denominator === 0)
28
+ throw new RangeError("Denominator must not be zero");
29
+ if (denominator < 0) {
30
+ numerator = -numerator;
31
+ denominator = -denominator;
32
+ }
33
+ const divisor = gcd(Math.abs(numerator), denominator);
34
+ this._numerator = numerator / divisor;
35
+ this._denominator = denominator / divisor;
36
+ return this;
37
+ }
38
+ copyFrom(other) {
39
+ this._numerator = other._numerator;
40
+ this._denominator = other._denominator;
41
+ return this;
42
+ }
43
+ clone() {
44
+ return new Fraction(this._numerator, this._denominator);
45
+ }
46
+ add(value, denominator = 1) {
47
+ let numerator;
48
+ if (typeof value === "number") {
49
+ numerator = value;
50
+ }
51
+ else {
52
+ numerator = value._numerator;
53
+ denominator = value._denominator;
54
+ }
55
+ return this.set(this._numerator * denominator + numerator * this._denominator, this._denominator * denominator);
56
+ }
57
+ sub(value, denominator = 1) {
58
+ let numerator;
59
+ if (typeof value === "number") {
60
+ numerator = value;
61
+ }
62
+ else {
63
+ numerator = value._numerator;
64
+ denominator = value._denominator;
65
+ }
66
+ return this.set(this._numerator * denominator - numerator * this._denominator, this._denominator * denominator);
67
+ }
68
+ mul(value, denominator = 1) {
69
+ let numerator;
70
+ if (typeof value === "number") {
71
+ numerator = value;
72
+ }
73
+ else {
74
+ numerator = value._numerator;
75
+ denominator = value._denominator;
76
+ }
77
+ return this.set(this._numerator * numerator, this._denominator * denominator);
78
+ }
79
+ div(value, denominator = 1) {
80
+ let numerator;
81
+ if (typeof value === "number") {
82
+ numerator = value;
83
+ }
84
+ else {
85
+ numerator = value._numerator;
86
+ denominator = value._denominator;
87
+ }
88
+ if (numerator === 0)
89
+ throw new RangeError("Cannot divide by zero");
90
+ return this.set(this._numerator * denominator, this._denominator * numerator);
91
+ }
92
+ divPow2(power = 1) {
93
+ if (this._numerator === 0)
94
+ return this;
95
+ while (power > 0 && this._numerator % 2 === 0) {
96
+ this._numerator /= 2;
97
+ power--;
98
+ }
99
+ this._denominator *= 2 ** power;
100
+ return this;
101
+ }
102
+ compare(value, denominator = 1) {
103
+ let numerator;
104
+ if (typeof value === "number") {
105
+ numerator = value;
106
+ }
107
+ else {
108
+ numerator = value._numerator;
109
+ denominator = value._denominator;
110
+ }
111
+ const difference = this._numerator * denominator - numerator * this._denominator;
112
+ return difference < 0 ? -1 : difference > 0 ? 1 : 0;
113
+ }
114
+ equals(value, denominator = 1) {
115
+ if (value instanceof Fraction) {
116
+ return this._numerator === value._numerator
117
+ && this._denominator === value._denominator;
118
+ }
119
+ return this._numerator * denominator === value * this._denominator;
120
+ }
121
+ isZero() {
122
+ return this._numerator === 0;
123
+ }
124
+ toNumber() {
125
+ return this._numerator / this._denominator;
126
+ }
127
+ toString() {
128
+ return this._denominator === 1
129
+ ? String(this._numerator)
130
+ : `${this._numerator}/${this._denominator}`;
131
+ }
132
+ }
@@ -1,5 +1,7 @@
1
1
  import type { SourceSpan, LengthValue, deSugarAtomFunction, deSugarRelationFunction } from "../parser/types.js";
2
+ import type { CallArgumentInfo } from "../parser/grammarType.js";
2
3
  import type { ParserContext } from "../parser/parserContext.js";
4
+ import type { Fraction } from "../fraction.js";
3
5
  import type { LoweringAugmenter, LoweringFinalizer, TemporalNodeBase, TimeFlowModel } from "../lowering/types.js";
4
6
  import type { LoweringContext } from "../lowering/loweringContext.js";
5
7
  import type { Track } from "../lowering/track.js";
@@ -13,13 +15,14 @@ export declare class ASTNodeBase {
13
15
  sourceSpan: SourceSpan;
14
16
  parent: ASTNodeBase | null;
15
17
  get children(): ASTNodeBase[] | null;
16
- constructor(sourceSpan: SourceSpan, parent?: ASTNodeBase | null);
18
+ constructor(sourceSpan: SourceSpan, // 源码区间
19
+ parent?: ASTNodeBase | null);
17
20
  /**
18
21
  * lowering 固化后的 attachment 生成钩子
19
22
  *
20
23
  * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
21
24
  * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
22
- * 该 hook 读取 LoweringResult 并返回新建的 LayoutAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
25
+ * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
23
26
  *
24
27
  * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
25
28
  */
@@ -50,15 +53,20 @@ export declare class ASTNodeBase {
50
53
  timeFlowModel(): TimeFlowModel | null;
51
54
  /**
52
55
  * 离开当前层级的回调 同 loweringEnter
56
+ *
57
+ * timeOffset 是 children 展开后的当前时间游标。
58
+ * 只有在同步重写本节点已经产生的 Temporal.t/T 时才可原地修改它,避免事件时间与后继事件起点不一致。
53
59
  */
54
- loweringExit(_ctx: LoweringContext, _track: Track): Iterable<TemporalNodeBase>;
60
+ loweringExit(_ctx: LoweringContext, _track: Track, _timeOffset: Fraction): Iterable<TemporalNodeBase>;
55
61
  toString(source: string): string;
56
62
  }
57
63
  export declare class ASTTextNode extends ASTNodeBase {
58
64
  }
59
65
  export declare class ASTLabelNode extends ASTNodeBase {
60
66
  label: string;
61
- constructor(sourceSpan: SourceSpan, label: string, parent: ASTNodeBase);
67
+ /** 被标注的节点。parent 是树结构、会被容器改写,不能用来表达这层关系 */
68
+ readonly target: ASTNodeBase;
69
+ constructor(sourceSpan: SourceSpan, label: string, target: ASTNodeBase, parent?: ASTNodeBase | null);
62
70
  toString(_: string): string;
63
71
  }
64
72
  export declare class ASTBraceNode extends ASTNodeBase {
@@ -89,12 +97,14 @@ export interface FunctionDef {
89
97
  }
90
98
  /** 参数名 -> 类型的规则:命名参数只认 def.args,位置参数可回落到 extraArgType */
91
99
  export declare function resolveArgType(def: FunctionDef, name: string | undefined, index: number): paramType | undefined;
92
- export type FunctionArgs = Map<string | number, paramValue | SourceSpan>;
100
+ /** 别名里的第一个是主名;`@set` 的 key 和 `getArgValue` 的前缀必须用同一个 */
101
+ export declare function primaryName(def: FunctionDef): string;
102
+ export type FunctionArgs = Map<string | number, paramValue | CallArgumentInfo>;
93
103
  export declare class ASTFunctionNode extends ASTNodeBase {
94
104
  /**
95
- * 返回真正承载标签的 AST 节点,null 表示不可被标注
105
+ * 不实现 = 对标签透明,绑定继续向前找;返回 null = 边界,绑定到此为止;返回节点 = 标签承载者
96
106
  */
97
- labelable(): ASTFunctionNode | null;
107
+ labelable?(): ASTFunctionNode | null;
98
108
  label?: string;
99
109
  static def?: FunctionDef;
100
110
  get def(): FunctionDef | undefined;
@@ -105,6 +115,13 @@ export declare class ASTFunctionNode extends ASTNodeBase {
105
115
  get deSugarRelation(): deSugarRelationFunction;
106
116
  getArgValue(args: FunctionArgs, ctx: ParserContext): paramValue[];
107
117
  toString(source: string): string;
118
+ /**
119
+ * 在子树里找标签承载者
120
+ * 未实现 labelable = 透明,继续下潜;实现了就采信它的返回值,null 即拒绝,不再往里找。
121
+ * 拒绝时别退回去遍历 children —— grace 的 labelable() 内部已经走过整棵子树
122
+ * 只有函数节点声明 labelable,别的节点读到的必是 undefined,所以无需 instanceof
123
+ */
124
+ static findLabelable(node: ASTNodeBase): ASTFunctionNode | null;
108
125
  /**
109
126
  * 用于语法糖向前结合
110
127
  * 一般向前结合都是寻找brace或者function
@@ -4,11 +4,12 @@ export function functionAddonKey(name) {
4
4
  return `@${name}`;
5
5
  }
6
6
  export class ASTNodeBase {
7
- sourceSpan; // 和源码的映射
7
+ sourceSpan;
8
8
  parent;
9
9
  // 空数组表示应该有 null表示自己就是叶子 和 timeFlowMode 的默认实现对应
10
10
  get children() { return null; }
11
- constructor(sourceSpan, parent = null) {
11
+ constructor(sourceSpan, // 源码区间
12
+ parent = null) {
12
13
  this.sourceSpan = sourceSpan;
13
14
  this.parent = parent;
14
15
  }
@@ -17,7 +18,7 @@ export class ASTNodeBase {
17
18
  *
18
19
  * 普通 loweringEnter/loweringExit 在递归遍历 AST 时执行,
19
20
  * 此时尚未完成锚点归并,事件的 t、track 和 layoutLine 不可用,因此需要观察完整事件流的功能不能在普通 hook 中可靠决定分组。
20
- * 该 hook 读取 LoweringResult 并返回新建的 LayoutAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
21
+ * 该 hook 读取 LoweringResult 并返回新建的 LoweringAttachment,LoweringContext 将返回值追加到当前文档或 fragment 的 attachments,不会把它们放入时间列或推进时间。
21
22
  *
22
23
  * 例:autobeam 扫描最终列,按轨道、谱面行、拍点和显式 beam 端点决定分组,再生成 BeamLayoutAttachment
23
24
  */
@@ -50,8 +51,11 @@ export class ASTNodeBase {
50
51
  timeFlowModel() { return null; }
51
52
  /**
52
53
  * 离开当前层级的回调 同 loweringEnter
54
+ *
55
+ * timeOffset 是 children 展开后的当前时间游标。
56
+ * 只有在同步重写本节点已经产生的 Temporal.t/T 时才可原地修改它,避免事件时间与后继事件起点不一致。
53
57
  */
54
- loweringExit(_ctx, _track) {
58
+ loweringExit(_ctx, _track, _timeOffset) {
55
59
  return [];
56
60
  }
57
61
  // 去糖后文本输出
@@ -66,10 +70,12 @@ export class ASTTextNode extends ASTNodeBase {
66
70
  // 主要用途是高亮等编辑器功能
67
71
  export class ASTLabelNode extends ASTNodeBase {
68
72
  label;
69
- // parent 就是指向的节点
70
- constructor(sourceSpan, label, parent) {
73
+ /** 被标注的节点。parent 是树结构、会被容器改写,不能用来表达这层关系 */
74
+ target;
75
+ constructor(sourceSpan, label, target, parent = null) {
71
76
  super(sourceSpan, parent);
72
77
  this.label = label;
78
+ this.target = target;
73
79
  }
74
80
  toString(_) {
75
81
  return `@${this.label} `;
@@ -117,13 +123,13 @@ export function resolveArgType(def, name, index) {
117
123
  return def.args.find(arg => arg.name?.toLowerCase() === name)?.type;
118
124
  return def.args[index]?.type ?? (def.allowExtraArgs ? def.extraArgType : undefined);
119
125
  }
126
+ /** 别名里的第一个是主名;`@set` 的 key 和 `getArgValue` 的前缀必须用同一个 */
127
+ export function primaryName(def) {
128
+ return Array.isArray(def.name) ? def.name[0] : def.name;
129
+ }
120
130
  // 所有函数节点的基类,提供通用的参数提取方法和标签功能
121
131
  // 非正常函数则实例化该函数 特征是getDef为undefined
122
132
  export class ASTFunctionNode extends ASTNodeBase {
123
- /**
124
- * 返回真正承载标签的 AST 节点,null 表示不可被标注
125
- */
126
- labelable() { return null; }
127
133
  label; // 可选的标签名,只对 labelable() 选中的节点有效; 或者是label节点
128
134
  // 获取函数定义 对于未知函数,不定义def
129
135
  static def;
@@ -133,10 +139,7 @@ export class ASTFunctionNode extends ASTNodeBase {
133
139
  // 实例访问: new ().def 或 new ().constructor.def
134
140
  // 静态访问: 类名.def 或 类名.prototype.def
135
141
  get callName() {
136
- const names = this.def?.name;
137
- if (!names)
138
- return "";
139
- return Array.isArray(names) ? names[0] : names;
142
+ return this.def ? primaryName(this.def) : "";
140
143
  }
141
144
  // 去糖函数 详见 ParserContext 中 deSugarAtomFns 和 deSugarRelationFns 的定义
142
145
  static deSugarAtom = () => null; // 默认没有去糖,子类只需要定义static deSugarAtom方法即可
@@ -149,8 +152,7 @@ export class ASTFunctionNode extends ASTNodeBase {
149
152
  if (!def)
150
153
  return [];
151
154
  const defArgs = def.args;
152
- // 使用第一个名称作为前缀
153
- const prefix = Array.isArray(def.name) ? def.name[0] : def.name;
155
+ const prefix = primaryName(def);
154
156
  return defArgs.map((argDef, index) => {
155
157
  let argNameL = argDef.name ? argDef.name.toLowerCase() : null; // 统一小写处理
156
158
  // 先查询是否传递
@@ -169,6 +171,23 @@ export class ASTFunctionNode extends ASTNodeBase {
169
171
  return super.toString(source);
170
172
  return `@${name} `;
171
173
  }
174
+ /**
175
+ * 在子树里找标签承载者
176
+ * 未实现 labelable = 透明,继续下潜;实现了就采信它的返回值,null 即拒绝,不再往里找。
177
+ * 拒绝时别退回去遍历 children —— grace 的 labelable() 内部已经走过整棵子树
178
+ * 只有函数节点声明 labelable,别的节点读到的必是 undefined,所以无需 instanceof
179
+ */
180
+ static findLabelable(node) {
181
+ const self = node;
182
+ if (self.labelable)
183
+ return self.labelable();
184
+ for (const child of node.children ?? []) {
185
+ const target = ASTFunctionNode.findLabelable(child);
186
+ if (target)
187
+ return target;
188
+ }
189
+ return null;
190
+ }
172
191
  /**
173
192
  * 用于语法糖向前结合
174
193
  * 一般向前结合都是寻找brace或者function
@@ -0,0 +1,2 @@
1
+ import { ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const AdjustNode: ASTFunctionClass;