jpfun 1.1.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 (54) hide show
  1. package/dist/diagnostic.d.ts +1 -0
  2. package/dist/diagnostic.js +1 -0
  3. package/dist/functions/ASTtypes.d.ts +2 -3
  4. package/dist/functions/ASTtypes.js +2 -3
  5. package/dist/functions/adjust/index.js +15 -67
  6. package/dist/functions/bar/index.js +8 -7
  7. package/dist/functions/beam/auto.js +15 -11
  8. package/dist/functions/beam/layout.js +22 -48
  9. package/dist/functions/br/index.d.ts +9 -3
  10. package/dist/functions/br/index.js +20 -16
  11. package/dist/functions/dash/index.js +13 -11
  12. package/dist/functions/div/index.d.ts +2 -2
  13. package/dist/functions/div/index.js +5 -9
  14. package/dist/functions/dot/index.js +5 -9
  15. package/dist/functions/dyn/index.js +125 -53
  16. package/dist/functions/grace/index.d.ts +2 -2
  17. package/dist/functions/grace/index.js +5 -9
  18. package/dist/functions/head/index.js +6 -7
  19. package/dist/functions/meter/index.js +7 -5
  20. package/dist/functions/note/index.js +5 -7
  21. package/dist/functions/ottava/index.js +8 -7
  22. package/dist/functions/page/index.js +8 -12
  23. package/dist/functions/pagebreak/index.js +2 -1
  24. package/dist/functions/rest/index.js +5 -5
  25. package/dist/functions/stack/index.js +1 -3
  26. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  27. package/dist/functions/symbol/symbols/dynamics.js +10 -1
  28. package/dist/functions/tempo/index.js +8 -3
  29. package/dist/functions/temporal.d.ts +18 -6
  30. package/dist/functions/temporal.js +1 -1
  31. package/dist/functions/text/index.js +1 -3
  32. package/dist/functions/up/index.js +29 -28
  33. package/dist/functions/voice/voice.d.ts +2 -1
  34. package/dist/functions/voice/voice.js +7 -13
  35. package/dist/functions/voice/voices.d.ts +4 -3
  36. package/dist/functions/voice/voices.js +8 -8
  37. package/dist/jpfun.min.js +48 -45
  38. package/dist/layout/engine.js +224 -211
  39. package/dist/layout/page.d.ts +2 -2
  40. package/dist/layout/page.js +8 -22
  41. package/dist/layout/types.d.ts +2 -4
  42. package/dist/lowering/loweringContext.d.ts +12 -7
  43. package/dist/lowering/loweringContext.js +50 -51
  44. package/dist/lowering/types.d.ts +2 -3
  45. package/dist/parser/grammarType.d.ts +4 -3
  46. package/dist/parser/parse-utils/brace-utils.js +4 -3
  47. package/dist/parser/parse-utils/call-utils.js +7 -7
  48. package/dist/parser/parserContext.d.ts +5 -9
  49. package/dist/parser/parserContext.js +24 -36
  50. package/dist/parser/types.d.ts +2 -1
  51. package/dist/playback/compile.js +23 -13
  52. package/dist/playback/types.d.ts +0 -1
  53. package/grammar.md +7 -6
  54. package/package.json +2 -2
