soma-core 1.4.0 → 1.4.2

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 (132) hide show
  1. package/README.md +1 -1
  2. package/core/build/blocks/block-compile.ts +31 -2
  3. package/core/build/blocks/block-container.ts +2 -11
  4. package/core/build/compiler/page-declaration-compiler.ts +30 -2
  5. package/core/build/compiler/soma-precompile.js +2053 -23
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/component/package-loader.ts +32 -0
  8. package/core/build/eject/component-eject.ts +473 -0
  9. package/core/build/eject/component-upgrade.ts +359 -0
  10. package/core/build/layout/constraint-solver.ts +235 -0
  11. package/core/build/layout/css-emitter.ts +116 -0
  12. package/core/build/layout/page-layout.ts +85 -0
  13. package/core/build/pack/pack-init.ts +270 -0
  14. package/core/client/base/SomaHttpClient.ts +34 -1
  15. package/core/client/base/SomaPageRootBase.ts +61 -0
  16. package/core/client/component/ai-catalog.ts +121 -4
  17. package/core/client/component/component-defaults.ts +100 -0
  18. package/core/client/component/component-definition.types.ts +39 -0
  19. package/core/client/component/component-manager.ts +79 -4
  20. package/core/client/component/component-pack.ts +126 -2
  21. package/core/client/component/keyboard-matrix.ts +144 -0
  22. package/core/client/component/pack-styles.ts +59 -1
  23. package/core/client/component/style-features.ts +131 -0
  24. package/core/client/component/theme-component-tokens.ts +83 -0
  25. package/core/client/component/verify-pack.ts +120 -1
  26. package/core/client/container/SomaContainerAdapter.ts +6 -2
  27. package/core/client/data/data-object-resolver.ts +407 -4
  28. package/core/client/data/reaction-engine.ts +176 -0
  29. package/core/client/data/window-engine.ts +477 -0
  30. package/core/client/engine/event-engine.ts +98 -0
  31. package/core/client/engine/soma-bootstrap.ts +265 -5
  32. package/core/client/engine/step-runner.ts +134 -0
  33. package/core/client/infra/http/SomaHttpService.ts +2 -2
  34. package/core/client/parser/blocks/page-parser.ts +15 -1
  35. package/core/client/parser/blocks/use-parser.ts +5 -12
  36. package/core/client/parser/data-config-parser.ts +316 -8
  37. package/core/client/parser/duration.ts +16 -0
  38. package/core/client/parser/layout-parser.ts +157 -0
  39. package/core/client/parser/page-state-parser.ts +166 -0
  40. package/core/client/parser/pipeline-parser.ts +76 -1
  41. package/core/client/parser/reaction-parser.ts +459 -0
  42. package/core/client/parser/reaction-sugar.ts +47 -0
  43. package/core/client/parser/step-parser.ts +359 -0
  44. package/core/client/parser/ui-config-parser.ts +59 -0
  45. package/core/client/parser/window-parser.ts +294 -0
  46. package/core/client/theme/theme-engine.ts +102 -2
  47. package/core/index.ts +184 -0
  48. package/core/shared/block-errors.ts +11 -0
  49. package/core/shared/calc/coerce.ts +29 -0
  50. package/core/shared/calc/errors.ts +43 -0
  51. package/core/shared/calc/evaluator.ts +101 -0
  52. package/core/shared/calc/index.ts +12 -0
  53. package/core/shared/calc/lexer.ts +194 -0
  54. package/core/shared/calc/parser.ts +204 -0
  55. package/core/shared/calc/typer.ts +184 -0
  56. package/core/shared/component/derive-sample.ts +105 -0
  57. package/core/shared/component/field-lines.ts +473 -0
  58. package/core/shared/path-algebra.ts +169 -0
  59. package/core/shared/predicates/index.ts +527 -0
  60. package/core/shared/types/component-contract.types.ts +151 -9
  61. package/core/shared/types/data-config.types.ts +120 -1
  62. package/core/shared/types/domain.types.ts +13 -0
  63. package/core/shared/types/event.types.ts +22 -2
  64. package/core/shared/types/layout-constraint.types.ts +73 -0
  65. package/core/shared/types/page-state.types.ts +60 -0
  66. package/core/shared/types/reaction.types.ts +144 -0
  67. package/core/shared/types/step.types.ts +91 -0
  68. package/core/shared/types/ui-config.types.ts +18 -0
  69. package/core/shared/types/window.types.ts +177 -0
  70. package/dist/cli/soma.js +13 -1
  71. package/dist/core/index.cjs +5529 -631
  72. package/dist/types/build/blocks/block-container.d.ts +1 -6
  73. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  74. package/dist/types/build/component/component-graph.d.ts +85 -0
  75. package/dist/types/build/eject/component-eject.d.ts +121 -0
  76. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  77. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  78. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  79. package/dist/types/build/layout/page-layout.d.ts +24 -0
  80. package/dist/types/build/pack/pack-init.d.ts +8 -0
  81. package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
  82. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  83. package/dist/types/client/component/ai-catalog.d.ts +33 -1
  84. package/dist/types/client/component/component-defaults.d.ts +15 -0
  85. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  86. package/dist/types/client/component/component-manager.d.ts +36 -0
  87. package/dist/types/client/component/component-pack.d.ts +32 -2
  88. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  89. package/dist/types/client/component/pack-styles.d.ts +21 -0
  90. package/dist/types/client/component/style-features.d.ts +26 -0
  91. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  92. package/dist/types/client/component/verify-pack.d.ts +10 -0
  93. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  94. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  95. package/dist/types/client/data/window-engine.d.ts +27 -0
  96. package/dist/types/client/engine/event-engine.d.ts +15 -0
  97. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  98. package/dist/types/client/engine/step-runner.d.ts +24 -0
  99. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  100. package/dist/types/client/parser/duration.d.ts +1 -0
  101. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  102. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  103. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  104. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  105. package/dist/types/client/parser/step-parser.d.ts +23 -0
  106. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  107. package/dist/types/client/parser/window-parser.d.ts +25 -0
  108. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  109. package/dist/types/index.d.ts +35 -2
  110. package/dist/types/shared/block-errors.d.ts +5 -0
  111. package/dist/types/shared/calc/coerce.d.ts +4 -0
  112. package/dist/types/shared/calc/errors.d.ts +14 -0
  113. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  114. package/dist/types/shared/calc/index.d.ts +6 -0
  115. package/dist/types/shared/calc/lexer.d.ts +20 -0
  116. package/dist/types/shared/calc/parser.d.ts +49 -0
  117. package/dist/types/shared/calc/typer.d.ts +16 -0
  118. package/dist/types/shared/component/derive-sample.d.ts +23 -0
  119. package/dist/types/shared/component/field-lines.d.ts +19 -0
  120. package/dist/types/shared/path-algebra.d.ts +56 -0
  121. package/dist/types/shared/predicates/index.d.ts +79 -0
  122. package/dist/types/shared/types/component-contract.types.d.ts +134 -6
  123. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  124. package/dist/types/shared/types/domain.types.d.ts +12 -0
  125. package/dist/types/shared/types/event.types.d.ts +8 -2
  126. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  127. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  128. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  129. package/dist/types/shared/types/step.types.d.ts +76 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  131. package/dist/types/shared/types/window.types.d.ts +171 -0
  132. package/package.json +3 -2
