jpfun 0.9.0 → 1.1.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 (125) hide show
  1. package/README.md +11 -16
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +21 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/default.js +2 -1
  11. package/dist/functions/div/index.d.ts +1 -1
  12. package/dist/functions/div/index.js +4 -2
  13. package/dist/functions/dyn/index.js +1 -0
  14. package/dist/functions/gliss/index.js +85 -9
  15. package/dist/functions/grace/index.d.ts +1 -8
  16. package/dist/functions/grace/index.js +23 -53
  17. package/dist/functions/head/index.js +23 -30
  18. package/dist/functions/key/index.js +5 -7
  19. package/dist/functions/meter/index.d.ts +1 -0
  20. package/dist/functions/meter/index.js +3 -0
  21. package/dist/functions/meter/shape.d.ts +1 -1
  22. package/dist/functions/note/accidentals.d.ts +3 -3
  23. package/dist/functions/note/accidentals.js +29 -16
  24. package/dist/functions/note/index.d.ts +5 -2
  25. package/dist/functions/note/index.js +168 -25
  26. package/dist/functions/note/source-transform.d.ts +23 -2
  27. package/dist/functions/note/source-transform.js +95 -74
  28. package/dist/functions/ottava/index.js +1 -0
  29. package/dist/functions/page/index.d.ts +1 -36
  30. package/dist/functions/page/index.js +8 -7
  31. package/dist/functions/rest/index.js +8 -6
  32. package/dist/functions/set/index.js +2 -2
  33. package/dist/functions/slide/index.js +1 -0
  34. package/dist/functions/stack/index.js +6 -4
  35. package/dist/functions/temporal.d.ts +12 -3
  36. package/dist/functions/temporal.js +15 -2
  37. package/dist/functions/text/index.js +2 -2
  38. package/dist/functions/tie/index.js +28 -4
  39. package/dist/functions/tremolo/index.js +1 -0
  40. package/dist/functions/tuplet/index.js +1 -0
  41. package/dist/functions/up/index.js +12 -12
  42. package/dist/functions/voice/connections.d.ts +1 -1
  43. package/dist/functions/voice/connections.js +2 -2
  44. package/dist/functions/voice/lyrics.d.ts +11 -5
  45. package/dist/functions/voice/lyrics.js +151 -47
  46. package/dist/functions/voice/voice.d.ts +6 -2
  47. package/dist/functions/voice/voice.js +51 -19
  48. package/dist/functions/voice/voices.d.ts +2 -1
  49. package/dist/functions/voice/voices.js +4 -3
  50. package/dist/functions/volta/index.js +1 -0
  51. package/dist/index.d.ts +69 -3
  52. package/dist/index.js +69 -3
  53. package/dist/jpfun.min.js +47 -60
  54. package/dist/layout/engine.d.ts +4 -3
  55. package/dist/layout/engine.js +173 -27
  56. package/dist/layout/model.d.ts +13 -4
  57. package/dist/layout/model.js +15 -7
  58. package/dist/layout/page.js +2 -2
  59. package/dist/layout/path.js +1 -1
  60. package/dist/layout/types.d.ts +12 -3
  61. package/dist/lowering/accidentalMemory.d.ts +33 -0
  62. package/dist/lowering/accidentalMemory.js +84 -0
  63. package/dist/lowering/loweringContext.js +4 -0
  64. package/dist/parser/grammarType.d.ts +8 -3
  65. package/dist/parser/parse-utils/brace-utils.js +7 -17
  66. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  67. package/dist/parser/parse-utils/call-utils.js +17 -32
  68. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  69. package/dist/parser/parse-utils/note-utils.js +8 -12
  70. package/dist/parser/parse-utils/string-utils.d.ts +1 -1
  71. package/dist/parser/parse-utils/string-utils.js +1 -1
  72. package/dist/parser/parserContext.d.ts +32 -26
  73. package/dist/parser/parserContext.js +104 -194
  74. package/dist/parser/preprocess.d.ts +7 -0
  75. package/dist/parser/preprocess.js +31 -42
  76. package/dist/parser/syntax.d.ts +9 -0
  77. package/dist/parser/syntax.js +109 -0
  78. package/dist/pipeline.d.ts +1 -1
  79. package/dist/pipeline.js +3 -2
  80. package/dist/playback/compile.js +5 -7
  81. package/dist/playback/event.d.ts +1 -2
  82. package/dist/playback/event.js +2 -3
  83. package/dist/render/canvas.js +50 -35
  84. package/dist/render/index.d.ts +2 -1
  85. package/dist/render/index.js +2 -1
  86. package/dist/render/paint.d.ts +7 -0
  87. package/dist/render/paint.js +70 -20
  88. package/dist/render/recording.d.ts +8 -1
  89. package/dist/render/recording.js +12 -0
  90. package/dist/render/svg.d.ts +5 -1
  91. package/dist/render/svg.js +37 -17
  92. package/dist/render/text.d.ts +2 -2
  93. package/dist/render/text.js +7 -6
  94. package/dist/render/translate.d.ts +3 -1
  95. package/dist/render/translate.js +6 -0
  96. package/dist/render/types.d.ts +9 -0
  97. package/grammar.md +7 -5
  98. package/package.json +8 -18
  99. package/dist/converter/midi/convert.d.ts +0 -42
  100. package/dist/converter/midi/convert.js +0 -682
  101. package/dist/converter/midi/index.d.ts +0 -5
  102. package/dist/converter/midi/index.js +0 -11
  103. package/dist/converter/midi/json.d.ts +0 -38
  104. package/dist/converter/midi/json.js +0 -1
  105. package/dist/converter/midi/triplet.d.ts +0 -30
  106. package/dist/converter/midi/triplet.js +0 -75
  107. package/dist/converter/musicxml/dom.d.ts +0 -25
  108. package/dist/converter/musicxml/dom.js +0 -65
  109. package/dist/converter/musicxml/features.d.ts +0 -114
  110. package/dist/converter/musicxml/features.js +0 -501
  111. package/dist/converter/musicxml/index.d.ts +0 -14
  112. package/dist/converter/musicxml/index.js +0 -1285
  113. package/dist/converter/musicxml/model.d.ts +0 -176
  114. package/dist/converter/musicxml/model.js +0 -1
  115. package/dist/converter/musicxml/resolve.d.ts +0 -10
  116. package/dist/converter/musicxml/resolve.js +0 -152
  117. package/dist/converter/source.d.ts +0 -19
  118. package/dist/converter/source.js +0 -53
  119. package/dist/core.d.ts +0 -24
  120. package/dist/core.js +0 -24
  121. package/dist/functions/voice/index.d.ts +0 -2
  122. package/dist/functions/voice/index.js +0 -2
  123. package/dist/jpfun.core.min.js +0 -132
  124. package/dist/jpfun.from-midi.min.js +0 -9
  125. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -1,45 +1,53 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