@@ -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);
@@ -65,14 +65,12 @@ export interface LayoutPrepareContext {
65
65
  export interface SubdomainLayout {
66
66
  width: number;
67
67
  height: number;
68
- /** 与 columns.flat() 一一对应,不含成员 onPlaced 追加的平移 */
68
+ /** 与 columns.flat() 一一对应的布局位置,不含后置平移 */
69
69
  positions: readonly LayoutPoint[];
70
70
  }
71
71
  export type LayoutRange = readonly [from: LayoutHost, to: LayoutHost];
72
72
  /** attachment 根据当前视觉轴生成几何时需要的完整页面信息 */
73
73
  export interface AttachmentLayoutContext extends LayoutPrepareContext {
74
- /** 占用测量使用布局位置,最终绘制才应用后置平移 */
75
- readonly layoutOnly?: boolean;
76
74
  width: number;
77
75
  originX: number;
78
76
  pages: readonly Rect[];
@@ -213,7 +211,7 @@ export interface LayoutAttachment extends LoweringAttachment {
213
211
  * 同一个值只对应一种图形,不应与时值对象的 kind 重名;取值规则见 render 文档
214
212
  */
215
213
  readonly kind?: string;
216
- /** 后置平移仅影响绘制,不参与占用求解 */
214
+ /** 后置平移:在 lowering 阶段声明,由引擎在占用测量后施加到绘制几何,不参与占用求解;createGeometry 不应自行平移 */
217
215
  placementOffset?: LayoutPoint;
218
216
  /** 几何端点;端点全部落在同一子域的成员上时,附件属于该子域。不表示内容包含或播放端点投影 */
219
217
  readonly endPoints?: readonly TemporalNodeBase[];
@@ -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 {};
@@ -76,16 +76,11 @@ export class LoweringContext {
76
76
  * 固化谱面行号、时间状态和最终时长
77
77
  */
78
78
  solidifyColumns(columns, duration) {
79
- // 同时刻跨轨的 br 已经合成一列,所以取最大;同轨连写仍是多个列,因而累加
79
+ // 同时刻跨轨的 br 已经合成一列,只换一行;同轨连写仍是多个列,因而累加
80
80
  let line = 0;
81
81
  for (const column of columns) {
82
- let offset = 0;
83
- for (const node of column) {
84
- const requested = node.addon?.breakBefore ?? 0;
85
- if (requested > offset)
86
- offset = requested;
87
- }
88
- line += offset;
82
+ if (column.some(node => node.addon?.breakBefore))
83
+ line++;
89
84
  // 换行列本身归属于换行之后的那一行
90
85
  column.layoutLine = line;
91
86
  }
@@ -106,6 +101,7 @@ export class LoweringContext {
106
101
  for (const column of columns) {
107
102
  if (!timeOffset.isZero())
108
103
  column.shiftTime(timeOffset);
104
+ column.bpm = state.bpm;
109
105
  let insertion;
110
106
  for (const node of column) {
111
107
  state.velocity = velocityOf(node.track);
@@ -117,6 +113,8 @@ export class LoweringContext {
117
113
  velocities.set(node.track, state.velocity);
118
114
  programs.set(node.track, state.program);
119
115
  }
116
+ // 与 bpm 不同,拍号取整列处理后的值,供跳转恢复
117
+ column.timeSignature = state.timeSignature;
120
118
  // 整列登记完再按时间先后结算变音,同一时刻的音互不影响
121
119
  state.accidentals.commit();
122
120
  // 同列声部一起开始,只在整列固化后累加一次偏移
@@ -257,6 +255,7 @@ export class LoweringContext {
257
255
  const hostIndex = spec.hostIndex === void 0 ? 0 : spec.hostIndex;
258
256
  const group = track.group(spec, hostIndex === null ? children.length : children.length - 1);
259
257
  const branches = [];
258
+ const ends = [];
260
259
  for (let i = 0; i < children.length; i++) {
261
260
  const c = children[i];
262
261
  // 宿主成员就地留在当前轨,其余成员按书写顺序拿分支音轨
@@ -268,22 +267,15 @@ export class LoweringContext {
268
267
  const branch = this.trackedEvents(c, branchTime, branchTrack);
269
268
  if (branch.length === 0) {
270
269
  this.diagnostics.push(Diagnostic.warning.ZeroTimeTrack(c.sourceSpan, i + 1));
270
+ continue;
271
271
  }
272
272
  branches.push(branch);
273
+ ends.push(branchTime);
273
274
  }
274
275
  // 归并 局部归并以限制对齐作用域
275
- const mergeStart = columns.length;
276
- for (const column of LoweringContext.anchorAlign(branches))
277
- columns.push(column);
278
- // 最长的事件未必落在最后一列,所以要扫全部合并列取最晚终点
279
- const eventEnd = new Fraction();
280
- for (let i = mergeStart; i < columns.length; i++) {
281
- for (const node of columns[i]) {
282
- eventEnd.copyFrom(node.t).add(node.T);
283
- if (eventEnd.compare(timeOffset) > 0)
284
- timeOffset.copyFrom(eventEnd);
285
- }
286
- }
276
+ const end = LoweringContext.anchorAlign(branches, ends, columns);
277
+ if (end && end.compare(timeOffset) > 0)
278
+ timeOffset.copyFrom(end);
287
279
  }
288
280
  break;
289
281
  }
@@ -320,26 +312,25 @@ export class LoweringContext {
320
312
  }
321
313
  /**
322
314
  * 多轨时间上的 ANCHOR 对齐形成列,被 trackedEvents 在中间使用。会修改时间
323
- * @param tracks 多个 trackedEvents 的结果
324
- * @returns 锚点对齐后的 tracks,多轨道相同时间的会被合并为一个列
315
+ * @param tracks 多个非空的 trackedEvents 结果
316
+ * @param ends 各轨道的结束时刻,会被原地平移
317
+ * @param result 锚点对齐后的列追加到这里,多轨道相同时间的会被合并为一个列
318
+ * @returns 对齐后最晚的轨道结束时刻;没有轨道时为 undefined
325
319
  */
326
- static anchorAlign(tracks) {
327
- // 删去长度为0的轨道
328
- for (let i = tracks.length - 1; i >= 0; i--) {
329
- if (tracks[i].length === 0)
330
- tracks.splice(i, 1);
331
- }
320
+ static anchorAlign(tracks, ends, result) {
332
321
  const l = tracks.length;
333
- // 分支全空;调用方已经逐条报过 ZeroTimeTrack
334
- if (l === 0)
335
- return [];
336
- if (l === 1)
337
- return tracks[0];
338
- 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
+ }
339
328
  // 归并多个轨道
340
329
  const p = new Uint32Array(l); // 当前指向第几个
341
330
  const dt = Array.from({ length: l }, () => new Fraction()); // 每个轨道的偏移量
342
331
  const anchorBuffer = [];
332
+ // 已排完轨道的最晚终点:没有后续锚点的轨道会先排完,锚点要落在它们结束之后
333
+ const end = new Fraction();
343
334
  const heap = new HeapSort(l); // 保证每个轨在堆里最多一个
344
335
  for (let i = 0; i < l; i++)
345
336
  heap.push({ e: tracks[i][0], i });
@@ -350,26 +341,27 @@ export class LoweringContext {
350
341
  e.shiftTime(dt[i]);
351
342
  heap.push({ e, i });
352
343
  }
344
+ else if (ends[i].add(dt[i]).compare(end) > 0) {
345
+ // 排完时平移量已定,平移后的终点就是原终点加平移量
346
+ end.copyFrom(ends[i]);
347
+ }
353
348
  };
354
349
  while (true) {
355
350
  const front = heap.pop();
356
351
  if (front === void 0) {
357
352
  if (anchorBuffer.length === 0)
358
353
  break; // 都完了
359
- const first = anchorBuffer[0];
360
- const container = first.e;
361
- let maxT = container.t;
362
- for (let j = 1; j < anchorBuffer.length; j++) {
363
- if (anchorBuffer[j].e.t.compare(maxT) > 0)
364
- maxT = anchorBuffer[j].e.t;
365
- }
366
- dt[first.i].add(maxT).sub(container.t);
367
- fetchNext(first.i);
368
- for (let j = 1; j < anchorBuffer.length; j++) {
369
- const item = anchorBuffer[j];
370
- container.push(...item.e);
371
- dt[item.i].add(maxT).sub(item.e.t);
372
- 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);
373
365
  }
374
366
  anchorBuffer.length = 0;
375
367
  container.t = maxT;
@@ -398,16 +390,20 @@ export class LoweringContext {
398
390
  for (const i of consumed)
399
391
  fetchNext(i);
400
392
  }
401
- return result;
393
+ return end;
402
394
  }
403
395
  }
404
- class TimeColumn extends Array {
396
+ /** 全局时间列:同一时刻且 mergeKey 相等的事件归并成一列,承载列级时间、行号与入口速度 */
397
+ export class TimeColumn extends Array {
405
398
  // map/filter/slice 默认会用本类重建,而构造器会把长度当事件用;统一退回普通数组
406
399
  static get [Symbol.species]() { return Array; }
407
400
  mergeKey;
408
- constructor(n) {
401
+ bpm;
402
+ timeSignature;
403
+ constructor(n, bpm = DEFAULT_BPM) {
409
404
  super(1);
410
405
  this.mergeKey = n.mergeKey;
406
+ this.bpm = bpm;
411
407
  this[0] = n;
412
408
  }
413
409
  get t() {
@@ -421,6 +417,9 @@ class TimeColumn extends Array {
421
417
  for (const node of this)
422
418
  node.t.add(offset);
423
419
  }
420
+ get layoutLine() {
421
+ return this[0].layoutLine;
422
+ }
424
423
  /** 将当前列所有事件的行号固化为 lowering 后的实际行号 */
425
424
  set layoutLine(value) {
426
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,4 +1,4 @@
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 {
@@ -31,11 +31,12 @@ export interface GrammarCallNodeTyped extends GrammarCallNodeBase {
31
31
  }
32
32
  export type GrammarCallNode = GrammarCallNodeRaw | GrammarCallNodeTyped;
33
33
  /**
34
- * 语法糖节点,具体数据含义由具体函数去糖函数决定,将在第二轮解析中被处理
34
+ * 语法糖节点,由发出它的 deSugarAtom 同时给出数据和第二轮的处理函数
35
35
  */
36
36
  export interface GrammarSugarNode extends GrammarNodeBase {
37
37
  kind: "sugar";
38
- data: any;
38
+ data?: any;
39
+ relation: deSugarRelationFunction;
39
40
  }
40
41
  /**
41
42
  * 调用的具体源码结构。除语义名称外保留括号、参数名、等号、逗号和值的 span,
@@ -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++;
@@ -1,4 +1,4 @@
1
- import { deSugarAtomFunction, deSugarRelationFunction, LengthValue, SourceSpan } from "./types.js";
1
+ import { deSugarAtomFunction, LengthValue, SourceSpan } from "./types.js";
2
2
  import { Diagnostic } from "../diagnostic.js";
3
3
  import { GrammarCallNode, GrammarCallNodeRaw, GrammarNode } from "./grammarType.js";
4
4
  import { ASTFunctionClass, ASTFunctionNode, ASTNodeBase, paramType, paramValue } from "../functions/ASTtypes.js";
@@ -27,10 +27,8 @@ export declare class ParserContext {
27
27
  documentDeclarations: Record<string, any>;
28
28
  /** 函数定义查找表 */
29
29
  functions: Map<string, ASTFunctionClass>;
30
- /** 语法糖识别函数列表,分为两轮:第一轮原子级去糖:将文本转为函数调用,或特殊标记 */
30
+ /** 第一轮原子去糖:将文本转为函数调用,或 sugar 标记;第二轮由 sugar 节点自带的 relation 处理 */
31
31
  deSugarAtomFns: deSugarAtomFunction[];
32
- /** 第二轮关系型去糖:得到函数节点。用于依赖 ASTNode 的语法糖 */
33
- deSugarRelationFns: deSugarRelationFunction[];
34
32
  /** .labelable() 返回的承载节点;null 是边界标记,标签绑定不能越过它 */
35
33
  labelableNodes: (ASTFunctionNode | null)[];
36
34
  /** 当前正在实例化的显式函数调用节点,供构造函数按需读取原始参数区间 */
@@ -46,10 +44,7 @@ export declare class ParserContext {
46
44
  labelableNodes?: (ASTFunctionNode | null)[];
47
45
  toConsume?: ASTNodeBase[];
48
46
  });
49
- static getDeSugarFns(classes: Iterable<ASTFunctionClass>): [
50
- deSugarAtomFunction[],
51
- deSugarRelationFunction[]
52
- ];
47
+ static getDeSugarFns(classes: Iterable<ASTFunctionClass>): deSugarAtomFunction[];
53
48
  pushNode(node: ASTNodeBase): void;
54
49
  setVariable(name: string, value: paramValue | undefined): void;
55
50
  registerFunctions(functionClasses: ASTFunctionClass[]): void;
@@ -94,8 +89,9 @@ export declare class ParserContext {
94
89
  * 根据参数类型解析参数值,解析过程中会记录诊断信息
95
90
  * funcStart 是为了找到该函数之前的label的位置 因为如果content先解析会污染 labelableNodes
96
91
  * 解析成功返回值 解析失败返回null
92
+ * required 的 content 解析失败时直接抛出内部错误:返回 null 只会换来掩盖真因的缺参错误
97
93
  */
98
- parseArgWithType(span: SourceSpan, type?: paramType, funcStart?: number): paramValue | null;
94
+ parseArgWithType(span: SourceSpan, type?: paramType, funcStart?: number, required?: boolean): paramValue | null;
99
95
  length2px(length: LengthValue): number;
100
96
  }
101
97
  export declare function skipSpaces(s: string, i: number, end: number): number;
@@ -6,7 +6,7 @@ import { parseString } from "./parse-utils/string-utils.js";
6
6
  import { readBrace } from "./parse-utils/brace-utils.js";
7
7
  import { readLabel } from "./parse-utils/label-utils.js";
8
8
  import { parseLength } from "./parse-utils/length-utils.js";
9
- import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, resolveArgType } from "../functions/ASTtypes.js";
9
+ import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, resolveArgDef, resolveArgType } from "../functions/ASTtypes.js";
10
10
  // bool 字面量 严格要求小写
11
11
  export const BOOL_RE = /^(true|false)$/;
12
12
  export const DEFAULT_FONT_SIZE = 18;
@@ -56,10 +56,8 @@ export class ParserContext {
56
56
  documentDeclarations;
57
57
  /** 函数定义查找表 */
58
58
  functions;
59
- /** 语法糖识别函数列表,分为两轮:第一轮原子级去糖:将文本转为函数调用,或特殊标记 */
59
+ /** 第一轮原子去糖:将文本转为函数调用,或 sugar 标记;第二轮由 sugar 节点自带的 relation 处理 */
60
60
  deSugarAtomFns;
61
- /** 第二轮关系型去糖:得到函数节点。用于依赖 ASTNode 的语法糖 */
62
- deSugarRelationFns;
63
61
  /** .labelable() 返回的承载节点;null 是边界标记,标签绑定不能越过它 */
64
62
  labelableNodes;
65
63
  /** 当前正在实例化的显式函数调用节点,供构造函数按需读取原始参数区间 */
@@ -77,7 +75,6 @@ export class ParserContext {
77
75
  this.variables = { ...ctx.variables }; // 继承但不修改父上下文的变量
78
76
  this.functions = ctx.functions; // 函数定义全局共享
79
77
  this.deSugarAtomFns = ctx.deSugarAtomFns; // 去糖方法全局共享
80
- this.deSugarRelationFns = ctx.deSugarRelationFns; // 去糖方法全局共享
81
78
  this.labelableNodes = ctx.labelableNodes; // 标签是全局属性
82
79
  this.nodes = []; // 待消费节点不共享,每个上下文单独维护
83
80
  }
@@ -91,26 +88,16 @@ export class ParserContext {
91
88
  this.functions = ctx.functions ?? new Map();
92
89
  this.labelableNodes = ctx.labelableNodes ?? [];
93
90
  this.nodes = ctx.toConsume ?? [];
94
- if (ctx.functions)
95
- [this.deSugarAtomFns, this.deSugarRelationFns] = ParserContext.getDeSugarFns(this.functions.values());
96
- else
97
- this.deSugarAtomFns = [], this.deSugarRelationFns = [];
91
+ this.deSugarAtomFns = ParserContext.getDeSugarFns(this.functions.values());
98
92
  }
99
93
  }
100
94
  static getDeSugarFns(classes) {
101
- // 去重 因为一个函数有多个别名
102
- const cls = new Set(classes);
103
- const deSugarAtomFns = [];
104
- const deSugarRelationFns = [];
105
- for (const fnClass of cls) {
106
- const deSugarAtom = fnClass.deSugarAtom;
107
- if (deSugarAtom && deSugarAtom !== ASTFunctionNode.deSugarAtom)
108
- deSugarAtomFns.push(deSugarAtom);
109
- const deSugarRelation = fnClass.deSugarRelation;
110
- if (deSugarRelation && deSugarRelation !== ASTFunctionNode.deSugarRelation)
111
- deSugarRelationFns.push(deSugarRelation);
112
- }
113
- return [deSugarAtomFns, deSugarRelationFns];
95
+ // 按函数去重:一个类有多个别名
96
+ const fns = new Set();
97
+ for (const fnClass of classes)
98
+ fns.add(fnClass.deSugarAtom);
99
+ fns.delete(ASTFunctionNode.deSugarAtom);
100
+ return [...fns];
114
101
  }
115
102
  pushNode(node) {
116
103
  this.nodes.push(node);
@@ -143,7 +130,7 @@ export class ParserContext {
143
130
  map.set(name.toLowerCase(), funcClass);
144
131
  }
145
132
  }
146
- [this.deSugarAtomFns, this.deSugarRelationFns] = ParserContext.getDeSugarFns(this.functions.values());
133
+ this.deSugarAtomFns = ParserContext.getDeSugarFns(this.functions.values());
147
134
  }
148
135
  //====== 解析相关 ======//
149
136
  /**
@@ -209,7 +196,7 @@ export class ParserContext {
209
196
  */
210
197
  makeNodes(nodes) {
211
198
  const base = this.pendingRight.length; // 只收尾本次登记的合成,同一上下文可重入
212
- outer: for (let i = 0; i < nodes.length; i++) {
199
+ for (let i = 0; i < nodes.length; i++) {
213
200
  const node = nodes[i];
214
201
  if (typeof node === "number") {
215
202
  this.pushText(node, node + 1);
@@ -240,14 +227,11 @@ export class ParserContext {
240
227
  }
241
228
  break;
242
229
  case "sugar":
243
- for (const fn of this.deSugarRelationFns) {
244
- const r = fn(this, nodes, i);
245
- if (r !== null) {
246
- i = r - 1; // 循环会+1
247
- continue outer;
248
- }
249
- }
250
- this.pushText(node.span.start, node.span.end); // 匹配失败,保留为文本
230
+ const next = node.relation(this, nodes, i);
231
+ if (next === null)
232
+ this.pushText(node.span.start, node.span.end); // 发出者放弃,保留为文本
233
+ else
234
+ i = next - 1; // 循环会+1
251
235
  break;
252
236
  }
253
237
  }
@@ -396,13 +380,16 @@ export class ParserContext {
396
380
  const key = name ?? i;
397
381
  if (type === void 0) {
398
382
  if (!def.allowExtraArgs) {
399
- this.diagnostics.push(Diagnostic.warning.TooManyPosArgs(callNode.name, defArgs.filter(arg => !arg.namedOnly).length, i + 1, arg.valueSpan));
383
+ this.diagnostics.push(name ?
384
+ Diagnostic.warning.UnknownArg(callNode.name, this.source.slice(arg.nameSpan.start, arg.nameSpan.end), arg.span) :
385
+ Diagnostic.warning.TooManyPosArgs(callNode.name, defArgs.filter(arg => !arg.namedOnly).length, i + 1, arg.valueSpan));
400
386
  }
401
387
  else
402
388
  args.set(key, arg);
403
389
  continue;
404
390
  }
405
- const value = this.parseArgWithType(arg.valueSpan, type, callNode.span.start);
391
+ const required = resolveArgDef(def, name, i)?.default === null;
392
+ const value = this.parseArgWithType(arg.valueSpan, type, callNode.span.start, required);
406
393
  if (value !== null)
407
394
  args.set(key, value);
408
395
  }
@@ -417,8 +404,9 @@ export class ParserContext {
417
404
  * 根据参数类型解析参数值,解析过程中会记录诊断信息
418
405
  * funcStart 是为了找到该函数之前的label的位置 因为如果content先解析会污染 labelableNodes
419
406
  * 解析成功返回值 解析失败返回null
407
+ * required 的 content 解析失败时直接抛出内部错误:返回 null 只会换来掩盖真因的缺参错误
420
408
  */
421
- parseArgWithType(span, type, funcStart) {
409
+ parseArgWithType(span, type, funcStart, required = false) {
422
410
  // 先去空白
423
411
  const r = trimRange(this.source, span.start, span.end);
424
412
  const start = r.start, end = r.end;
@@ -465,7 +453,7 @@ export class ParserContext {
465
453
  else
466
454
  delete target.label;
467
455
  }
468
- if (this.variables.strict || !(e instanceof Diagnostic))
456
+ if (required || this.variables.strict || !(e instanceof Diagnostic))
469
457
  throw e;
470
458
  // 当前参数会被跳过,因此在恢复点记录被吞掉的具体错误
471
459
  this.diagnostics.push(e, Diagnostic.warning.InvalidContent(r));
@@ -24,8 +24,9 @@ export type deSugarAtomFunction = (source: string, start: number, end: number, d
24
24
  node: GrammarNode;
25
25
  } | null;
26
26
  /**
27
+ * 关系去糖:由 deSugarAtom 挂在 sugar 节点上,makeNodes 遇到该节点时直接调用,不再逐个尝试
27
28
  * 传入的列表已经被拆为单字符了 会修改 ctx
28
- * 返回值是下一个位置 指 nodes 数组;若为null则表示不匹配,需要继续尝试
29
+ * 返回值是下一个位置 指 nodes 数组;返回 null 表示放弃,该 sugar 保留为文本
29
30
  * 内部报错需要push到ctx再throw
30
31
  */
31
32
  export type deSugarRelationFunction = (ctx: ParserContext, nodes: (GrammarNode | number)[], at: number) => number | null;