soma-core 1.3.5 → 1.4.1
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.
- package/README.md +20 -7
- package/app/SomaPageClient.tsx +4 -4
- package/app/components/SomaHostPage.tsx +5 -5
- package/app/components/SomaHydrationShell.tsx +4 -7
- package/app/globals.css +126 -3
- package/core/build/{v2 → blocks}/block-compile.ts +47 -18
- package/core/build/{v2/soma-file-loader.ts → blocks/block-container.ts} +28 -37
- package/core/build/{v2 → blocks}/block-loader.ts +1 -1
- package/core/build/{v2 → blocks}/html-index.ts +1 -1
- package/core/build/{v2/migrate-v1.ts → blocks/migrate-flat.ts} +27 -27
- package/core/build/compiler/host-config-sync.cjs +2 -9
- package/core/build/compiler/page-declaration-compiler.ts +32 -4
- package/core/build/compiler/soma-manifest-webpack-plugin.js +1 -1
- package/core/build/compiler/soma-precompile.js +2057 -35
- package/core/build/compiler/soma-precompile.ts +2 -2
- package/core/build/component/component-graph.ts +208 -0
- package/core/build/eject/component-eject.ts +473 -0
- package/core/build/eject/component-upgrade.ts +359 -0
- package/core/build/layout/constraint-solver.ts +235 -0
- package/core/build/layout/css-emitter.ts +116 -0
- package/core/build/layout/page-layout.ts +85 -0
- package/core/build/pack/pack-init.ts +265 -0
- package/core/client/base/SomaPageRootBase.ts +61 -0
- package/core/client/component/ai-catalog.ts +83 -8
- package/core/client/component/component-defaults.ts +100 -0
- package/core/client/component/component-definition.types.ts +39 -0
- package/core/client/component/component-manager.ts +79 -4
- package/core/client/component/component-pack.ts +126 -2
- package/core/client/component/contract-compat.ts +32 -3
- package/core/client/component/{example-v2.ts → example-blocks.ts} +19 -19
- package/core/client/component/keyboard-matrix.ts +144 -0
- package/core/client/component/pack-styles.ts +59 -1
- package/core/client/component/style-features.ts +131 -0
- package/core/client/component/theme-component-tokens.ts +83 -0
- package/core/client/data/data-object-resolver.ts +407 -4
- package/core/client/data/reaction-engine.ts +176 -0
- package/core/client/data/window-engine.ts +477 -0
- package/core/client/engine/event-engine.ts +98 -0
- package/core/client/engine/soma-bootstrap.ts +286 -7
- package/core/client/engine/step-runner.ts +134 -0
- package/core/client/engine/style-binder.ts +1 -1
- package/core/client/infra/notify/DomNotifyService.ts +2 -1
- package/core/client/infra/notify/INotifyTheme.ts +1 -1
- package/core/client/parser/{v2 → blocks}/namespace.ts +1 -1
- package/core/client/parser/{v2 → blocks}/page-parser.ts +30 -16
- package/core/client/parser/{v2 → blocks}/use-parser.ts +24 -25
- package/core/client/parser/data-config-parser.ts +316 -8
- package/core/client/parser/duration.ts +16 -0
- package/core/client/parser/layout-parser.ts +157 -0
- package/core/client/parser/page-state-parser.ts +166 -0
- package/core/client/parser/pipeline-parser.ts +76 -1
- package/core/client/parser/reaction-parser.ts +459 -0
- package/core/client/parser/reaction-sugar.ts +47 -0
- package/core/client/parser/step-parser.ts +359 -0
- package/core/client/parser/style-config-parser.ts +7 -7
- package/core/client/parser/ui-config-parser.ts +59 -0
- package/core/client/parser/value-lang.ts +1 -1
- package/core/client/parser/window-parser.ts +294 -0
- package/core/client/registry/index.ts +8 -0
- package/core/client/theme/theme-engine.ts +144 -16
- package/core/client/typography/typography-base.ts +1 -1
- package/core/index.ts +188 -13
- package/core/server/host/csp-nonce-metadata.ts +1 -1
- package/core/server/host/published-page-assets.ts +3 -8
- package/core/server/host/soma-page-compile.ts +1 -1
- package/core/server/index.ts +2 -2
- package/core/shared/block-errors.ts +11 -0
- package/core/shared/calc/coerce.ts +29 -0
- package/core/shared/calc/errors.ts +43 -0
- package/core/shared/calc/evaluator.ts +101 -0
- package/core/shared/calc/index.ts +12 -0
- package/core/shared/calc/lexer.ts +194 -0
- package/core/shared/calc/parser.ts +204 -0
- package/core/shared/calc/typer.ts +184 -0
- package/core/shared/path-algebra.ts +169 -0
- package/core/shared/predicates/index.ts +527 -0
- package/core/shared/published-page-route.ts +61 -0
- package/core/shared/types/adaptive.types.ts +1 -1
- package/core/shared/types/component-contract.types.ts +128 -2
- package/core/shared/types/data-config.types.ts +149 -2
- package/core/shared/types/domain.types.ts +13 -0
- package/core/shared/types/event.types.ts +22 -2
- package/core/shared/types/layout-constraint.types.ts +73 -0
- package/core/shared/types/page-state.types.ts +60 -0
- package/core/shared/types/reaction.types.ts +144 -0
- package/core/shared/types/scope-manifest.types.ts +11 -15
- package/core/shared/types/step.types.ts +91 -0
- package/core/shared/types/style-config.types.ts +4 -4
- package/core/shared/types/ui-config.types.ts +18 -0
- package/core/shared/types/window.types.ts +177 -0
- package/dist/cli/soma.js +28 -3
- package/dist/core/index.cjs +4829 -405
- package/dist/types/build/{v2 → blocks}/block-compile.d.ts +7 -7
- package/dist/types/build/{v2/soma-file-loader.d.ts → blocks/block-container.d.ts} +6 -11
- package/dist/types/build/{v2/migrate-v1.d.ts → blocks/migrate-flat.d.ts} +6 -6
- package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
- package/dist/types/build/component/component-graph.d.ts +85 -0
- package/dist/types/build/eject/component-eject.d.ts +121 -0
- package/dist/types/build/eject/component-upgrade.d.ts +43 -0
- package/dist/types/build/layout/constraint-solver.d.ts +36 -0
- package/dist/types/build/layout/css-emitter.d.ts +18 -0
- package/dist/types/build/layout/page-layout.d.ts +24 -0
- package/dist/types/build/pack/pack-init.d.ts +8 -0
- package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
- package/dist/types/client/component/ai-catalog.d.ts +24 -1
- package/dist/types/client/component/component-defaults.d.ts +15 -0
- package/dist/types/client/component/component-definition.types.d.ts +38 -0
- package/dist/types/client/component/component-manager.d.ts +36 -0
- package/dist/types/client/component/component-pack.d.ts +32 -2
- package/dist/types/client/component/contract-compat.d.ts +2 -2
- package/dist/types/client/component/example-blocks.d.ts +9 -0
- package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
- package/dist/types/client/component/pack-styles.d.ts +21 -0
- package/dist/types/client/component/style-features.d.ts +26 -0
- package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
- package/dist/types/client/data/data-object-resolver.d.ts +106 -1
- package/dist/types/client/data/reaction-engine.d.ts +21 -0
- package/dist/types/client/data/window-engine.d.ts +27 -0
- package/dist/types/client/engine/event-engine.d.ts +15 -0
- package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
- package/dist/types/client/engine/step-runner.d.ts +24 -0
- package/dist/types/client/infra/notify/DomNotifyService.d.ts +2 -1
- package/dist/types/client/infra/notify/INotifyTheme.d.ts +1 -1
- package/dist/types/client/parser/{v2 → blocks}/page-parser.d.ts +2 -2
- package/dist/types/client/parser/{v2 → blocks}/use-parser.d.ts +3 -3
- package/dist/types/client/parser/duration.d.ts +1 -0
- package/dist/types/client/parser/layout-parser.d.ts +9 -0
- package/dist/types/client/parser/page-state-parser.d.ts +32 -0
- package/dist/types/client/parser/reaction-parser.d.ts +16 -0
- package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
- package/dist/types/client/parser/step-parser.d.ts +23 -0
- package/dist/types/client/parser/style-config-parser.d.ts +1 -1
- package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
- package/dist/types/client/parser/window-parser.d.ts +25 -0
- package/dist/types/client/registry/index.d.ts +1 -0
- package/dist/types/client/theme/theme-engine.d.ts +37 -0
- package/dist/types/index.d.ts +40 -9
- package/dist/types/server/host/published-page-assets.d.ts +3 -2
- package/dist/types/server/index.d.ts +1 -1
- package/dist/types/shared/block-errors.d.ts +5 -0
- package/dist/types/shared/calc/coerce.d.ts +4 -0
- package/dist/types/shared/calc/errors.d.ts +14 -0
- package/dist/types/shared/calc/evaluator.d.ts +2 -0
- package/dist/types/shared/calc/index.d.ts +6 -0
- package/dist/types/shared/calc/lexer.d.ts +20 -0
- package/dist/types/shared/calc/parser.d.ts +49 -0
- package/dist/types/shared/calc/typer.d.ts +16 -0
- package/dist/types/shared/path-algebra.d.ts +56 -0
- package/dist/types/shared/predicates/index.d.ts +79 -0
- package/dist/types/shared/published-page-route.d.ts +21 -0
- package/dist/types/shared/types/component-contract.types.d.ts +112 -0
- package/dist/types/shared/types/data-config.types.d.ts +132 -2
- package/dist/types/shared/types/domain.types.d.ts +12 -0
- package/dist/types/shared/types/event.types.d.ts +8 -2
- package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
- package/dist/types/shared/types/page-state.types.d.ts +49 -0
- package/dist/types/shared/types/reaction.types.d.ts +115 -0
- package/dist/types/shared/types/scope-manifest.types.d.ts +11 -11
- package/dist/types/shared/types/step.types.d.ts +76 -0
- package/dist/types/shared/types/style-config.types.d.ts +4 -4
- package/dist/types/shared/types/ui-config.types.d.ts +18 -0
- package/dist/types/shared/types/window.types.d.ts +171 -0
- package/package.json +2 -6
- package/dist/types/client/component/example-v2.d.ts +0 -9
- package/postcss.config.js +0 -6
- package/tailwind.config.ts +0 -43
- /package/dist/types/build/{v2 → blocks}/block-loader.d.ts +0 -0
- /package/dist/types/build/{v2 → blocks}/html-index.d.ts +0 -0
- /package/dist/types/client/parser/{v2 → blocks}/namespace.d.ts +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// calc 类型推导(REQ-010 S1a)——本层是 calc 存在的最大理由。
|
|
2
|
+
//
|
|
3
|
+
// JsonLogic 的 `var` 路径是自由字符串、Formily 的表达式在 `new Function` 里跑、
|
|
4
|
+
// amis 的 `${}` 沿运行时数据链求值——三家都**无法在声明期知道一个表达式算出来是什么类型**,
|
|
5
|
+
// 于是 `[amount] - [note]`(金额减备注)这种错只会在页面上显示成 `NaN`,
|
|
6
|
+
// 而且显示 NaN 的那一刻离写错的地方已经隔了很远。
|
|
7
|
+
//
|
|
8
|
+
// SOMA 的字段类型是字典里的封闭枚举,所以这件事可以在解析期做完:
|
|
9
|
+
// 每个节点推出类型,与字段声明的 `type` 对账,不配就当场点名到列号。
|
|
10
|
+
//
|
|
11
|
+
// ── 一条刻意的收紧 ────────────────────────────────────────────────────
|
|
12
|
+
// `date - date → number`(毫秒差)是有用的(算时长),但 `date + date` 无意义,
|
|
13
|
+
// `date * 2` 更无意义——所以日期的算术只开了「差」与「加减一个数」两扇门。
|
|
14
|
+
|
|
15
|
+
import { SomaCalcTypeError } from './errors';
|
|
16
|
+
import type { CalcAst } from './parser';
|
|
17
|
+
|
|
18
|
+
export type CalcType = 'number' | 'text' | 'bool' | 'date';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 字段类型 → calc 类型。
|
|
22
|
+
*
|
|
23
|
+
* 表里没有的字段类型**不可被引用**:`richtext` 引用进算式没有意义(它是一段 HTML),
|
|
24
|
+
* `image / file` 是资源标识,`tags / tree / cascade` 是集合或路径。
|
|
25
|
+
* 与其让它们悄悄按 text 参与拼接,不如直接拒绝并让作者换个字段。
|
|
26
|
+
*/
|
|
27
|
+
const FIELD_TO_CALC: Readonly<Record<string, CalcType>> = {
|
|
28
|
+
int: 'number', float: 'number', money: 'number', percent: 'number', progress: 'number',
|
|
29
|
+
text: 'text', url: 'text', enum: 'text',
|
|
30
|
+
bool: 'bool',
|
|
31
|
+
date: 'date', datetime: 'date',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** calc 类型 → 允许声明的字段类型(用于结果与 `type` 对账) */
|
|
35
|
+
const CALC_TO_FIELD: Readonly<Record<CalcType, readonly string[]>> = {
|
|
36
|
+
number: ['int', 'float', 'money', 'percent', 'progress'],
|
|
37
|
+
text: ['text', 'url', 'enum'],
|
|
38
|
+
bool: ['bool'],
|
|
39
|
+
date: ['date', 'datetime'],
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export interface CalcTypeContext {
|
|
43
|
+
/** 字段名 → 字典里的 `type`(缺省视为 text,与字典本身的缺省一致) */
|
|
44
|
+
fieldTypes: Readonly<Record<string, string | undefined>>;
|
|
45
|
+
/** 原始表达式串,仅用于错误定位 */
|
|
46
|
+
source: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function inferCalcType(ast: CalcAst, ctx: CalcTypeContext): CalcType {
|
|
50
|
+
return infer(ast, ctx);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function infer(node: CalcAst, ctx: CalcTypeContext): CalcType {
|
|
54
|
+
const bad: (message: string, expected: string, actual: string) => never = (message, expected, actual) => {
|
|
55
|
+
throw new SomaCalcTypeError(message, ctx.source, node.pos, expected, actual);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
switch (node.k) {
|
|
59
|
+
case 'num': return 'number';
|
|
60
|
+
case 'str': return 'text';
|
|
61
|
+
case 'bool': return 'bool';
|
|
62
|
+
case 'date': return 'date';
|
|
63
|
+
|
|
64
|
+
case 'ref': {
|
|
65
|
+
const declared = ctx.fieldTypes[node.name];
|
|
66
|
+
if (declared === undefined && !(node.name in ctx.fieldTypes)) {
|
|
67
|
+
bad(`引用了不存在的字段 "${node.name}"`, '字典里的字段', '未声明');
|
|
68
|
+
}
|
|
69
|
+
const kind = FIELD_TO_CALC[declared ?? 'text'];
|
|
70
|
+
if (!kind) {
|
|
71
|
+
bad(
|
|
72
|
+
`字段 "${node.name}" 是 ${declared} 类型,不能参与计算`
|
|
73
|
+
+ `(可引用的类型:${Object.keys(FIELD_TO_CALC).join(' / ')})`,
|
|
74
|
+
'可计算的字段类型', String(declared),
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return kind;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
case 'un': {
|
|
81
|
+
const inner = infer(node.arg, ctx);
|
|
82
|
+
if (inner !== 'number') bad('取负只能作用在数值上', 'number', inner);
|
|
83
|
+
return 'number';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
case 'bin': {
|
|
87
|
+
const left = infer(node.left, ctx);
|
|
88
|
+
const right = infer(node.right, ctx);
|
|
89
|
+
switch (node.op) {
|
|
90
|
+
case '+': case '-': {
|
|
91
|
+
if (left === 'number' && right === 'number') return 'number';
|
|
92
|
+
if (node.op === '-' && left === 'date' && right === 'date') return 'number'; // 毫秒差
|
|
93
|
+
if (left === 'date' && right === 'number') return 'date'; // 日期 ± 天数(毫秒)
|
|
94
|
+
if (node.op === '+' && left === 'number' && right === 'date') return 'date';
|
|
95
|
+
// 建议要对得上运算符:对减法说「请用 CONCAT」是句错话,
|
|
96
|
+
// 作者照做只会得到第二个错误。只有 + 才可能是「想拼接」写错了。
|
|
97
|
+
if (node.op === '+' && (left === 'text' || right === 'text')) {
|
|
98
|
+
bad('文本不能用 + 拼接——请用 CONCAT(a, b)', 'number 或 date', `${left} 与 ${right}`);
|
|
99
|
+
}
|
|
100
|
+
return bad(`${node.op} 不能作用在 ${left} 与 ${right} 上`, 'number', `${left} 与 ${right}`);
|
|
101
|
+
}
|
|
102
|
+
case '*': case '/': {
|
|
103
|
+
if (left === 'number' && right === 'number') return 'number';
|
|
104
|
+
return bad(`${node.op} 只能作用在数值上`, 'number', `${left} 与 ${right}`);
|
|
105
|
+
}
|
|
106
|
+
case '>': case '>=': case '<': case '<=': {
|
|
107
|
+
if (left === right && (left === 'number' || left === 'date')) return 'bool';
|
|
108
|
+
return bad('比较大小只能在两个数值之间或两个日期之间', '同为 number 或同为 date', `${left} 与 ${right}`);
|
|
109
|
+
}
|
|
110
|
+
case '==': case '!=': {
|
|
111
|
+
if (left === right) return 'bool';
|
|
112
|
+
return bad('相等比较的两侧必须同型', left, right);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
case 'call': {
|
|
118
|
+
switch (node.fn) {
|
|
119
|
+
case 'IF': {
|
|
120
|
+
const cond = infer(node.args[0], ctx);
|
|
121
|
+
if (cond !== 'bool') bad('IF 的第一个参数必须是判断(比较或布尔字段)', 'bool', cond);
|
|
122
|
+
const a = infer(node.args[1], ctx);
|
|
123
|
+
const b = infer(node.args[2], ctx);
|
|
124
|
+
if (a !== b) bad('IF 的两个分支必须同型', a, b);
|
|
125
|
+
return a;
|
|
126
|
+
}
|
|
127
|
+
case 'MIN': case 'MAX': {
|
|
128
|
+
const kinds = node.args.map((arg) => infer(arg, ctx));
|
|
129
|
+
const first = kinds[0];
|
|
130
|
+
if (first !== 'number' && first !== 'date') {
|
|
131
|
+
bad(`${node.fn} 只能作用在数值或日期上`, 'number 或 date', first);
|
|
132
|
+
}
|
|
133
|
+
const off = kinds.find((kind) => kind !== first);
|
|
134
|
+
if (off) bad(`${node.fn} 的参数必须同型`, first, off);
|
|
135
|
+
return first;
|
|
136
|
+
}
|
|
137
|
+
case 'ROUND': {
|
|
138
|
+
const value = infer(node.args[0], ctx);
|
|
139
|
+
if (value !== 'number') bad('ROUND 只能作用在数值上', 'number', value);
|
|
140
|
+
return 'number';
|
|
141
|
+
}
|
|
142
|
+
case 'ABS': {
|
|
143
|
+
const value = infer(node.args[0], ctx);
|
|
144
|
+
if (value !== 'number') bad('ABS 只能作用在数值上', 'number', value);
|
|
145
|
+
return 'number';
|
|
146
|
+
}
|
|
147
|
+
case 'CONCAT': {
|
|
148
|
+
node.args.forEach((arg) => infer(arg, ctx)); // 任意型,逐个求值即可(错在里面照样点名)
|
|
149
|
+
return 'text';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 与字段声明的 `type` 对账。
|
|
158
|
+
*
|
|
159
|
+
* 单独一个函数而不是塞进 `infer`:解析器可能被用在「只想知道类型」的场合
|
|
160
|
+
* (如 DW 的派生列预览),那时还没有目标字段。
|
|
161
|
+
*/
|
|
162
|
+
export function assertCalcResultType(
|
|
163
|
+
result: CalcType,
|
|
164
|
+
declaredFieldType: string | undefined,
|
|
165
|
+
ctx: CalcTypeContext,
|
|
166
|
+
ast: CalcAst,
|
|
167
|
+
): void {
|
|
168
|
+
const declared = declaredFieldType ?? 'text';
|
|
169
|
+
const allowed = CALC_TO_FIELD[result];
|
|
170
|
+
if (!allowed.includes(declared)) {
|
|
171
|
+
throw new SomaCalcTypeError(
|
|
172
|
+
`表达式算出来是 ${result},但字段声明的是 ${declared}`
|
|
173
|
+
+ `(${result} 可以声明为:${allowed.join(' / ')})`,
|
|
174
|
+
ctx.source, ast.pos, allowed.join('|'), declared,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
if (result === 'bool') {
|
|
178
|
+
throw new SomaCalcTypeError(
|
|
179
|
+
'派生列不能是判断结果——字段类型里没有「显示 true」这种业务语义;'
|
|
180
|
+
+ '想按条件出不同文案请用 IF(条件, "A", "B")',
|
|
181
|
+
ctx.source, ast.pos, 'number|text|date', 'bool',
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|