2
  import { DEFAULT_TEXT_FONT, JIANPU_NUMBER_FONT } from "../render/text.js";
3
- import { readCall, trimRange } from "./parse-utils/call-utils.js";
3
+ import { isNonLineWhitespace } from "./preprocess.js";
4
+ import { callArgName, readCall, trimRange } from "./parse-utils/call-utils.js";
4
5
  import { parseString } from "./parse-utils/string-utils.js";
5
6
  import { readBrace } from "./parse-utils/brace-utils.js";
6
7
  import { readLabel } from "./parse-utils/label-utils.js";
7
8
  import { parseLength } from "./parse-utils/length-utils.js";
8
9
  import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, resolveArgType } from "../functions/ASTtypes.js";
9
10
  // bool 字面量 严格要求小写
10
- const BOOL_RE = /^(true|false)$/;
11
- /** 有函数参数契约时直接用声明类型;未知参数回落到真正的字面量解析器,不另写一套正则 */
12
- function classifySyntaxValue(type, text) {
13
- if (type)
14
- return type === "content" ? undefined : type;
15
- if (BOOL_RE.test(text))
16
- return "boolean";
17
- if (text.startsWith('"'))
18
- return "string";
19
- if (!isNaN(Number(text)))
20
- return "number";
21
- if (!(parseLength(text) instanceof Diagnostic))
22
- return "length";
23
- return undefined;
24
- }
25
- export const DEFAULT_FONT_SIZE = 22;
11
+ export const BOOL_RE = /^(true|false)$/;
12
+ export const DEFAULT_FONT_SIZE = 18;
13
+ export const DEFAULT_NUMBER_WEIGHT = 700;
26
14
  // 解析上下文
