jpfun 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +1 -1
  2. package/dist/diagnostic.d.ts +1 -0
  3. package/dist/diagnostic.js +1 -0
  4. package/dist/functions/ASTtypes.d.ts +2 -3
  5. package/dist/functions/ASTtypes.js +2 -3
  6. package/dist/functions/adjust/index.js +15 -67
  7. package/dist/functions/bar/index.js +11 -7
  8. package/dist/functions/beam/auto.js +15 -11
  9. package/dist/functions/beam/layout.js +22 -48
  10. package/dist/functions/br/index.d.ts +9 -3
  11. package/dist/functions/br/index.js +20 -16
  12. package/dist/functions/dash/index.js +13 -11
  13. package/dist/functions/default.js +2 -1
  14. package/dist/functions/div/index.d.ts +2 -2
  15. package/dist/functions/div/index.js +5 -9
  16. package/dist/functions/dot/index.js +5 -9
  17. package/dist/functions/dyn/index.js +125 -53
  18. package/dist/functions/gliss/index.js +81 -7
  19. package/dist/functions/grace/index.d.ts +3 -10
  20. package/dist/functions/grace/index.js +25 -57
  21. package/dist/functions/head/index.js +6 -7
  22. package/dist/functions/key/index.js +1 -0
  23. package/dist/functions/meter/index.js +7 -5
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +162 -19
  26. package/dist/functions/note/source-transform.d.ts +8 -2
  27. package/dist/functions/note/source-transform.js +25 -11
  28. package/dist/functions/ottava/index.js +8 -7
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +11 -15
  31. package/dist/functions/pagebreak/index.js +2 -1
  32. package/dist/functions/rest/index.js +5 -5
  33. package/dist/functions/set/index.js +2 -2
  34. package/dist/functions/stack/index.js +7 -7
  35. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  36. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  37. package/dist/functions/tempo/index.js +8 -3
  38. package/dist/functions/temporal.d.ts +21 -6
  39. package/dist/functions/temporal.js +1 -1
  40. package/dist/functions/text/index.js +3 -5
  41. package/dist/functions/up/index.js +37 -34
  42. package/dist/functions/voice/connections.js +2 -2
  43. package/dist/functions/voice/lyrics.d.ts +2 -0
  44. package/dist/functions/voice/lyrics.js +4 -4
  45. package/dist/functions/voice/voice.d.ts +2 -1
  46. package/dist/functions/voice/voice.js +9 -15
  47. package/dist/functions/voice/voices.d.ts +6 -4
  48. package/dist/functions/voice/voices.js +10 -10
  49. package/dist/index.d.ts +6 -34
  50. package/dist/index.js +6 -34
  51. package/dist/jpfun.min.js +49 -46
  52. package/dist/layout/engine.js +237 -232
  53. package/dist/layout/model.d.ts +1 -1
  54. package/dist/layout/page.d.ts +2 -2
  55. package/dist/layout/page.js +8 -22
  56. package/dist/layout/types.d.ts +4 -5
  57. package/dist/lowering/accidentalMemory.d.ts +33 -0
  58. package/dist/lowering/accidentalMemory.js +84 -0
  59. package/dist/lowering/loweringContext.d.ts +12 -7
  60. package/dist/lowering/loweringContext.js +54 -51
  61. package/dist/lowering/types.d.ts +2 -3
  62. package/dist/parser/grammarType.d.ts +10 -4
  63. package/dist/parser/parse-utils/brace-utils.js +4 -3
  64. package/dist/parser/parse-utils/call-utils.js +7 -7
  65. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  66. package/dist/parser/parse-utils/string-utils.js +1 -1
  67. package/dist/parser/parserContext.d.ts +30 -34
  68. package/dist/parser/parserContext.js +77 -181
  69. package/dist/parser/preprocess.js +10 -23
  70. package/dist/parser/syntax.d.ts +9 -0
  71. package/dist/parser/syntax.js +109 -0
  72. package/dist/parser/types.d.ts +2 -1
  73. package/dist/pipeline.js +3 -2
  74. package/dist/playback/compile.js +26 -18
  75. package/dist/playback/event.d.ts +1 -2
  76. package/dist/playback/event.js +2 -3
  77. package/dist/playback/types.d.ts +0 -1
  78. package/dist/render/index.d.ts +1 -0
  79. package/dist/render/index.js +1 -0
  80. package/grammar.md +8 -6
  81. package/package.json +2 -2
  82. package/dist/functions/voice/index.d.ts +0 -2
  83. package/dist/functions/voice/index.js +0 -2
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 基于弹簧的有时长物体排版模型 原理参考 apps/docs/src/content/docs/docs/developer/layout.md
2
+ * 基于弹簧的有时长物体排版模型 原理参考 apps/docs/src/content/docs/docs/developer/layout-algorithm.mdx
3
3
  * 基本使用: 借助 layoutElement() 构建 LayoutElement[][],调用 layout() 函数进行排版