@@ -0,0 +1,29 @@
1
+ // 值归一(REQ-010 S1a)——calc 与谓词图共用的一层。
2
+ //
3
+ // 为什么必须共用:同一个 `amount` 字段,在 `visible_when: { field: amount, op: gt, value: 1000 }`
4
+ // 里被判为「大于 1000」,在 `calc: "[amount] * 0.1"` 里必须也当成同一个数。
5
+ // 两处各写一套归一,迟早出现「谓词说大于、算式算成 NaN」这种自相矛盾。
6
+ //
7
+ // 归一规则与 `soma-ui/src/shared/field-predicates.ts` 的 `ordinal()` 逐条对齐:
8
+ // 数字原样;Date 取时间戳;纯数字串转数字;可解析的日期串转时间戳;其余为 null。
9
+
10
+ /** 数值/日期归一:能当数用就返回数,否则 null */
11
+ export function ordinalOf(value: unknown): number | null {
12
+ if (value === null || value === undefined || value === '') return null;
13
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
14
+ if (typeof value === 'boolean') return null;
15
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime();
16
+ const text = String(value).trim();
17
+ if (text === '') return null;
18
+ if (/^[-+]?\d+(\.\d+)?$/.test(text)) {
19
+ const parsed = Number(text);
20
+ return Number.isFinite(parsed) ? parsed : null;
21
+ }
22
+ const asDate = Date.parse(text);
23
+ return Number.isNaN(asDate) ? null : asDate;
24
+ }
25
+
26
+ /** 文本化:null/undefined → 空串(CONCAT 与等值比较共用) */
27
+ export function textOf(value: unknown): string {
28
+ return value === null || value === undefined ? '' : String(value);
29
+ }
@@ -0,0 +1,43 @@
1
+ // calc 表达式层的错误类型(REQ-010 S1a)。
2
+ //
3
+ // 两类错误分开是刻意的:语法错是「这串字符不是一个表达式」,类型错是「它是个表达式,
4
+ // 但算的东西说不通」。前者作者改的是写法,后者作者改的是字段选型——错得不一样,
5
+ // 提示也不该混成一句「表达式无效」。
6
+ //
7
+ // 两者都带 `pos`(源串里的字符区间)。声明写在 YAML 里,出错时只说「calc 有问题」
8
+ // 等于让人拿肉眼在一行里找那个字母;带列号才能一眼看到。
9
+
10
+ /** 源串里的字符区间 [起, 止),用于错误定位 */
11
+ export type CalcSpan = readonly [number, number];
12
+
13
+ export class SomaCalcSyntaxError extends Error {
14
+ readonly pos: CalcSpan;
15
+ /** 出错处附近的原文片段(供报错时回显) */
16
+ readonly near: string;
17
+
18
+ constructor(message: string, source: string, pos: CalcSpan) {
19
+ super(`[soma-core][calc] ${formatWhere(source, pos)}:${message}`);
20
+ this.name = 'SomaCalcSyntaxError';
21
+ this.pos = pos;
22
+ this.near = source.slice(pos[0], pos[1]);
23
+ }
24
+ }
25
+
26
+ export class SomaCalcTypeError extends Error {
27
+ readonly pos: CalcSpan;
28
+ readonly expected: string;
29
+ readonly actual: string;
30
+
31
+ constructor(message: string, source: string, pos: CalcSpan, expected: string, actual: string) {
32
+ super(`[soma-core][calc] ${formatWhere(source, pos)}:${message}`);
33
+ this.name = 'SomaCalcTypeError';
34
+ this.pos = pos;
35
+ this.expected = expected;
36
+ this.actual = actual;
37
+ }
38
+ }
39
+
40
+ /** `calc "[amount] - [dsicount]" 第 12 列` —— 源串短,整串回显比行号有用 */
41
+ function formatWhere(source: string, pos: CalcSpan): string {
42
+ return `calc ${JSON.stringify(source)} 第 ${pos[0] + 1} 列`;
43
+ }
@@ -0,0 +1,101 @@
1
+ // calc 求值(REQ-010 S1a)——纯递归,无 eval、无 Function 构造、无副作用。
2
+ //
3
+ // 求值发生在**类型已经推过**之后,所以这里不重复做类型判断;它只处理运行期才知道的事:
4
+ // 值缺失、除零、以及「声明写的是 money,接口回来是字符串 "1280.00"」这类现实。
5
+ //
6
+ // ── 空值语义:任一操作数缺失 → 结果为 null,不抛 ────────────────────────
7
+ // 派生列的空值不是错误:数据还没到、字段本来就允许空,都会让它算不出来。
8
+ // 抛异常会让一整行渲染失败;返回 null 让那一格显示为空,其余照常。
9
+ // 这与四态资产的纪律一致——把「没有」画出来,而不是把页面炸掉。
10
+
11
+ import { ordinalOf, textOf } from './coerce';
12
+ import type { CalcAst } from './parser';
13
+
14
+ export function evaluateCalc(ast: CalcAst, values: Record<string, unknown>): unknown {
15
+ return evaluate(ast, values);
16
+ }
17
+
18
+ function evaluate(node: CalcAst, values: Record<string, unknown>): unknown {
19
+ switch (node.k) {
20
+ case 'num': return node.v;
21
+ case 'str': return node.v;
22
+ case 'bool': return node.v;
23
+ case 'date': return node.v;
24
+ case 'ref': return values[node.name] ?? null;
25
+
26
+ case 'un': {
27
+ const n = num(evaluate(node.arg, values));
28
+ return n === null ? null : -n;
29
+ }
30
+
31
+ case 'bin': {
32
+ const left = evaluate(node.left, values);
33
+ const right = evaluate(node.right, values);
34
+ switch (node.op) {
35
+ case '+': case '-': case '*': case '/': {
36
+ const a = num(left);
37
+ const b = num(right);
38
+ if (a === null || b === null) return null;
39
+ if (node.op === '+') return a + b;
40
+ if (node.op === '-') return a - b;
41
+ if (node.op === '*') return a * b;
42
+ // 除零返回 null 而不是 Infinity:Infinity 会一路流进 CONCAT 变成 "Infinity"
43
+ return b === 0 ? null : a / b;
44
+ }
45
+ case '>': case '>=': case '<': case '<=': {
46
+ const a = num(left);
47
+ const b = num(right);
48
+ if (a === null || b === null) return null;
49
+ if (node.op === '>') return a > b;
50
+ if (node.op === '>=') return a >= b;
51
+ if (node.op === '<') return a < b;
52
+ return a <= b;
53
+ }
54
+ case '==': case '!=': {
55
+ // 等值比较走字符串(与谓词图、form-rules 同一口径):
56
+ // 声明来自 YAML,enum 的 key 可能是数字也可能是字符串
57
+ const same = textOf(left) === textOf(right);
58
+ return node.op === '==' ? same : !same;
59
+ }
60
+ }
61
+ }
62
+
63
+ case 'call': {
64
+ switch (node.fn) {
65
+ case 'IF': {
66
+ const cond = evaluate(node.args[0], values);
67
+ // 条件算不出来时不猜分支——整条派生为空,比默认走 else 诚实
68
+ if (cond === null) return null;
69
+ return evaluate(node.args[cond === true ? 1 : 2], values);
70
+ }
71
+ case 'MIN': case 'MAX': {
72
+ const nums = node.args.map((arg) => num(evaluate(arg, values)));
73
+ if (nums.some((n) => n === null)) return null;
74
+ const list = nums as number[];
75
+ return node.fn === 'MIN' ? Math.min(...list) : Math.max(...list);
76
+ }
77
+ case 'ROUND': {
78
+ const value = num(evaluate(node.args[0], values));
79
+ if (value === null) return null;
80
+ const digits = node.args[1] ? Number((node.args[1] as { v: number }).v) : 0;
81
+ const factor = 10 ** digits;
82
+ // 先乘后除而不是 toFixed:toFixed 返回字符串,会让 number 型派生列悄悄变成 text
83
+ return Math.round(value * factor) / factor;
84
+ }
85
+ case 'ABS': {
86
+ const value = num(evaluate(node.args[0], values));
87
+ return value === null ? null : Math.abs(value);
88
+ }
89
+ case 'CONCAT': {
90
+ // 拼接里的 null 按空串:一段拼接不该因为其中一节没值就整体消失
91
+ return node.args.map((arg) => textOf(evaluate(arg, values))).join('');
92
+ }
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ /** 取数:复用与谓词图同一套数值/日期归一,保证「同一个值在两处判定一致」 */
99
+ function num(value: unknown): number | null {
100
+ return ordinalOf(value);
101
+ }
@@ -0,0 +1,12 @@
1
+ // calc 表达式层(REQ-010 S1a)——派生列与反应图 `value: { calc }` 的共同语言。
2
+ //
3
+ // 完整规格见 `prd/REQ-010-青出于蓝/模块类设计.md` L2.1(token 表 / 文法 / 类型规则 / 错误格式)。
4
+ // 一句话边界:**这不是表达式语言,是一张受限的算式表**——没有变量绑定、没有循环、
5
+ // 没有用户函数,函数名是六个的封闭集。想加第七个必须走需求文档,不许在 lexer 里顺手加。
6
+
7
+ export { SomaCalcSyntaxError, SomaCalcTypeError, type CalcSpan } from './errors';
8
+ export { tokenize, parseDateLiteral, CALC_FUNCTIONS, type CalcToken, type CalcTokenKind, type CalcFunctionName } from './lexer';
9
+ export { parseCalc, collectCalcRefs, type CalcAst, type CalcBinaryOp } from './parser';
10
+ export { inferCalcType, assertCalcResultType, type CalcType, type CalcTypeContext } from './typer';
11
+ export { evaluateCalc } from './evaluator';
12
+ export { ordinalOf, textOf } from './coerce';
@@ -0,0 +1,194 @@
1
+ // calc 词法分析(REQ-010 S1a)。
2
+ //
3
+ // 表外的任何字符**立即报错**,绝不跳过——一个被静默忽略的字符会让
4
+ // `[a] & [b]` 变成 `[a] [b]`,然后在语法分析里报一句莫名其妙的「意外的 REF」。
5
+ // 越早报错,错误信息离真正的原因越近。
6
+ //
7
+ // 三个刻意的词法决定:
8
+ // 1. **日期字面量用井号包裹** `#2026-09-04#`。不包裹的话 `2026-09-04` 与
9
+ // 「2026 减 9 减 4」在词法上无法区分——这不是能靠优先级解决的歧义。
10
+ // 2. **字符串只认双引号**。声明住在 YAML 里,单引号是 YAML 自己的引号;
11
+ // 让 calc 也认单引号,作者就要同时在脑子里跑两套引号规则。
12
+ // 3. **函数名只认大写的那六个**。任何其它标识符都是错——不给「以后可能加」留口子,
13
+ // 因为一个能写任意标识符的词法器,下一步必然被要求支持「调用自定义函数」。
14
+
15
+ import { SomaCalcSyntaxError, type CalcSpan } from './errors';
16
+
17
+ export type CalcTokenKind =
18
+ | 'number' | 'string' | 'date' | 'bool' | 'ref' | 'ident'
19
+ | 'op' | 'lparen' | 'rparen' | 'comma' | 'eof';
20
+
21
+ export interface CalcToken {
22
+ kind: CalcTokenKind;
23
+ /** number → 数值;string → 已去引号去转义的文本;date → UTC 毫秒;bool → 布尔;
24
+ * ref → 字段名;ident → 函数名;op → 运算符原文 */
25
+ value: string | number | boolean;
26
+ pos: CalcSpan;
27
+ }
28
+
29
+ /** 六个函数名——封闭集。新增必须走需求文档,不许在这里顺手加 */
30
+ export const CALC_FUNCTIONS = ['IF', 'MIN', 'MAX', 'ROUND', 'CONCAT', 'ABS'] as const;
31
+ export type CalcFunctionName = typeof CALC_FUNCTIONS[number];
32
+
33
+ /** 运算符——按长度降序排列,保证 `>=` 先于 `>` 匹配 */
34
+ const OPERATORS = ['>=', '<=', '==', '!=', '+', '-', '*', '/', '>', '<'] as const;
35
+
36
+ const IDENT_START = /[A-Za-z_]/;
37
+ const IDENT_PART = /[A-Za-z0-9_]/;
38
+ const DIGIT = /[0-9]/;
39
+
40
+ export function tokenize(source: string): CalcToken[] {
41
+ const tokens: CalcToken[] = [];
42
+ let i = 0;
43
+
44
+ const fail: (message: string, from: number, to: number) => never = (message, from, to) => {
45
+ throw new SomaCalcSyntaxError(message, source, [from, to] as CalcSpan);
46
+ };
47
+
48
+ while (i < source.length) {
49
+ const char = source[i];
50
+
51
+ // 空白:只认空格与制表;换行不该出现在一行 YAML 标量里,出现了多半是块标量写错了
52
+ if (char === ' ' || char === '\t') { i += 1; continue; }
53
+ if (char === '\n' || char === '\r') {
54
+ fail('表达式不能换行(它是一个 YAML 标量,不是块)', i, i + 1);
55
+ }
56
+
57
+ const start = i;
58
+
59
+ // 字段引用 [name]
60
+ if (char === '[') {
61
+ i += 1;
62
+ const nameStart = i;
63
+ while (i < source.length && source[i] !== ']') i += 1;
64
+ if (i >= source.length) fail('字段引用缺少闭合的 "]"', start, source.length);
65
+ const name = source.slice(nameStart, i);
66
+ i += 1; // 吃掉 ]
67
+ if (name === '') fail('字段引用不能为空(写成 [字段名])', start, i);
68
+ if (!IDENT_START.test(name[0]) || ![...name].every((c) => IDENT_PART.test(c))) {
69
+ fail(`字段名 "${name}" 必须是标识符(字母或下划线开头);派生列只能引用同层字段,不支持 . 深取`, start, i);
70
+ }
71
+ tokens.push({ kind: 'ref', value: name, pos: [start, i] });
72
+ continue;
73
+ }
74
+
75
+ // 日期字面量 #YYYY-MM-DD# / #YYYY-MM-DDTHH:mm#
76
+ if (char === '#') {
77
+ i += 1;
78
+ const textStart = i;
79
+ while (i < source.length && source[i] !== '#') i += 1;
80
+ if (i >= source.length) fail('日期字面量缺少闭合的 "#"', start, source.length);
81
+ const text = source.slice(textStart, i);
82
+ i += 1;
83
+ const ms = parseDateLiteral(text);
84
+ if (ms === null) {
85
+ fail(`日期字面量 "${text}" 不合法(只认 #YYYY-MM-DD# 与 #YYYY-MM-DDTHH:mm#)`, start, i);
86
+ }
87
+ tokens.push({ kind: 'date', value: ms, pos: [start, i] });
88
+ continue;
89
+ }
90
+
91
+ // 字符串 "…"
92
+ if (char === '"') {
93
+ i += 1;
94
+ let text = '';
95
+ while (i < source.length && source[i] !== '"') {
96
+ if (source[i] === '\n') fail('字符串不能跨行', start, i);
97
+ if (source[i] === '\\') {
98
+ const next = source[i + 1];
99
+ if (next !== '"' && next !== '\\') {
100
+ fail(`字符串里只允许 \\" 与 \\\\ 两种转义,收到 "\\${String(next ?? '')}"`, i, i + 2);
101
+ }
102
+ text += next;
103
+ i += 2;
104
+ continue;
105
+ }
106
+ text += source[i];
107
+ i += 1;
108
+ }
109
+ if (i >= source.length) fail('字符串缺少闭合的双引号', start, source.length);
110
+ i += 1;
111
+ tokens.push({ kind: 'string', value: text, pos: [start, i] });
112
+ continue;
113
+ }
114
+
115
+ // 数字(无指数、无前导正号——`-` 一律是一元算子)
116
+ if (DIGIT.test(char)) {
117
+ while (i < source.length && DIGIT.test(source[i])) i += 1;
118
+ if (source[i] === '.') {
119
+ i += 1;
120
+ if (!DIGIT.test(source[i] ?? '')) fail('小数点后缺少数字', start, i + 1);
121
+ while (i < source.length && DIGIT.test(source[i])) i += 1;
122
+ }
123
+ if (source[i] === 'e' || source[i] === 'E') {
124
+ fail('不支持科学计数法——派生列的数值应当是人能一眼读懂的字面量', start, i + 1);
125
+ }
126
+ tokens.push({ kind: 'number', value: Number(source.slice(start, i)), pos: [start, i] });
127
+ continue;
128
+ }
129
+
130
+ // 标识符:true / false / 六个函数名;其余一律错
131
+ if (IDENT_START.test(char)) {
132
+ while (i < source.length && IDENT_PART.test(source[i])) i += 1;
133
+ const word = source.slice(start, i);
134
+ if (word === 'true' || word === 'false') {
135
+ tokens.push({ kind: 'bool', value: word === 'true', pos: [start, i] });
136
+ continue;
137
+ }
138
+ if ((CALC_FUNCTIONS as readonly string[]).includes(word)) {
139
+ tokens.push({ kind: 'ident', value: word, pos: [start, i] });
140
+ continue;
141
+ }
142
+ fail(
143
+ `未知的标识符 "${word}"。字段要写成 [${word}];函数只有 ${CALC_FUNCTIONS.join(' / ')}`,
144
+ start, i,
145
+ );
146
+ }
147
+
148
+ if (char === '(') { tokens.push({ kind: 'lparen', value: '(', pos: [start, i + 1] }); i += 1; continue; }
149
+ if (char === ')') { tokens.push({ kind: 'rparen', value: ')', pos: [start, i + 1] }); i += 1; continue; }
150
+ if (char === ',') { tokens.push({ kind: 'comma', value: ',', pos: [start, i + 1] }); i += 1; continue; }
151
+
152
+ const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
153
+ if (op) {
154
+ i += op.length;
155
+ tokens.push({ kind: 'op', value: op, pos: [start, i] });
156
+ continue;
157
+ }
158
+
159
+ // 单独的 = & | ! 最容易被误写,专门给一句能直接改的提示
160
+ const hint = char === '=' ? '判断相等要写 =='
161
+ : char === '&' ? '并且要写成 IF 的嵌套;calc 不支持逻辑运算符'
162
+ : char === '|' ? '或者要写成 IF 的嵌套;calc 不支持逻辑运算符'
163
+ : char === '!' ? '不等要写 !='
164
+ : char === "'" ? '字符串要用双引号(单引号是 YAML 的引号)'
165
+ : '它不在 calc 的词法表里';
166
+ fail(`无法识别的字符 "${char}"——${hint}`, start, i + 1);
167
+ }
168
+
169
+ tokens.push({ kind: 'eof', value: '', pos: [source.length, source.length] });
170
+ return tokens;
171
+ }
172
+
173
+ /**
174
+ * 日期字面量 → UTC 毫秒。
175
+ *
176
+ * 用 `Date.UTC` 而不是 `Date.parse`:后者对无时区的串在各引擎上曾有本地/UTC 之争,
177
+ * 而派生列的日期比较必须在任何机器上给同一个答案。
178
+ */
179
+ export function parseDateLiteral(text: string): number | null {
180
+ const match = text.match(/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?$/);
181
+ if (!match) return null;
182
+ const [, y, mo, d, h, mi] = match;
183
+ const year = Number(y);
184
+ const month = Number(mo);
185
+ const day = Number(d);
186
+ const hour = h === undefined ? 0 : Number(h);
187
+ const minute = mi === undefined ? 0 : Number(mi);
188
+ if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return null;
189
+ const ms = Date.UTC(year, month - 1, day, hour, minute);
190
+ // 回读校验:2026-02-31 会被 Date.UTC 滚成 3 月 3 日,这里把它挡回去
191
+ const back = new Date(ms);
192
+ if (back.getUTCMonth() !== month - 1 || back.getUTCDate() !== day) return null;
193
+ return ms;
194
+ }
@@ -0,0 +1,204 @@
1
+ // calc 语法分析(REQ-010 S1a)——递归下降,**不是 eval**。
2
+ //
3
+ // 为什么值得自己写一个解析器:AG Grid 的 `calculatedExpression`(`"[revenue] - [cost]"`、
4
+ // `'IF([margin] >= 0.25, "Healthy", "Review")'`)证明了一件事——受限表达式串足以覆盖
5
+ // 绝大多数派生列需求,而它天然只读、可序列化、可入状态。SOMA 的 DSL 刻意不图灵完备
6
+ // (`verify:no-eval` 是硬闸门),所以「给个函数」这条路从一开始就不通;但「完全不给派生列」
7
+ // 又会把 `1280 → "¥1,280.00"` 这类格式化逼回 Domain,于是排序按字符串排、导出带货币符号。
8
+ // 递归下降解析器是这两难之间唯一的正解:能力够用,且产物是可静态检查的 AST。
9
+ //
10
+ // ── 两条刻意的语法限制 ────────────────────────────────────────────────
11
+ // 1. **比较不可链**:`a < b < c` 是语法错,不是 `(a<b)<c`。C 系语言里这个表达式合法但
12
+ // 几乎总是写错了意思,而我们没有理由继承一个人人都要防的坑。
13
+ // 2. **比较只能出现在 IF 的第一参**(由 typer 判定,不在文法里限制):一个求值为 bool 的
14
+ // 派生列没有意义——字段类型里没有「显示 true」这种业务语义。
15
+ //
16
+ // 文法(左结合):
17
+ // calc := cmp
18
+ // cmp := sum (('>'|'>='|'<'|'<='|'=='|'!=') sum)?
19
+ // sum := product (('+'|'-') product)*
20
+ // product := unary (('*'|'/') unary)*
21
+ // unary := '-' unary | primary
22
+ // primary := NUMBER | STRING | DATE | BOOL | REF | call | '(' calc ')'
23
+ // call := IF '(' calc ',' calc ',' calc ')'
24
+ // | MIN '(' calc (',' calc)+ ')' | MAX '(' calc (',' calc)+ ')'
25
+ // | ROUND '(' calc (',' NUMBER)? ')'
26
+ // | CONCAT '(' calc (',' calc)+ ')'
27
+ // | ABS '(' calc ')'
28
+
29
+ import { SomaCalcSyntaxError, type CalcSpan } from './errors';
30
+ import { tokenize, type CalcFunctionName, type CalcToken } from './lexer';
31
+
32
+ export type CalcBinaryOp = '+' | '-' | '*' | '/' | '>' | '>=' | '<' | '<=' | '==' | '!=';
33
+
34
+ export type CalcAst =
35
+ | { k: 'num'; v: number; pos: CalcSpan }
36
+ | { k: 'str'; v: string; pos: CalcSpan }
37
+ | { k: 'date'; v: number; pos: CalcSpan }
38
+ | { k: 'bool'; v: boolean; pos: CalcSpan }
39
+ | { k: 'ref'; name: string; pos: CalcSpan }
40
+ | { k: 'un'; op: '-'; arg: CalcAst; pos: CalcSpan }
41
+ | { k: 'bin'; op: CalcBinaryOp; left: CalcAst; right: CalcAst; pos: CalcSpan }
42
+ | { k: 'call'; fn: CalcFunctionName; args: CalcAst[]; pos: CalcSpan };
43
+
44
+ const CMP_OPS: readonly string[] = ['>', '>=', '<', '<=', '==', '!='];
45
+
46
+ /** 每个函数的参数个数约束:[最少, 最多],Infinity = 不限 */
47
+ const ARITY: Readonly<Record<CalcFunctionName, readonly [number, number]>> = {
48
+ IF: [3, 3],
49
+ MIN: [2, Infinity],
50
+ MAX: [2, Infinity],
51
+ ROUND: [1, 2],
52
+ CONCAT: [2, Infinity],
53
+ ABS: [1, 1],
54
+ };
55
+
56
+ export function parseCalc(source: string): CalcAst {
57
+ const tokens = tokenize(source);
58
+ let at = 0;
59
+
60
+ const peek = (): CalcToken => tokens[at];
61
+ const next = (): CalcToken => tokens[at++];
62
+ const fail = (message: string, token: CalcToken): never => {
63
+ throw new SomaCalcSyntaxError(message, source, token.pos);
64
+ };
65
+ const expect = (kind: CalcToken['kind'], what: string): CalcToken => {
66
+ const token = peek();
67
+ if (token.kind !== kind) fail(`缺少${what}`, token);
68
+ return next();
69
+ };
70
+
71
+ const parseCmp = (): CalcAst => {
72
+ const left = parseSum();
73
+ const token = peek();
74
+ if (token.kind === 'op' && CMP_OPS.includes(String(token.value))) {
75
+ next();
76
+ const right = parseSum();
77
+ const after = peek();
78
+ if (after.kind === 'op' && CMP_OPS.includes(String(after.value))) {
79
+ fail('比较不能连写(a < b < c 几乎总是写错了意思)——请拆成两个 IF 或改用 between 谓词', after);
80
+ }
81
+ return { k: 'bin', op: String(token.value) as CalcBinaryOp, left, right, pos: [left.pos[0], right.pos[1]] };
82
+ }
83
+ return left;
84
+ };
85
+
86
+ const parseSum = (): CalcAst => {
87
+ let node = parseProduct();
88
+ for (;;) {
89
+ const token = peek();
90
+ if (token.kind !== 'op' || (token.value !== '+' && token.value !== '-')) return node;
91
+ next();
92
+ const right = parseProduct();
93
+ node = { k: 'bin', op: token.value, left: node, right, pos: [node.pos[0], right.pos[1]] };
94
+ }
95
+ };
96
+
97
+ const parseProduct = (): CalcAst => {
98
+ let node = parseUnary();
99
+ for (;;) {
100
+ const token = peek();
101
+ if (token.kind !== 'op' || (token.value !== '*' && token.value !== '/')) return node;
102
+ next();
103
+ const right = parseUnary();
104
+ node = { k: 'bin', op: token.value, left: node, right, pos: [node.pos[0], right.pos[1]] };
105
+ }
106
+ };
107
+
108
+ const parseUnary = (): CalcAst => {
109
+ const token = peek();
110
+ if (token.kind === 'op' && token.value === '-') {
111
+ next();
112
+ const arg = parseUnary();
113
+ return { k: 'un', op: '-', arg, pos: [token.pos[0], arg.pos[1]] };
114
+ }
115
+ return parsePrimary();
116
+ };
117
+
118
+ const parsePrimary = (): CalcAst => {
119
+ const token = next();
120
+ switch (token.kind) {
121
+ case 'number': return { k: 'num', v: token.value as number, pos: token.pos };
122
+ case 'string': return { k: 'str', v: token.value as string, pos: token.pos };
123
+ case 'date': return { k: 'date', v: token.value as number, pos: token.pos };
124
+ case 'bool': return { k: 'bool', v: token.value as boolean, pos: token.pos };
125
+ case 'ref': return { k: 'ref', name: token.value as string, pos: token.pos };
126
+ case 'lparen': {
127
+ const inner = parseCmp();
128
+ expect('rparen', '右括号 ")"');
129
+ return inner;
130
+ }
131
+ case 'ident': return parseCall(token);
132
+ case 'op':
133
+ return fail(`运算符 "${String(token.value)}" 前面缺少操作数`, token);
134
+ case 'eof':
135
+ return fail('表达式不完整', token);
136
+ default:
137
+ return fail(`意外的 "${String(token.value)}"`, token);
138
+ }
139
+ };
140
+
141
+ const parseCall = (name: CalcToken): CalcAst => {
142
+ const fn = name.value as CalcFunctionName;
143
+ expect('lparen', `${fn} 后的左括号 "("`);
144
+ const args: CalcAst[] = [];
145
+
146
+ // ROUND 的第二参必须是字面量整数(精度不能是算出来的——那会让类型推导无从谈起)
147
+ if (peek().kind !== 'rparen') {
148
+ args.push(parseCmp());
149
+ while (peek().kind === 'comma') {
150
+ next();
151
+ if (fn === 'ROUND' && args.length === 1) {
152
+ const digits = peek();
153
+ if (digits.kind !== 'number' || !Number.isInteger(digits.value) || (digits.value as number) < 0 || (digits.value as number) > 6) {
154
+ fail('ROUND 的第二参必须是 0~6 的整数字面量', digits);
155
+ }
156
+ next();
157
+ args.push({ k: 'num', v: digits.value as number, pos: digits.pos });
158
+ continue;
159
+ }
160
+ args.push(parseCmp());
161
+ }
162
+ }
163
+ const close = expect('rparen', `${fn} 的右括号 ")"`);
164
+
165
+ const [min, max] = ARITY[fn];
166
+ if (args.length < min || args.length > max) {
167
+ const want = max === Infinity ? `至少 ${min} 个` : (min === max ? `${min} 个` : `${min}~${max} 个`);
168
+ fail(`${fn} 需要${want}参数,收到 ${args.length} 个`, name);
169
+ }
170
+ return { k: 'call', fn, args, pos: [name.pos[0], close.pos[1]] };
171
+ };
172
+
173
+ const ast = parseCmp();
174
+ const rest = peek();
175
+ if (rest.kind !== 'eof') {
176
+ fail(`表达式在这里就结束了,后面的 "${String(rest.value)}" 是多余的`, rest);
177
+ }
178
+ return ast;
179
+ }
180
+
181
+ /**
182
+ * 收集表达式引用的字段名(去重、首次出现序)。
183
+ *
184
+ * 这是 RG 反应图建 DAG 的原料之一:`total: { calc: "[amount] - [discount]" }`
185
+ * 的入边就是 `amount` 与 `discount`。Formily / amis 的依赖靠运行时收集,
186
+ * 所以它们建不出这张图——这个函数是那条结构性差异的落点。
187
+ */
188
+ export function collectCalcRefs(ast: CalcAst): string[] {
189
+ const out: string[] = [];
190
+ const seen = new Set<string>();
191
+ const walk = (node: CalcAst): void => {
192
+ switch (node.k) {
193
+ case 'ref':
194
+ if (!seen.has(node.name)) { seen.add(node.name); out.push(node.name); }
195
+ return;
196
+ case 'un': walk(node.arg); return;
197
+ case 'bin': walk(node.left); walk(node.right); return;
198
+ case 'call': node.args.forEach(walk); return;
199
+ default: return;
200
+ }
201
+ };
202
+ walk(ast);
203
+ return out;
204
+ }