27
15
  export class ParserContext {
28
16
  /** 系统变量,供 `@set` 读取 */
29
17
  static systemVariables = {
30
- fontsize: { type: "length", default: DEFAULT_FONT_SIZE },
31
- font: { type: "string", default: DEFAULT_TEXT_FONT },
32
- numberfont: { type: "string", default: JIANPU_NUMBER_FONT },
33
- strict: { type: "boolean", default: false },
18
+ fontsize: {
19
+ type: "length",
20
+ default: DEFAULT_FONT_SIZE,
21
+ description: "基准字号,也是 `em` 长度的换算基准"
22
+ },
23
+ font: {
24
+ type: "string",
25
+ default: DEFAULT_TEXT_FONT,
26
+ description: "普通文字字体"
27
+ },
28
+ numberfont: {
29
+ type: "string",
30
+ default: JIANPU_NUMBER_FONT,
31
+ description: "音符及同类谱面数字字体"
32
+ },
33
+ numberweight: {
34
+ type: "number",
35
+ default: DEFAULT_NUMBER_WEIGHT,
36
+ description: "主谱面数字字重,仅控制 `note`、`meter`、`rest`"
37
+ },
38
+ strict: {
39
+ type: "boolean",
40
+ default: false,
41
+ description: "开启严格的语法检查"
42
+ }
34
43
  };
35
- /** 根解析器为 0,内容参数和大括号子解析器依次加一 */
44
+ /**
45
+ * 根解析器为 0,内容参数和大括号子解析器依次加一
46
+ * 分组只存在于 AST 路径,导致语法糖并不会和函数调用一样开辟新的层级,因此只有 0(顶层)是可信的,非零的具体数值不可依赖
47
+ */
36
48
  scopeDepth;
37
49
  /** 源代码 */
38
50
  source;
39
- /** 词法层产物,只由 parseSyntax 填充;所有子上下文共享 */
40
- syntax;
41
- /** syntax.tokens 前缀注释区间的扫描游标 */
42
- commentIndex;
43
51
  /** 解析过程中产生的诊断信息,包含错误和警告 */
44
52
  diagnostics;
45
53
  /** 变量表,存储 `@set` 定义的变量,供解析过程中查询和修改,具有局部作用域 */
@@ -54,7 +62,11 @@ export class ParserContext {
54
62
  deSugarRelationFns;
55
63
  /** .labelable() 返回的承载节点;null 是边界标记,标签绑定不能越过它 */
56
64
  labelableNodes;
65
+ /** 当前正在实例化的显式函数调用节点,供构造函数按需读取原始参数区间 */
66
+ callNode;
57
67
  nodes; // 解析结果
68
+ /** 等待右操作数的中缀语法糖,见 deferRightOperand */
69
+ pendingRight = [];
58
70
  constructor(ctx) {
59
71
  if (ctx instanceof ParserContext) {
60
72
  // 构建子上下文
@@ -62,8 +74,6 @@ export class ParserContext {
62
74
  this.documentDeclarations = ctx.documentDeclarations;
63
75
  this.source = ctx.source;
64
76
  this.diagnostics = ctx.diagnostics; // 诊断信息全局共享
65
- this.syntax = ctx.syntax;
66
- this.commentIndex = ctx.commentIndex;
67
77
  this.variables = { ...ctx.variables }; // 继承但不修改父上下文的变量
68
78
  this.functions = ctx.functions; // 函数定义全局共享
69
79
  this.deSugarAtomFns = ctx.deSugarAtomFns; // 去糖方法全局共享
@@ -76,11 +86,6 @@ export class ParserContext {
76
86
  this.documentDeclarations = {};
77
87
  this.source = ctx.source;
78
88
  this.diagnostics = ctx.diagnostics ?? [];
79
- this.syntax = {
80
- tokens: (ctx.commentSpans ?? []).map(span => ({ kind: "comment", span })),
81
- calls: [],
82
- };
83
- this.commentIndex = 0;
84
89
  this.variables = Object.fromEntries(Object.entries(ParserContext.systemVariables).map(([name, definition]) => [name, definition.default]));
85
90
  Object.assign(this.variables, ctx.variables);
86
91
  this.functions = ctx.functions ?? new Map();
@@ -142,94 +147,13 @@ export class ParserContext {
142
147
  }
143
148
  //====== 解析相关 ======//
144
149
  /**
145
- * 扫描 GrammarNode 并构造 AST;不产出 syntax
146
- * 用于最终渲染
150
+ * 扫描 GrammarNode 并构造 AST,用于最终渲染
151
+ * 编辑器语法视图不构造 AST,见 syntax.ts 的 collectSyntax
147
152
  */
148
153
  parse(start = 0, end = this.source.length) {
149
154
  this.makeNodes(this.parseGrammar(start, end));
150
155
  return this.nodes;
151
156
  }
152
- /**
153
- * 词法层:容错扫描 GrammarNode 并收集 syntax
154
- * 用于防抖时的编辑器高亮和补全
155
- */
156
- parseSyntax(start = 0, end = this.source.length) {
157
- this.parseGrammar(start, end, true);
158
- if (this.scopeDepth === 0) {
159
- const cmp = (a, b) => a.span.start - b.span.start || a.span.end - b.span.end;
160
- this.syntax.tokens.sort(cmp);
161
- this.syntax.calls.sort(cmp);
162
- }
163
- return this.syntax;
164
- }
165
- // syntax 路径独占这些 span,AST 路径不会读取或改写它们;跨注释区间按前缀 comment token 切开以保证互不重叠
166
- addSyntax(kind, span) {
167
- if (!span || span.start >= span.end)
168
- return;
169
- let start = span.start;
170
- const tokens = this.syntax.tokens;
171
- while (tokens[this.commentIndex]?.kind === "comment" && tokens[this.commentIndex].span.end <= start) {
172
- this.commentIndex++;
173
- }
174
- for (let i = this.commentIndex; i < tokens.length; i++) {
175
- const token = tokens[i];
176
- if (token.kind !== "comment" || token.span.start >= span.end)
177
- break;
178
- if (start < token.span.start) {
179
- tokens.push({ kind, span: { start, end: token.span.start } });
180
- }
181
- start = token.span.end;
182
- this.commentIndex = i + 1;
183
- }
184
- if (start < span.end) {
185
- tokens.push({ kind, span: { start, end: span.end } });
186
- }
187
- }
188
- /** 把已识别的 GrammarNode 映射为源码 token;content/brace 在这里继续递归 */
189
- recordSyntax(node) {
190
- if (node.kind === "brace") {
191
- this.addSyntax("punctuation", { start: node.span.start, end: node.span.start + 1 });
192
- const close = Math.min(this.source.length, node.span.end - 1);
193
- new ParserContext(this).parseSyntax(node.span.start + 1, close);
194
- if (this.source[close] === "}")
195
- this.addSyntax("punctuation", { start: close, end: close + 1 });
196
- return;
197
- }
198
- if (node.kind === "label") {
199
- this.addSyntax("label", node.span);
200
- return;
201
- }
202
- if (node.kind === "sugar" || node.typed) {
203
- this.addSyntax(node.syntaxKind ?? "operator", node.span);
204
- return;
205
- }
206
- // syntax.calls 只暴露源码结构,不带 grammar 阶段的字段
207
- const { kind, typed, syntaxKind, ...call } = node;
208
- this.syntax.calls.push(call);
209
- this.addSyntax("function", call.nameSpan);
210
- this.addSyntax("punctuation", call.openParenSpan);
211
- const def = this.functions.get(call.name.toLowerCase())?.def;
212
- for (let index = 0; index < call.args.length; index++) {
213
- const arg = call.args[index];
214
- this.addSyntax("property", arg.nameSpan);
215
- this.addSyntax("punctuation", arg.equalsSpan);
216
- const name = arg.nameSpan
217
- ? this.source.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase()
218
- : void 0;
219
- const type = def && resolveArgType(def, name, index);
220
- if (type === "content") {
221
- new ParserContext(this).parseSyntax(arg.valueSpan.start, arg.valueSpan.end);
222
- }
223
- else {
224
- const text = this.source.slice(arg.valueSpan.start, arg.valueSpan.end);
225
- const kind = classifySyntaxValue(type, text);
226
- if (kind)
227
- this.addSyntax(kind, arg.valueSpan);
228
- }
229
- this.addSyntax("punctuation", arg.commaSpan);
230
- }
231
- this.addSyntax("punctuation", call.closeParenSpan);
232
- }
233
157
  /**
234
158
  * 向前寻找最后一个非文本节点下标;
235
159
  * 若末尾是标签,则将“被标注节点..标签”原位打包为 ASTBraceNode
@@ -253,51 +177,42 @@ export class ParserContext {
253
177
  }
254
178
  return left;
255
179
  }
256
- /** 摘出末尾最后一个操作数(含其后置标签) */
257
- takeLeftOperand() {
180
+ /**
181
+ * 摘出末尾最后一个操作数(含其后置标签)
182
+ * 传入 chain 时,若该操作数恰是同一 chain 挂起合成的唯一右操作数,先合成再返回:同类中缀由此左结合
183
+ */
184
+ takeLeftOperand(chain) {
258
185
  const index = this.findLastOperandIndex();
259
186
  if (index < 0)
260
187
  return null;
261
188
  const node = this.nodes[index];
262
189
  this.nodes.length = index;
263
- return node;
190
+ const top = this.pendingRight.at(-1);
191
+ if (chain === undefined || top?.chain !== chain || this.nodes.some(n => !(n instanceof ASTTextNode)))
192
+ return node;
193
+ this.pendingRight.pop();
194
+ this.nodes = top.left;
195
+ return top.combine(node);
264
196
  }
265
- /** 解析右侧剩余序列,将首个非文本节点交给 combine 合成后连同后续节点写回 this.nodes */
266
- consumeRightOperand(nodes, at, combine) {
267
- const storage = this.nodes;
197
+ /**
198
+ * 中缀语法糖的右操作数是本层剩余部分的首个非文本节点,要等本层解析完才能确定。
199
+ * 这里只挂起:已有节点留作左侧,后续节点解析到新数组,由 makeNodes 收尾时交给 combine;没有右操作数时 combine 收到 undefined
200
+ * 默认右结合;登记 chain 后,下一个同 chain 的中缀可经 takeLeftOperand 提前合成本帧。提前合成的结果不会进入 nodes,combine 不应有登记之类的副作用
201
+ */
202
+ deferRightOperand(combine, chain) {
203
+ this.pendingRight.push({ left: this.nodes, combine, chain });
268
204
  this.nodes = [];
269
- try {
270
- this.makeNodes(nodes, at);
271
- for (let i = 0; i < this.nodes.length; i++) {
272
- const right = this.nodes[i];
273
- if (right instanceof ASTTextNode)
274
- continue;
275
- storage.push(combine(right));
276
- while (++i < this.nodes.length)
277
- storage.push(this.nodes[i]);
278
- return nodes.length;
279
- }
280
- return null;
281
- }
282
- finally {
283
- this.nodes = storage;
284
- }
285
205
  }
286
206
  /**
287
207
  * 第二轮去糖 & 函数节点创建
288
208
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
289
209
  */
290
- makeNodes(nodes, i = 0, end = nodes.length) {
291
- outer: for (; i < end; i++) {
210
+ makeNodes(nodes) {
211
+ const base = this.pendingRight.length; // 只收尾本次登记的合成,同一上下文可重入
212
+ outer: for (let i = 0; i < nodes.length; i++) {
292
213
  const node = nodes[i];
293
214
  if (typeof node === "number") {
294
- // 合并多个连续文本为一个
295
- const prev = this.nodes.at(-1);
296
- if (prev instanceof ASTTextNode && prev.sourceSpan.end === node) {
297
- prev.sourceSpan.end = node + 1;
298
- }
299
- else
300
- this.nodes.push(new ASTTextNode({ start: node, end: node + 1 }, null));
215
+ this.pushText(node, node + 1);
301
216
  continue;
302
217
  }
303
218
  switch (node.kind) {
@@ -332,39 +247,55 @@ export class ParserContext {
332
247
  continue outer;
333
248
  }
334
249
  }
335
- // 匹配失败,保留为文本
336
- const prev = this.nodes.at(-1);
337
- if (prev instanceof ASTTextNode && prev.sourceSpan.end === node.span.start) {
338
- prev.sourceSpan.end = node.span.end;
339
- }
340
- else
341
- this.nodes.push(new ASTTextNode(node.span, null));
250
+ this.pushText(node.span.start, node.span.end); // 匹配失败,保留为文本
342
251
  break;
343
252
  }
344
253
  }
345
- return i;
254
+ // 由内向外合成,最外层的左侧就是原输出数组;各层剩余节点倒序暂存、最后接回,整体线性
255
+ const tail = [];
256
+ while (this.pendingRight.length > base) {
257
+ const { left, combine } = this.pendingRight.pop();
258
+ const right = this.nodes;
259
+ let i = 0;
260
+ while (right[i] instanceof ASTTextNode)
261
+ i++;
262
+ left.push(combine(right[i]));
263
+ for (let k = right.length - 1; k > i; k--)
264
+ tail.push(right[k]);
265
+ this.nodes = left;
266
+ }
267
+ while (tail.length)
268
+ this.nodes.push(tail.pop());
269
+ }
270
+ /** 追加文本,与紧邻的上一个文本节点合并;新建区间对象,避免改写语法节点的 span */
271
+ pushText(start, end) {
272
+ const prev = this.nodes.at(-1);
273
+ if (prev instanceof ASTTextNode && prev.sourceSpan.end === start)
274
+ prev.sourceSpan.end = end;
275
+ else
276
+ this.nodes.push(new ASTTextNode({ start, end }, null));
346
277
  }
347
278
  /**
348
279
  * 识别核心语法: 大括号/函数调用/标签,其余尝试语法糖,失败的字符以索引的形式存在于返回值中,供第二轮识别终止符或合并为 TextNode
349
280
  * 即使是关系型的语法糖,这一阶段也要将依赖的字符提取为 GrammarSugarNode,供下一阶段处理
350
281
  * 必须将第一阶段语法糖识别放到grammar解析中,比如 `@fn()`,引号若作为语法糖会导致后面的 `@` 无效
351
- * syntaxOnly 是词法层模式:用户语法错误只记录诊断不抛出(保留 partial call),并顺带记录 syntax;
352
- * 它不得改变“识别出什么结构”,否则两条路径会认不同的语言
282
+ * observe 在每个节点识别后、校验前收到该节点及当前上下文;返回 true 即接管该节点:其语法错误只记录诊断不抛出(保留 partial call),
283
+ * 供编辑器在输入途中继续工作。不传或返回 false 时照常抛出。observe 不得改变“识别出什么结构”,否则两条路径会认不同的语言
353
284
  */
354
- parseGrammar(p, end, syntaxOnly = false) {
285
+ parseGrammar(p, end, observe) {
355
286
  const nodes = [];
287
+ /** 返回观察者是否接管该节点 */
356
288
  const emit = (node) => {
357
289
  nodes.push(node);
358
- if (syntaxOnly)
359
- this.recordSyntax(node);
290
+ return observe?.(node, this) ?? false;
360
291
  };
361
292
  outer: while ((p = skipSpaces(this.source, p, end)) < end) {
362
293
  const ch = this.source[p];
363
294
  if (ch === "@") {
364
295
  const call = readCall(this.source, p, end);
365
296
  if (call) {
366
- // 先落 syntax 再校验,抛错时编辑器仍拿得到已识别的结构
367
- emit(Object.assign(call, {
297
+ // 先交给观察者再校验:抛错时编辑器仍拿得到已识别的结构
298
+ const tolerant = emit(Object.assign(call, {
368
299
  kind: "call",
369
300
  typed: false
370
301
  }));
@@ -377,7 +308,7 @@ export class ParserContext {
377
308
  else if (!isNamed && positionArgEnd) {
378
309
  // 位置参数不允许出现在命名参数之后
379
310
  const error = Diagnostic.error.PosAfterNamedArg(call.name, arg.span);
380
- if (!syntaxOnly)
311
+ if (!tolerant)
381
312
  throw error;
382
313
  this.diagnostics.push(error);
383
314
  }
@@ -385,7 +316,7 @@ export class ParserContext {
385
316
  // 括号未闭合
386
317
  if (!call.closeParenSpan) {
387
318
  const fatal = Diagnostic.error.UnterminatedCall(call.name, call.span);
388
- if (!syntaxOnly)
319
+ if (!tolerant)
389
320
  throw fatal;
390
321
  this.diagnostics.push(fatal);
391
322
  }
@@ -409,11 +340,8 @@ export class ParserContext {
409
340
  // 找到结尾
410
341
  let braceEnd = readBrace(this.source, p, end);
411
342
  // 大括号不匹配 报警 但继续解析 相当于补了一个右大括号
412
- if (braceEnd < 0 || braceEnd >= end || braceEnd <= p) {
413
- this.diagnostics.push(Diagnostic.warning.UnmatchedBrace({
414
- start: p,
415
- end: end
416
- }));
343
+ if (braceEnd < 0) {
344
+ this.diagnostics.push(Diagnostic.warning.UnmatchedBrace({ start: p, end }));
417
345
  braceEnd = end;
418
346
  }
419
347
  emit({
@@ -434,11 +362,8 @@ export class ParserContext {
434
362
  }
435
363
  }
436
364
  catch (e) {
437
- // 原子级去糖一般不出错。出错肯定是原则性问题
438
- if (e instanceof Diagnostic) {
439
- this.diagnostics.push(e);
440
- }
441
- else
365
+ // 原子级去糖一般不出错。Diagnostic 交给捕获方记录,避免内容参数恢复时重复
366
+ if (!(e instanceof Diagnostic))
442
367
  this.diagnostics.push(Diagnostic.error.Bug(e.toString(), { start: p, end }));
443
368
  throw e;
444
369
  }
@@ -466,9 +391,7 @@ export class ParserContext {
466
391
  const args = new Map();
467
392
  for (let i = 0; i < callNode.args.length; i++) {
468
393
  const arg = callNode.args[i];
469
- const name = arg.nameSpan
470
- ? this.source.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase()
471
- : void 0;
394
+ const name = callArgName(this.source, arg);
472
395
  const type = resolveArgType(def, name, i);
473
396
  const key = name ?? i;
474
397
  if (type === void 0) {
@@ -483,8 +406,10 @@ export class ParserContext {
483
406
  if (value !== null)
484
407
  args.set(key, value);
485
408
  }
409
+ this.callNode = callNode;
486
410
  return new callFNClass(callNode.span, args, this, null);
487
411
  } // 完全信任 typed 时的 arg
412
+ this.callNode = undefined;
488
413
  // 构造函数内用定义查询实际传参
489
414
  return new callFNClass(callNode.span, callNode.args, this, null);
490
415
  }
@@ -593,28 +518,13 @@ export class ParserContext {
593
518
  }
594
519
  // 换行转义已经在预处理解决了,这里不用再跳过了
595
520
  export function skipSpaces(s, i, end) {
596
- while (i < end && isWhitespaceButNotNewline(s[i]))
521
+ while (i < end && isNonLineWhitespace(s.charCodeAt(i)))
597
522
  i++;
598
523
  return i;
599
524
  }
600
525
  /** 反向跳过非换行空白,越界返回 -1 */
601
526
  export function skipSpacesBack(s, i, start = 0) {
602
- while (i >= start && isWhitespaceButNotNewline(s[i]))
527
+ while (i >= start && isNonLineWhitespace(s.charCodeAt(i)))
603
528
  i--;
604
529
  return i;
605
530
  }
606
- function isWhitespaceButNotNewline(ch) {
607
- switch (ch) {
608
- case ' ':
609
- case '\t':
610
- case '\v': // 垂直制表符
611
- case '\f': // 换页符
612
- case '\u00A0': // 不间断空格
613
- case '\uFEFF': // 零宽不连字空格
614
- case '\u3000': // 中文全角空格
615
- return true;
616
- default:
617
- return false;
618
- // \n 和 \r 不算
619
- }
620
- }
@@ -1,4 +1,11 @@
1
1
  import type { SourceSpan } from "./types.js";
2
+ /**
3
+ * 判断非换行空白(对齐 ECMAScript `\s` 中除 `\r`/`\n`/`\u2028`/`\u2029` 外的全部空白字符):
4
+ * - ASCII 空白:`' '` (32)、`'\t'` (9)、`'\v'` (11)、`'\f'` (12)
5
+ * - Unicode 空白:`'\u00A0'` 不间断空格、`'\u1680'` 欧甘空格、`'\u2000'`..`'\u200A'` (8192..8202) 排版空格族、
6
+ * `'\u202F'` 窄不间断空格、`'\u205F'` 中等数学空格、`'\u3000'` 中文全角空格、`'\uFEFF'` BOM
7
+ */
8
+ export declare function isNonLineWhitespace(ch: number): boolean;
2
9
  export declare function preprocessSource(source: string): {
3
10
  maskedSource: string;
4
11
  lineStarts: number[];
@@ -9,21 +9,21 @@ import { findClosingQuote } from "./parse-utils/string-utils.js";
9
9
  * - 若 n 为奇数,则该行换行符也替换为空格(续行)
10
10
  * 4. 字符串外 CRLF 中的 CR 等长替换为空格,词法层只消费 LF
11
11
  */
12
- const CHAR_LF = 10;
13
- const CHAR_CR = 13;
14
- const CHAR_TAB = 9;
15
- const CHAR_VTAB = 11;
16
- const CHAR_FF = 12;
17
- const CHAR_SPACE = 32;
18
- const CHAR_NBSP = 160;
19
- const CHAR_OGHAM_SPACE_MARK = 5760;
20
- const CHAR_NARROW_NO_BREAK_SPACE = 8239;
21
- const CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;
22
- const CHAR_IDEOGRAPHIC_SPACE = 12288;
23
- const CHAR_BOM = 65279;
24
- const CHAR_QUOTE_DOUBLE = 34;
25
- const CHAR_BACKSLASH = 92;
26
- const CHAR_PERCENT = 37;
12
+ const CHAR_LF = 10; // \n 换行
13
+ const CHAR_CR = 13; // \r 回车
14
+ const CHAR_TAB = 9; // \t 水平制表符
15
+ const CHAR_VTAB = 11; // \v 垂直制表符
16
+ const CHAR_FF = 12; // \f 换页符
17
+ const CHAR_SPACE = 32; // ' ' 普通空格
18
+ const CHAR_NBSP = 160; // \u00A0 不间断空格
19
+ const CHAR_OGHAM_SPACE_MARK = 5760; // \u1680 欧甘空格
20
+ const CHAR_NARROW_NO_BREAK_SPACE = 8239; // \u202F 窄不间断空格
21
+ const CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287; // \u205F 中等数学空格
22
+ const CHAR_IDEOGRAPHIC_SPACE = 12288; // \u3000 中文全角空格
23
+ const CHAR_BOM = 65279; // \uFEFF 零宽不连字空格 (BOM)
24
+ const CHAR_QUOTE_DOUBLE = 34; // '"'
25
+ const CHAR_BACKSLASH = 92; // '\\'
26
+ const CHAR_PERCENT = 37; // '%'
27
27
  // 掩码几乎都是短注释和续行反斜杠,长的既少重复又要一直占着内存,所以只缓存短的
28
28
  const MAX_CACHED_SPACES = 32;
29
29
  const SHORT_SPACES = [];
@@ -33,10 +33,12 @@ function getSpaces(length) {
33
33
  return SHORT_SPACES[length] ??= " ".repeat(length);
34
34
  }
35
35
  /**
36
- * 判断 非换行空白
37
- * 说明:CR/LF 由主循环单独处理,这里只负责可被“行尾回看”忽略的空白
36
+ * 判断非换行空白(对齐 ECMAScript `\s` 中除 `\r`/`\n`/`\u2028`/`\u2029` 外的全部空白字符):
37
+ * - ASCII 空白:`' '` (32)、`'\t'` (9)、`'\v'` (11)、`'\f'` (12)
38
+ * - Unicode 空白:`'\u00A0'` 不间断空格、`'\u1680'` 欧甘空格、`'\u2000'`..`'\u200A'` (8192..8202) 排版空格族、
39
+ * `'\u202F'` 窄不间断空格、`'\u205F'` 中等数学空格、`'\u3000'` 中文全角空格、`'\uFEFF'` BOM
38
40
  */
39
- function isNonLineWhitespace(ch) {
41
+ export function isNonLineWhitespace(ch) {
40
42
  // 热路径优先处理 ASCII
41
43
  if (ch === CHAR_SPACE || ch === CHAR_TAB || ch === CHAR_VTAB || ch === CHAR_FF)
42
44
  return true;
@@ -44,7 +46,7 @@ function isNonLineWhitespace(ch) {
44
46
  return false;
45
47
  return (ch === CHAR_NBSP ||
46
48
  ch === CHAR_OGHAM_SPACE_MARK ||
47
- (ch >= 8192 && ch <= 8202) ||
49
+ (ch >= 8192 && ch <= 8202) || // \u2000..\u200A:En/Em Quad、En/Em/Three-Per-Em/Four-Per-Em/Six-Per-Em/Figure/Punctuation/Thin/Hair Space
48
50
  ch === CHAR_NARROW_NO_BREAK_SPACE ||
49
51
  ch === CHAR_MEDIUM_MATHEMATICAL_SPACE ||
50
52
  ch === CHAR_IDEOGRAPHIC_SPACE ||
@@ -77,15 +79,14 @@ export function preprocessSource(source) {
77
79
  };
78
80
  /**
79
81
  * 扫描状态说明:
80
- * - inQuote:0=不在字符串;其他值为当前引号字符码
81
- * - escaped:仅在字符串内有效,表示上一个字符是 `\`
82
+ * - quoteEnd:当前/上一个字符串的闭引号位置,前瞻失败后为 -1;`i <= quoteEnd` 即在字符串内,转义规则只由 findClosingQuote 决定
83
+ * - noPairedQuoteAfter:前瞻失败过,后文不再有可配对的引号
82
84
  * - pendingCommentStart:>=0 表示已遇到 `%`,等待到行尾/EOF 收口注释
83
85
  * - tailBackslashRunStart/tailBackslashRunCount:
84
86
  * 当前行末尾候选连续 `\` 片段(允许后面跟空白),用于换行处一次性判定
85
87
  */
86
- let inQuote = 0;
88
+ let quoteEnd = -1;
87
89
  let noPairedQuoteAfter = false;
88
- let escaped = false;
89
90
  let pendingCommentStart = -1;
90
91
  let tailBackslashRunStart = -1;
91
92
  let tailBackslashRunCount = 0;
@@ -118,23 +119,16 @@ export function preprocessSource(source) {
118
119
  }
119
120
  if (isOddBackslashRun)
120
121
  pushReplaceRange(i, i + newlineWidth);
121
- else if (inQuote === 0 && newlineWidth === 2)
122
+ else if (i > quoteEnd && newlineWidth === 2)
122
123
  pushReplaceRange(i, i + 1);
123
124
  // 新行重置行内状态
124
125
  tailBackslashRunStart = -1;
125
126
  tailBackslashRunCount = 0;
126
- escaped = false;
127
127
  i += newlineWidth;
128
128
  continue;
129
129
  }
130
- // 字符串内仅处理转义与闭合;不识别注释
131
- if (inQuote !== 0) {
132
- if (escaped)
133
- escaped = false;
134
- else if (ch === CHAR_BACKSLASH)
135
- escaped = true;
136
- else if (ch === inQuote)
137
- inQuote = 0;
130
+ // 字符串内不识别引号与注释,只参与行尾反斜杠判定;单独成快路径,字符串密集时比与下方合流快约 20%
131
+ if (i <= quoteEnd) {
138
132
  if (!isNonLineWhitespace(ch))
139
133
  updateLineTailState(i, ch);
140
134
  i++;
@@ -144,17 +138,12 @@ export function preprocessSource(source) {
144
138
  // 配对才算字符串,否则一个孤立引号会让后文的 `%` 全部失去注释语义
145
139
  // 一次前瞻失败即证明剩余源码里没有可配对的引号,置位后不再前瞻,整体仍是 O(n)
146
140
  if (!noPairedQuoteAfter) {
147
- if (findClosingQuote(source, i, sourceLength) < 0)
148
- noPairedQuoteAfter = true;
149
- else
150
- inQuote = ch;
141
+ quoteEnd = findClosingQuote(source, i, sourceLength);
142
+ noPairedQuoteAfter = quoteEnd < 0;
151
143
  }
152
- updateLineTailState(i, ch);
153
- i++;
154
- continue;
155
144
  }
156
- // 非字符串上下文下,`%` 到行尾是注释;直接跳到换行,减少无效判断
157
- if (ch === CHAR_PERCENT) {
145
+ else if (ch === CHAR_PERCENT) {
146
+ // `%` 到行尾是注释;直接跳到换行,减少无效判断
158
147
  pendingCommentStart = i;
159
148
  i++;
160
149
  while (i < sourceLength) {
@@ -0,0 +1,9 @@
1
+ import type { SyntaxAnalysis } from "./grammarType.js";
2
+ import { ParserContext } from "./parserContext.js";
3
+ import type { SourceSpan } from "./types.js";
4
+ /**
5
+ * 编辑器语法视图:以词法层模式观察 parseGrammar,收集着色 token 与调用结构,不构造 AST
6
+ * 节点按源码顺序发出、子区间就地递归,所以 tokens 有序且互不重叠,calls 按起点严格递增,无需排序;
7
+ * 注释在预处理阶段已被掩码,最后从 commentSpans 归并回来
8
+ */
9
+ export declare function collectSyntax(parser: ParserContext, commentSpans: SourceSpan[]): SyntaxAnalysis;