4
4
  */
5
5
  import type { HorizontalSpringConfig, LayoutBox, TimeLineEvent } from "./types.js";
@@ -21,9 +21,9 @@ export declare function normalizePageConfig(source?: Partial<PageConfig>): PageC
21
21
  /**
22
22
  * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
23
23
  * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
24
- * headrooms 按行号索引:每行顶部高出主旋律上沿(基线 - 半字高)的外扩高度,优先借用上一行下方的行距留白。
24
+ * gaps 按行号索引:该行完整盒与上一行完整盒之间的自然间距,缺省为 0;页首行忽略。
25
25
  */
26
- export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[], headrooms?: readonly number[]): {
26
+ export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[], gaps?: readonly number[]): {
27
27
  pages: DocumentLayoutPage[];
28
28
  lineTops: number[];
29
29
  };
@@ -19,8 +19,6 @@ export const DEFAULT_PAGE_CONFIG = {
19
19
  marginBottom: 48,
20
20
  marginLeft: 40,
21
21
  marginRight: 40,
22
- lineGap: 18,
23
- minLineGap: 7.2,
24
22
  fillRatio: 0.5,
25
23
  };
26
24
  /**
@@ -35,8 +33,6 @@ export function normalizePageConfig(source = {}) {
35
33
  marginBottom: Math.max(0, source.marginBottom ?? DEFAULT_PAGE_CONFIG.marginBottom),
36
34
  marginLeft: Math.max(0, source.marginLeft ?? DEFAULT_PAGE_CONFIG.marginLeft),
37
35
  marginRight: Math.max(0, source.marginRight ?? DEFAULT_PAGE_CONFIG.marginRight),
38
- lineGap: Math.max(0, source.lineGap ?? DEFAULT_PAGE_CONFIG.lineGap),
39
- minLineGap: Math.max(0, source.minLineGap ?? DEFAULT_PAGE_CONFIG.minLineGap),
40
36
  fillRatio: source.fillRatio ?? DEFAULT_PAGE_CONFIG.fillRatio,
41
37
  };
42
38
  if (!Number.isFinite(page.width) || page.width <= 0) {
@@ -45,16 +41,8 @@ export function normalizePageConfig(source = {}) {
45
41
  if (page.height !== Infinity && (!Number.isFinite(page.height) || page.height <= 0)) {
46
42
  throw new Error(`Page height must be positive or Infinity, got ${page.height}`);
47
43
  }
48
- const values = [
49
- page.marginTop,
50
- page.marginBottom,
51
- page.marginLeft,
52
- page.marginRight,
53
- page.lineGap,
54
- page.minLineGap,
55
- ];
56
- if (values.some(value => !Number.isFinite(value))) {
57
- throw new Error("Page margins and line gap must be finite non-negative numbers");
44
+ if (![page.marginTop, page.marginBottom, page.marginLeft, page.marginRight].every(Number.isFinite)) {
45
+ throw new Error("Page margins must be finite non-negative numbers");
58
46
  }
59
47
  const contentWidth = page.width - page.marginLeft - page.marginRight;
60
48
  if (contentWidth <= 0) {
@@ -69,12 +57,10 @@ export function normalizePageConfig(source = {}) {
69
57
  /**
70
58
  * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
71
59
  * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
72
- * headrooms 按行号索引:每行顶部高出主旋律上沿(基线 - 半字高)的外扩高度,优先借用上一行下方的行距留白。
60
+ * gaps 按行号索引:该行完整盒与上一行完整盒之间的自然间距,缺省为 0;页首行忽略。
73
61
  */
74
- export function paginateLayoutLines(heights, page, pageBreaks = [], headrooms = []) {
62
+ export function paginateLayoutLines(heights, page, pageBreaks = [], gaps = []) {
75
63
  const availableHeight = page.height - page.marginTop - page.marginBottom;
76
- const floor = Math.min(page.lineGap, page.minLineGap);
77
- const gapBefore = (line) => Math.max(page.lineGap - Math.max(0, headrooms[line] ?? 0), floor);
78
64
  const pages = [];
79
65
  const lineTops = new Array(heights.length).fill(0);
80
66
  let pageTop = 0;
@@ -88,7 +74,7 @@ export function paginateLayoutLines(heights, page, pageBreaks = [], headrooms =
88
74
  let lineTop = pageTop + page.marginTop;
89
75
  for (let i = start; i < end; i++) {
90
76
  lineTops[i] = lineTop;
91
- lineTop += heights[i] + (i + 1 < end ? gapBefore(i + 1) + share : 0);
77
+ lineTop += heights[i] + (i + 1 < end ? (gaps[i + 1] ?? 0) + share : 0);
92
78
  }
93
79
  const height = Number.isFinite(page.height)
94
80
  ? page.height
@@ -109,15 +95,15 @@ export function paginateLayoutLines(heights, page, pageBreaks = [], headrooms =
109
95
  used = 0;
110
96
  };
111
97
  for (let i = 0; i < heights.length; i++) {
112
- const height = heights[i];
98
+ const height = heights[i], gap = gaps[i] ?? 0;
113
99
  if (Number.isFinite(page.height) && height > availableHeight + 1e-6) {
114
100
  throw new PageLayoutError(i, height, availableHeight);
115
101
  }
116
102
  // 强制边界与自然溢出统一封页;无限页高不分配余白
117
- if (i > start && (pageBreaks[i] !== undefined || Number.isFinite(page.height) && used + gapBefore(i) + height > availableHeight + 1e-6)) {
103
+ if (i > start && (pageBreaks[i] !== undefined || Number.isFinite(page.height) && used + gap + height > availableHeight + 1e-6)) {
118
104
  closePage(i, Number.isFinite(page.height) && (pageBreaks[i] ?? true));
119
105
  }
120
- used += (i > start ? gapBefore(i) : 0) + height;
106
+ used += (i > start ? gap : 0) + height;
121
107
  }
122
108
  if (heights.length > start)
123
109
  closePage(heights.length, false);
@@ -3,7 +3,7 @@ import type { Extent, Track } from "../lowering/track.js";
3
3
  import type { Fraction } from "../fraction.js";
4
4
  import type { TemporalNodeBase, VisualTemporalNode } from "../functions/temporal.js";
5
5
  import type { SourceSpan } from "../parser/types.js";
6
- import type { HorizontalLayoutHook } from "./model.js";
6
+ import type { HorizontalLayoutHook, SolverOptions } from "./model.js";
7
7
  import type { LoweringAttachment, LoweringContent, PageConfig } from "../lowering/types.js";
8
8
  export type { Extent, PageConfig };
9
9
  /** 轴对齐矩形,是所有排版几何的公共部分 */
@@ -59,19 +59,18 @@ export interface LayoutPrepareContext {
59
59
  * 由 layoutDocument 在主体准备阶段注入;调用方创建的上下文没有它。
60
60
  */
61
61
  layoutSubdomain?(owner: TemporalNodeBase, columns: readonly (readonly VisualTemporalNode[])[], root: Track, attachments: readonly LoweringAttachment[]): SubdomainLayout;
62
+ solverOptions?: SolverOptions;
62
63
  }
63
64
  /** 子域块的尺寸与成员位置,坐标以块的左上角为原点 */
64
65
  export interface SubdomainLayout {
65
66
  width: number;
66
67
  height: number;
67
- /** 与 columns.flat() 一一对应,不含成员 onPlaced 追加的平移 */
68
+ /** 与 columns.flat() 一一对应的布局位置,不含后置平移 */
68
69
  positions: readonly LayoutPoint[];
69
70
  }
70
71
  export type LayoutRange = readonly [from: LayoutHost, to: LayoutHost];
71
72
  /** attachment 根据当前视觉轴生成几何时需要的完整页面信息 */
72
73
  export interface AttachmentLayoutContext extends LayoutPrepareContext {
73
- /** 占用测量使用布局位置,最终绘制才应用后置平移 */
74
- readonly layoutOnly?: boolean;
75
74
  width: number;
76
75
  originX: number;
77
76
  pages: readonly Rect[];
@@ -212,7 +211,7 @@ export interface LayoutAttachment extends LoweringAttachment {
212
211
  * 同一个值只对应一种图形,不应与时值对象的 kind 重名;取值规则见 render 文档
213
212
  */
214
213
  readonly kind?: string;
215
- /** 后置平移仅影响绘制,不参与占用求解 */
214
+ /** 后置平移:在 lowering 阶段声明,由引擎在占用测量后施加到绘制几何,不参与占用求解;createGeometry 不应自行平移 */
216
215
  placementOffset?: LayoutPoint;
217
216
  /** 几何端点;端点全部落在同一子域的成员上时,附件属于该子域。不表示内容包含或播放端点投影 */
218
217
  readonly endPoints?: readonly TemporalNodeBase[];
@@ -0,0 +1,33 @@
1
+ import type { Track } from "./track.js";
2
+ /**
3
+ * 一个音在记忆中的位置:key 为「级数:八度」;bar 只作小节的身份;seq 是读谱顺序;
4
+ * prior 是读到的半音偏移。升降半音补记时按 (bar, key) 分组,按 seq 找第一个
5
+ */
6
+ export interface AccidentalReading {
7
+ key: string;
8
+ bar: object;
9
+ seq: number;
10
+ prior: number;
11
+ }
12
+ /**
13
+ * 小节内变音记忆,作用按时间先后:后发生的音读得到先发生的写入,同一时刻的音互不影响。
14
+ * 处理顺序不等于时间顺序(如 ^ 从后往前处理),所以一列里的读写和清空先登记,列末按时刻结算
15
+ */
16
+ export declare class AccidentalMemory {
17
+ private readonly memory;
18
+ private readonly events;
19
+ private readonly staged;
20
+ private readonly now;
21
+ private reads;
22
+ /** 在列内时刻 time 处理 run。一列默认都在时刻 0,倚音成员在宿主之前或之后;嵌套时逐级细分,缺省的级为 0 */
23
+ at<T>(time: number, run: () => T): T;
24
+ /** 登记一个音:结算时读到前文,resolve 返回要写入的半音偏移,不写返回 undefined */
25
+ read(track: Track, key: string, resolve: (reading: AccidentalReading) => number | undefined): void;
26
+ /** 小节线清本轨及其子孙轨道(stack 的分支轨道跨小节复用);转调不传 track,全部清空 */
27
+ clear(track?: Track): void;
28
+ /** 列末按时刻结算;同一时刻按处理顺序执行 */
29
+ commit(): void;
30
+ private flush;
31
+ /** 当前小节的记忆;清空后会换成新的 Map,因此也作为小节的身份 */
32
+ private scope;
33
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 小节内变音记忆,作用按时间先后:后发生的音读得到先发生的写入,同一时刻的音互不影响。
3
+ * 处理顺序不等于时间顺序(如 ^ 从后往前处理),所以一列里的读写和清空先登记,列末按时刻结算
4
+ */
5
+ export class AccidentalMemory {
6
+ memory = new Map(); // 每个声部本小节的变音:声部轨道 → (键 → 半音偏移,# 为 +1、n 为 0)
7
+ events = []; // 本列登记的读写与清空
8
+ staged = []; // 当前时刻的写入,时刻推进时才提交
9
+ now = [];
10
+ reads = 0;
11
+ /** 在列内时刻 time 处理 run。一列默认都在时刻 0,倚音成员在宿主之前或之后;嵌套时逐级细分,缺省的级为 0 */
12
+ at(time, run) {
13
+ this.now.push(time);
14
+ try {
15
+ return run();
16
+ }
17
+ finally {
18
+ this.now.pop();
19
+ }
20
+ }
21
+ /** 登记一个音:结算时读到前文,resolve 返回要写入的半音偏移,不写返回 undefined */
22
+ read(track, key, resolve) {
23
+ const owner = voiceOf(track);
24
+ this.events.push({ time: [...this.now], run: () => {
25
+ const bar = this.scope(owner);
26
+ const offset = resolve({ key, bar, seq: this.reads++, prior: bar.get(key) ?? 0 });
27
+ if (offset !== undefined)
28
+ this.staged.push([owner, key, offset]);
29
+ } });
30
+ }
31
+ /** 小节线清本轨及其子孙轨道(stack 的分支轨道跨小节复用);转调不传 track,全部清空 */
32
+ clear(track) {
33
+ this.events.push({ time: [...this.now], run: () => {
34
+ if (!track)
35
+ return this.memory.clear();
36
+ for (const owner of this.memory.keys())
37
+ if (within(owner, track))
38
+ this.memory.delete(owner);
39
+ } });
40
+ }
41
+ /** 列末按时刻结算;同一时刻按处理顺序执行 */
42
+ commit() {
43
+ const events = this.events.splice(0).sort((a, b) => compareTime(a.time, b.time));
44
+ events.forEach(({ time, run }, i) => {
45
+ if (i > 0 && compareTime(events[i - 1].time, time))
46
+ this.flush();
47
+ run();
48
+ });
49
+ this.flush();
50
+ }
51
+ flush() {
52
+ for (const [owner, key, offset] of this.staged.splice(0))
53
+ this.scope(owner).set(key, offset);
54
+ }
55
+ /** 当前小节的记忆;清空后会换成新的 Map,因此也作为小节的身份 */
56
+ scope(owner) {
57
+ let map = this.memory.get(owner);
58
+ if (!map)
59
+ this.memory.set(owner, map = new Map());
60
+ return map;
61
+ }
62
+ }
63
+ /** 列内时刻逐级比较,缺省的级视为 0 */
64
+ function compareTime(a, b) {
65
+ for (let i = 0; i < a.length || i < b.length; i++) {
66
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
67
+ if (diff)
68
+ return diff;
69
+ }
70
+ return 0;
71
+ }
72
+ /** 记忆按声部归属:分组里的分支各成声部;不在父轨分组里的子轨(如倚音的私有根轨)只是排版子域,延续父轨的声部 */
73
+ function voiceOf(track) {
74
+ while (track.parent && !track.parent.groups.some(group => group.members.includes(track)))
75
+ track = track.parent;
76
+ return track;
77
+ }
78
+ function within(track, root) {
79
+ for (let current = track; current; current = current.parent) {
80
+ if (current === root)
81
+ return true;
82
+ }
83
+ return false;
84
+ }
@@ -1,7 +1,7 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
2
  import { Fraction } from "../fraction.js";
3
3
  import { ASTNodeBase } from "../functions/ASTtypes.js";
4
- import { TemporalNodeBase } from "../functions/temporal.js";
4
+ import { TemporalNodeBase, type TimeState } from "../functions/temporal.js";
5
5
  import type { LoweringFinalizer, LoweringGroup, LoweringAttachment, LoweringResult, PageConfig } from "./types.js";
6
6
  import { Track } from "./track.js";
7
7
  /**
@@ -101,19 +101,24 @@ export declare class LoweringContext {
101
101
  private indexTemporal;
102
102
  /**
103
103
  * 多轨时间上的 ANCHOR 对齐形成列,被 trackedEvents 在中间使用。会修改时间
104
- * @param tracks 多个 trackedEvents 的结果
105
- * @returns 锚点对齐后的 tracks,多轨道相同时间的会被合并为一个列
104
+ * @param tracks 多个非空的 trackedEvents 结果
105
+ * @param ends 各轨道的结束时刻,会被原地平移
106
+ * @param result 锚点对齐后的列追加到这里,多轨道相同时间的会被合并为一个列
107
+ * @returns 对齐后最晚的轨道结束时刻;没有轨道时为 undefined
106
108
  */
107
- static anchorAlign(tracks: TimeColumn[][]): TimeColumn[];
109
+ private static anchorAlign;
108
110
  }
109
- declare class TimeColumn extends Array<TemporalNodeBase> {
111
+ /** 全局时间列:同一时刻且 mergeKey 相等的事件归并成一列,承载列级时间、行号与入口速度 */
112
+ export declare class TimeColumn extends Array<TemporalNodeBase> {
110
113
  static get [Symbol.species](): ArrayConstructor;
111
114
  readonly mergeKey: number;
112
- constructor(n: TemporalNodeBase);
115
+ bpm: number;
116
+ timeSignature: TimeState["timeSignature"];
117
+ constructor(n: TemporalNodeBase, bpm?: number);
113
118
  get t(): Fraction;
114
119
  set t(value: Fraction);
115
120
  shiftTime(offset: Fraction): void;
121
+ get layoutLine(): number;
116
122
  /** 将当前列所有事件的行号固化为 lowering 后的实际行号 */
117
123
  set layoutLine(value: number);
118
124
  }
119
- export {};
@@ -2,6 +2,7 @@ import { Diagnostic } from "../diagnostic.js";
2
2
  import { Fraction } from "../fraction.js";
3
3
  import { ANCHOR_KEY, DEFAULT_BPM, DEFAULT_PROGRAM, DEFAULT_TONALITY, DEFAULT_VELOCITY, } from "../functions/temporal.js";
4
4
  import { Track } from "./track.js";
5
+ import { AccidentalMemory } from "./accidentalMemory.js";
5
6
  /**
6
7
  * 把 AST 展开并固化为时间列、attachment 和页面配置
7
8
  *
@@ -75,16 +76,11 @@ export class LoweringContext {
75
76
  * 固化谱面行号、时间状态和最终时长
76
77
  */
77
78
  solidifyColumns(columns, duration) {
78
- // 同时刻跨轨的 br 已经合成一列,所以取最大;同轨连写仍是多个列,因而累加
79
+ // 同时刻跨轨的 br 已经合成一列,只换一行;同轨连写仍是多个列,因而累加
79
80
  let line = 0;
80
81
  for (const column of columns) {
81
- let offset = 0;
82
- for (const node of column) {
83
- const requested = node.addon?.breakBefore ?? 0;
84
- if (requested > offset)
85
- offset = requested;
86
- }
87
- line += offset;
82
+ if (column.some(node => node.addon?.breakBefore))
83
+ line++;
88
84
  // 换行列本身归属于换行之后的那一行
89
85
  column.layoutLine = line;
90
86
  }
@@ -94,6 +90,7 @@ export class LoweringContext {
94
90
  velocity: DEFAULT_VELOCITY,
95
91
  keySignature: DEFAULT_TONALITY,
96
92
  program: DEFAULT_PROGRAM,
93
+ accidentals: new AccidentalMemory(),
97
94
  };
98
95
  // 力度和音色按音轨各自流动,新分叉的声部继承分叉处父轨的值
99
96
  const velocities = new Map();
@@ -104,6 +101,7 @@ export class LoweringContext {
104
101
  for (const column of columns) {
105
102
  if (!timeOffset.isZero())
106
103
  column.shiftTime(timeOffset);
104
+ column.bpm = state.bpm;
107
105
  let insertion;
108
106
  for (const node of column) {
109
107
  state.velocity = velocityOf(node.track);
@@ -115,6 +113,10 @@ export class LoweringContext {
115
113
  velocities.set(node.track, state.velocity);
116
114
  programs.set(node.track, state.program);
117
115
  }
116
+ // 与 bpm 不同,拍号取整列处理后的值,供跳转恢复
117
+ column.timeSignature = state.timeSignature;
118
+ // 整列登记完再按时间先后结算变音,同一时刻的音互不影响
119
+ state.accidentals.commit();
118
120
  // 同列声部一起开始,只在整列固化后累加一次偏移
119
121
  if (insertion)
120
122
  timeOffset.add(insertion);
@@ -253,6 +255,7 @@ export class LoweringContext {
253
255
  const hostIndex = spec.hostIndex === void 0 ? 0 : spec.hostIndex;
254
256
  const group = track.group(spec, hostIndex === null ? children.length : children.length - 1);
255
257
  const branches = [];
258
+ const ends = [];
256
259
  for (let i = 0; i < children.length; i++) {
257
260
  const c = children[i];
258
261
  // 宿主成员就地留在当前轨,其余成员按书写顺序拿分支音轨
@@ -264,22 +267,15 @@ export class LoweringContext {
264
267
  const branch = this.trackedEvents(c, branchTime, branchTrack);
265
268
  if (branch.length === 0) {
266
269
  this.diagnostics.push(Diagnostic.warning.ZeroTimeTrack(c.sourceSpan, i + 1));
270
+ continue;
267
271
  }
268
272
  branches.push(branch);
273
+ ends.push(branchTime);
269
274
  }
270
275
  // 归并 局部归并以限制对齐作用域
271
- const mergeStart = columns.length;
272
- for (const column of LoweringContext.anchorAlign(branches))
273
- columns.push(column);
274
- // 最长的事件未必落在最后一列,所以要扫全部合并列取最晚终点
275
- const eventEnd = new Fraction();
276
- for (let i = mergeStart; i < columns.length; i++) {
277
- for (const node of columns[i]) {
278
- eventEnd.copyFrom(node.t).add(node.T);
279
- if (eventEnd.compare(timeOffset) > 0)
280
- timeOffset.copyFrom(eventEnd);
281
- }
282
- }
276
+ const end = LoweringContext.anchorAlign(branches, ends, columns);
277
+ if (end && end.compare(timeOffset) > 0)
278
+ timeOffset.copyFrom(end);
283
279
  }
284
280
  break;
285
281
  }
@@ -316,26 +312,25 @@ export class LoweringContext {
316
312
  }
317
313
  /**
318
314
  * 多轨时间上的 ANCHOR 对齐形成列,被 trackedEvents 在中间使用。会修改时间
319
- * @param tracks 多个 trackedEvents 的结果
320
- * @returns 锚点对齐后的 tracks,多轨道相同时间的会被合并为一个列
315
+ * @param tracks 多个非空的 trackedEvents 结果
316
+ * @param ends 各轨道的结束时刻,会被原地平移
317
+ * @param result 锚点对齐后的列追加到这里,多轨道相同时间的会被合并为一个列
318
+ * @returns 对齐后最晚的轨道结束时刻;没有轨道时为 undefined
321
319
  */
322
- static anchorAlign(tracks) {
323
- // 删去长度为0的轨道
324
- for (let i = tracks.length - 1; i >= 0; i--) {
325
- if (tracks[i].length === 0)
326
- tracks.splice(i, 1);
327
- }
320
+ static anchorAlign(tracks, ends, result) {
328
321
  const l = tracks.length;
329
- // 分支全空;调用方已经逐条报过 ZeroTimeTrack
330
- if (l === 0)
331
- return [];
332
- if (l === 1)
333
- return tracks[0];
334
- const result = [];
322
+ if (l <= 1) {
323
+ if (l === 1)
324
+ for (const column of tracks[0])
325
+ result.push(column);
326
+ return ends[0];
327
+ }
335
328
  // 归并多个轨道
336
329
  const p = new Uint32Array(l); // 当前指向第几个
337
330
  const dt = Array.from({ length: l }, () => new Fraction()); // 每个轨道的偏移量
338
331
  const anchorBuffer = [];
332
+ // 已排完轨道的最晚终点:没有后续锚点的轨道会先排完,锚点要落在它们结束之后
333
+ const end = new Fraction();
339
334
  const heap = new HeapSort(l); // 保证每个轨在堆里最多一个
340
335
  for (let i = 0; i < l; i++)
341
336
  heap.push({ e: tracks[i][0], i });
@@ -346,26 +341,27 @@ export class LoweringContext {
346
341
  e.shiftTime(dt[i]);
347
342
  heap.push({ e, i });
348
343
  }
344
+ else if (ends[i].add(dt[i]).compare(end) > 0) {
345
+ // 排完时平移量已定,平移后的终点就是原终点加平移量
346
+ end.copyFrom(ends[i]);
347
+ }
349
348
  };
350
349
  while (true) {
351
350
  const front = heap.pop();
352
351
  if (front === void 0) {
353
352
  if (anchorBuffer.length === 0)
354
353
  break; // 都完了
355
- const first = anchorBuffer[0];
356
- const container = first.e;
357
- let maxT = container.t;
358
- for (let j = 1; j < anchorBuffer.length; j++) {
359
- if (anchorBuffer[j].e.t.compare(maxT) > 0)
360
- maxT = anchorBuffer[j].e.t;
361
- }
362
- dt[first.i].add(maxT).sub(container.t);
363
- fetchNext(first.i);
364
- for (let j = 1; j < anchorBuffer.length; j++) {
365
- const item = anchorBuffer[j];
366
- container.push(...item.e);
367
- dt[item.i].add(maxT).sub(item.e.t);
368
- fetchNext(item.i);
354
+ // 有锚点的轨道已全部停在锚点,其余轨道已排完
355
+ const maxT = end.clone();
356
+ for (const { e } of anchorBuffer)
357
+ if (e.t.compare(maxT) > 0)
358
+ maxT.copyFrom(e.t);
359
+ const container = anchorBuffer[0].e;
360
+ for (const { e, i } of anchorBuffer) {
361
+ if (e !== container)
362
+ container.push(...e);
363
+ dt[i].add(maxT).sub(e.t);
364
+ fetchNext(i);
369
365
  }
370
366
  anchorBuffer.length = 0;
371
367
  container.t = maxT;
@@ -394,16 +390,20 @@ export class LoweringContext {
394
390
  for (const i of consumed)
395
391
  fetchNext(i);
396
392
  }
397
- return result;
393
+ return end;
398
394
  }
399
395
  }
400
- class TimeColumn extends Array {
396
+ /** 全局时间列:同一时刻且 mergeKey 相等的事件归并成一列,承载列级时间、行号与入口速度 */
397
+ export class TimeColumn extends Array {
401
398
  // map/filter/slice 默认会用本类重建,而构造器会把长度当事件用;统一退回普通数组
402
399
  static get [Symbol.species]() { return Array; }
403
400
  mergeKey;
404
- constructor(n) {
401
+ bpm;
402
+ timeSignature;
403
+ constructor(n, bpm = DEFAULT_BPM) {
405
404
  super(1);
406
405
  this.mergeKey = n.mergeKey;
406
+ this.bpm = bpm;
407
407
  this[0] = n;
408
408
  }
409
409
  get t() {
@@ -417,6 +417,9 @@ class TimeColumn extends Array {
417
417
  for (const node of this)
418
418
  node.t.add(offset);
419
419
  }
420
+ get layoutLine() {
421
+ return this[0].layoutLine;
422
+ }
420
423
  /** 将当前列所有事件的行号固化为 lowering 后的实际行号 */
421
424
  set layoutLine(value) {
422
425
  for (const node of this)
@@ -3,6 +3,7 @@ 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 { TimeColumn } from "./loweringContext.js";
6
7
  import type { Track, TrackArrangement } from "./track.js";
7
8
  /** 文档页面的固化尺寸,所有值均为 px */
8
9
  export interface PageConfig {
@@ -12,8 +13,6 @@ export interface PageConfig {
12
13
  marginBottom: number;
13
14
  marginLeft: number;
14
15
  marginRight: number;
15
- lineGap: number;
16
- minLineGap: number;
17
16
  fillRatio: number;
18
17
  }
19
18
  /** lowering 产生的不推进时间的附属对象;具体能力由 layout/playback 子协议声明 */
@@ -37,7 +36,7 @@ export type LoweringFinalizer = (result: LoweringResult) => void;
37
36
  */
38
37
  export interface LoweringResult {
39
38
  diagnostics: Diagnostic[];
40
- columns: TemporalNodeBase[][];
39
+ columns: TimeColumn[];
41
40
  attachments: LoweringAttachment[];
42
41
  astToTemporal: Map<ASTNodeBase, TemporalNodeBase[]>;
43
42
  duration: Fraction;
@@ -1,10 +1,14 @@
1
- import type { SourceSpan } from "./types.js";
1
+ import type { SourceSpan, deSugarRelationFunction } from "./types.js";
2
2
  import type { FunctionArgs } from "../functions/ASTtypes.js";
3
3
  export type GrammarNode = GrammarBraceNode | GrammarLabelNode | GrammarCallNode | GrammarSugarNode;
4
4
  export interface GrammarNodeBase {
5
5
  kind: "brace" | "label" | "call" | "sugar";
6
6
  span: SourceSpan;
7
- /** 语法高亮类型;缺省为 operator,复合语法糖可直接给出多段 SyntaxToken */
7
+ /**
8
+ * 语法高亮类型;缺省为 operator,复合语法糖可直接给出多段 SyntaxToken
9
+ * 多段须按源码顺序、互不重叠,且落在 deSugarAtom 本次消费的 [start, next) 内(可超出 span,如 `H.title:` 后的正文);
10
+ * 解析器既不排序也不校验,违反时编辑器高亮会出错
11
+ */
8
12
  syntaxKind?: SyntaxTokenKind | SyntaxToken[];
9
13
  }
10
14
  export interface GrammarBraceNode extends GrammarNodeBase {
@@ -27,11 +31,12 @@ export interface GrammarCallNodeTyped extends GrammarCallNodeBase {
27
31
  }
28
32
  export type GrammarCallNode = GrammarCallNodeRaw | GrammarCallNodeTyped;
29
33
  /**
30
- * 语法糖节点,具体数据含义由具体函数去糖函数决定,将在第二轮解析中被处理
34
+ * 语法糖节点,由发出它的 deSugarAtom 同时给出数据和第二轮的处理函数
31
35
  */
32
36
  export interface GrammarSugarNode extends GrammarNodeBase {
33
37
  kind: "sugar";
34
- data: any;
38
+ data?: any;
39
+ relation: deSugarRelationFunction;
35
40
  }
36
41
  /**
37
42
  * 调用的具体源码结构。除语义名称外保留括号、参数名、等号、逗号和值的 span,
@@ -73,6 +78,7 @@ export interface SyntaxToken {
73
78
  /**
74
79
  * 面向编辑器的源码视图
75
80
  * tokens 用于着色,calls 保留调用与参数边界供补全定位;两者都引用原始源码 offset
81
+ * tokens 按起点升序且互不重叠;calls 按起点严格递增,外层调用在内层之前
76
82
  */
77
83
  export interface SyntaxAnalysis {
78
84
  tokens: SyntaxToken[];
@@ -6,9 +6,10 @@ export function readBrace(source, lBracePos, end) {
6
6
  for (let i = lBracePos + 1; i < end; i++) {
7
7
  const ch = source[i];
8
8
  if (ch === '"') {
9
- i = findClosingQuote(source, i, end);
10
- if (i < 0)
11
- break;
9
+ // 孤立引号按普通字符,与预处理“配对才算字符串”一致
10
+ const q = findClosingQuote(source, i, end);
11
+ if (q >= 0)
12
+ i = q;
12
13
  }
13
14
  else if (ch === "{")
14
15
  depth++;
@@ -61,11 +61,11 @@ export function readCall(source, atPos, end) {
61
61
  });
62
62
  for (i++; i < end; i++) {
63
63
  const ch = source[i];
64
- // 跳过字符串;忽略大括号内的小括号 防止大括号内小括号的不闭合影响外部
64
+ // 跳过字符串(孤立引号按普通字符);忽略大括号内的小括号 防止大括号内小括号的不闭合影响外部
65
65
  if (ch === '"') {
66
- i = findClosingQuote(source, i, end);
67
- if (i < 0)
68
- break;
66
+ const q = findClosingQuote(source, i, end);
67
+ if (q >= 0)
68
+ i = q;
69
69
  }
70
70
  else if (ch === "{")
71
71
  braceDepth++;
@@ -116,9 +116,9 @@ export function findRightParen(source, start, end) {
116
116
  for (let i = start; i < end; i++) {
117
117
  const ch = source[i];
118
118
  if (ch === '"') {
119
- i = findClosingQuote(source, i, end);
120
- if (i < 0)
121
- break;
119
+ const q = findClosingQuote(source, i, end);
120
+ if (q >= 0)
121
+ i = q;
122
122
  }
123
123
  else if (ch === "(")
124
124
  parenDepth++;
@@ -8,4 +8,4 @@ export declare function findClosingQuote(source: string, quotePos: number, end:
8
8
  /** 剥掉成对的双引号(若有)并解码编码/定界级转义(`\"`、`\\`、`\uXXXX`);其余 `\X` 原样保留给具体函数解析 */
9
9
  export declare function parseString(source: string): string | Diagnostic;
10
10
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
11
- export declare function quote(value: string): string;
11
+ export declare function quoteSourceString(value: string): string;
@@ -34,6 +34,6 @@ export function parseString(source) {
34
34
  return diagnostic ?? text;
35
35
  }
36
36
  /** 生成双引号包裹的 jpFun 源码,仅转义反斜杠和双引号;与 JSON.stringify 不同,保留真实换行和制表符 */
37
- export function quote(value) {
37
+ export function quoteSourceString(value) {
38
38
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
39
39
  }