sh-tools 2.3.10 → 2.3.12

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.
@@ -1,542 +1,550 @@
1
- import utilsModule from '../utils'
1
+ import utils from '../utils'
2
+
3
+ // ======================== Token 配置 ========================
4
+ export const TOKEN_TYPES = [
5
+ { type: 'JSON', reg: /#JSON#[\s\S]*?#JSON#/, handler: token => token },
6
+ { type: 'STRING', reg: /(["'])(.*?)\1/, handler: token => token.slice(1, -1) },
7
+ { type: 'NUMBER', reg: /\d+\.?\d*|\.\d+/, handler: token => Number(token) },
8
+ {
9
+ type: 'KEYWORD',
10
+ reg: /\b(?:if|else|null|undefined|true|false)\b/,
11
+ handler: token => {
12
+ switch (token) {
13
+ case 'null':
14
+ return null
15
+ case 'undefined':
16
+ return undefined
17
+ case 'true':
18
+ return true
19
+ case 'false':
20
+ return false
21
+ default:
22
+ return token
23
+ }
24
+ }
25
+ },
26
+ { type: 'IDENTIFIER', reg: /[a-zA-Z_$][a-zA-Z0-9_$]*/, handler: token => token },
27
+ { type: 'OPERATOR', reg: /===|!==|==|!=|<=|>=|<<|>>|>>>|\|\||&&|\*\*|[,.+\-*/%^&|<>!?()\[\]:]/, handler: token => token }
28
+ ]
29
+
30
+ export const OPERATOR_CONFIG = {
31
+ // 三元运算符
32
+ '?': { precedence: 1, associativity: 'right', isTernary: true, fn: (c, a, b) => (c ? a : b) },
33
+ // 逻辑运算符
34
+ '||': { precedence: 2, associativity: 'left', fn: (a, b) => a || b },
35
+ '&&': { precedence: 3, associativity: 'left', fn: (a, b) => a && b },
36
+ // 位运算符
37
+ '|': { precedence: 4, associativity: 'left', fn: (a, b) => a | b },
38
+ '^': { precedence: 5, associativity: 'left', fn: (a, b) => a ^ b },
39
+ '&': { precedence: 6, associativity: 'left', fn: (a, b) => a & b },
40
+ // 比较运算符
41
+ '==': { precedence: 7, associativity: 'left', fn: (a, b) => a == b },
42
+ '!=': { precedence: 7, associativity: 'left', fn: (a, b) => a != b },
43
+ '===': { precedence: 7, associativity: 'left', fn: utils.isEqual },
44
+ '!==': { precedence: 7, associativity: 'left', fn: (a, b) => a !== b },
45
+ '<': { precedence: 8, associativity: 'left', fn: (a, b) => utils.compareValue(a, b) },
46
+ '>': { precedence: 8, associativity: 'left', fn: (a, b) => utils.compareValue(b, a) },
47
+ '<=': { precedence: 8, associativity: 'left', fn: (a, b) => !utils.compareValue(b, a) },
48
+ '>=': { precedence: 8, associativity: 'left', fn: (a, b) => !utils.compareValue(a, b) },
49
+ // 算术运算符
50
+ '+': { precedence: 10, associativity: 'left', fn: utils.add },
51
+ '-': { precedence: 10, associativity: 'left', fn: utils.subtract },
52
+ '*': { precedence: 11, associativity: 'left', fn: utils.multiply },
53
+ '/': { precedence: 11, associativity: 'left', fn: utils.divide },
54
+ '%': { precedence: 11, associativity: 'left', fn: (a, b) => a % b },
55
+ '**': { precedence: 12, associativity: 'right', fn: (a, b) => Math.pow(a, b) },
56
+ // 一元运算符
57
+ '!': { precedence: 13, associativity: 'right', isUnary: true, fn: a => !a },
58
+ '~': { precedence: 13, associativity: 'right', isUnary: true, fn: a => ~a }
59
+ }
2
60
 
3
- /**
4
- * 表达式求值器 - 支持JSON标记解析、常用数学/数组/对象运算
5
- * @class ExprEvaluator
6
- * @description 通过#JSON#双标记精准解析嵌套JSON,聚焦核心运算场景
7
- */
8
- class ExprEvaluator {
9
- // 静态常量 - 仅保留核心方法
10
- static MATH_METHODS = ['abs', 'sin', 'cos', 'tan', 'log', 'exp', 'pow']
11
- static UTIL_METHODS = {
12
- base: [
13
- 'isNaN',
14
- 'isFinite',
15
- 'isArray',
16
- 'isFloat',
17
- 'isInteger',
18
- 'isBoolean',
19
- 'isString',
20
- 'isNumber',
21
- 'isPlainObject',
22
- 'isDate',
23
- 'isEmpty',
24
- 'isNull',
25
- 'isMatch',
26
- 'isEqual',
27
- 'getSize',
28
- 'first',
29
- 'last'
30
- ],
61
+ // ======================== 工具函数 ========================
62
+ function getUtilsFunctions() {
63
+ const utilMethods = {
64
+ base: ['isNaN', 'isArray', 'isFloat', 'isInteger', 'isBoolean', 'isString', 'isNumber', 'isPlainObject', 'isDate', 'isEmpty', 'isNull', 'isMatch', 'isEqual', 'getSize', 'first', 'last'],
31
65
  object: ['has', 'get', 'assign', 'merge', 'pick', 'omit'],
32
- array: [
33
- 'slice',
34
- 'indexOf',
35
- 'includes',
36
- 'includeArrays',
37
- 'sum',
38
- 'mean',
39
- 'zip',
40
- 'unzip',
41
- 'uniq',
42
- 'union',
43
- 'flatten',
44
- 'pluck',
45
- 'invoke',
46
- 'orderBy',
47
- 'groupBy',
48
- 'countBy',
49
- 'toArrayTree',
50
- 'toTreeArray'
51
- ],
52
- date: ['toDateString', 'getYearDiff', 'getMonthDiff', 'getDayDiff', 'getHourDiff', 'getMinuteDiff', 'getSecondDiff', 'getYearDay', 'getYearWeek', 'getMonthWeek', 'getDayOfMonth'],
66
+ array: ['slice', 'indexOf', 'includes', 'includeArrays', 'sum', 'mean', 'unzip', 'uniq', 'union', 'flatten', 'pluck', 'invoke', 'orderBy', 'groupBy', 'countBy', 'toArrayTree', 'toTreeArray'],
67
+ date: ['now', 'timestamp', 'toDateString', 'getYearDiff', 'getMonthDiff', 'getDayDiff', 'getHourDiff', 'getMinuteDiff', 'getSecondDiff', 'getDayOfMonth'],
53
68
  number: ['random', 'min', 'max', 'ceil', 'floor', 'round', 'truncate', 'toFixed', 'toNumber', 'toNumberString', 'toInteger', 'add', 'subtract', 'multiply', 'divide'],
54
- string: ['toValueString', 'trim', 'trimLeft', 'trimRight', 'camelCase', 'kebabCase', 'startsWith', 'endsWith']
69
+ string: ['toValueString', 'trim', 'trimLeft', 'trimRight', 'camelCase', 'kebabCase']
55
70
  }
71
+ return Object.values(utilMethods)
72
+ .flat()
73
+ .reduce((acc, method) => {
74
+ if (typeof utils[method] === 'function') acc[method] = utils[method]
75
+ else if (process.env.NODE_ENV === 'development') console.warn(`[ExprEvaluator] utils方法不存在: ${method}`)
76
+ return acc
77
+ }, {})
78
+ }
56
79
 
57
- // TOKEN_REG匹配
58
- static TOKEN_REG = /\s*(?:#JSON#([\s\S]*?)#JSON#|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|if|else|[a-zA-Z_$][a-zA-Z0-9_$]*|\d+\.?\d*|\.\d+|===|!==|==|!=|<=|>=|\|\||&&|[,.+\-*/%^&|<>!?()\[\]:])\s*/g
80
+ function getBuiltinFunctions() {
81
+ return {
82
+ ...Object.fromEntries(['abs', 'sin', 'cos', 'tan', 'log', 'exp', 'pow'].map(name => [name, Math[name]])),
83
+ ...getUtilsFunctions(),
84
+ startsWith: (str, value) => String(str || '').startsWith(value),
85
+ endsWith: (str, value) => String(str || '').endsWith(value),
86
+ length: value => value.length
87
+ }
88
+ }
89
+
90
+ function tokensToExpr(tokens, start, end) {
91
+ return tokens
92
+ .slice(start, end)
93
+ .map(t => t.raw)
94
+ .join('')
95
+ .replace(/\s+/g, ' ')
96
+ .trim()
97
+ }
59
98
 
60
- // 精简版OP_MAP:移除unary、shift,仅保留核心运算
61
- static OP_MAP = {
62
- equality: { '==': true, '!=': true, '===': true, '!==': true },
63
- relational: { '<': true, '>': true, '<=': true, '>=': true },
64
- arithmetic: { '+': true, '-': true, '*': true, '/': true, '%': true }
99
+ // ======================== 分词器 ========================
100
+ class Tokenizer {
101
+ tokenize(expr) {
102
+ const normalizedExpr = expr.replace(/[\n\r]/g, ' ').trim()
103
+ if (!normalizedExpr) throw new Error('表达式不能为空')
104
+ const tokens = []
105
+ let remaining = normalizedExpr
106
+ while (remaining) {
107
+ remaining = remaining.trim()
108
+ if (!remaining) break
109
+ let matchedType = null
110
+ let matchedValue = ''
111
+ for (const type of TOKEN_TYPES) {
112
+ const match = type.reg.exec(remaining)
113
+ if (match && match.index === 0) {
114
+ matchedType = type
115
+ matchedValue = match[0]
116
+ break
117
+ }
118
+ }
119
+ if (!matchedType) throw new Error(`无法识别的字符: ${remaining[0]}`)
120
+ tokens.push({
121
+ type: matchedType.type,
122
+ value: matchedType.handler(matchedValue),
123
+ raw: matchedValue
124
+ })
125
+ remaining = remaining.slice(matchedValue.length)
126
+ }
127
+ return tokens
65
128
  }
129
+ }
66
130
 
131
+ // ======================== 解析器(简化日志版本) ========================
132
+ class Parser {
67
133
  constructor() {
68
- this.functions = {} // 工具函数映射
69
- this.operators = {} // 运算符执行函数
70
- this._isInited = false // 懒加载标记
71
- this._cachedUtilMethods = null // 缓存扁平化的工具方法列表
72
-
73
- // 绑定this
74
- this.parsePrimary = this.parsePrimary.bind(this)
75
- this.parseFunctionArgs = this.parseFunctionArgs.bind(this)
134
+ this.functions = getBuiltinFunctions()
135
+ this.operators = { ...OPERATOR_CONFIG }
136
+ this.tokens = []
137
+ this.pos = 0
138
+ this.enableLog = true
139
+
140
+ // 日志相关 - 简化处理
141
+ this.executionLog = [] // 存储原始日志对象
142
+ this.idCounter = 1
143
+ this.parentStack = [] // 存储父节点的ID
76
144
  }
77
145
 
78
- /**
79
- * 类型归一化 - 为比较运算统一值类型(日期→数字→字符串)
80
- * @private
81
- * @param {any} value 待归一化的值
82
- * @returns {number|string} 归一化后的值(日期转时间戳,数字串转数字,其余转字符串)
83
- */
84
- _normalizeCompareValue(value) {
85
- // 1. 处理日期类型(日期对象/可解析的日期字符串)
86
- if (value instanceof Date) {
87
- return value.getTime() // 转时间戳(数字)
146
+ registerFunction(name, fn, override = false) {
147
+ if (typeof name === 'object') {
148
+ Object.entries(name).forEach(([key, func]) => this.registerFunction(key, func, override))
149
+ return
88
150
  }
89
- if (typeof value === 'string') {
90
- // 尝试解析为日期(支持YYYY-MM-DD、YYYY/MM/DD、带时分秒的格式)
91
- const date = new Date(value)
92
- if (!isNaN(date.getTime())) {
93
- return date.getTime()
94
- }
95
- // 尝试解析为数字(如"123"、"45.6")
96
- const num = Number(value)
97
- if (!isNaN(num)) {
98
- return num
99
- }
100
- // 普通字符串(去空格后比较)
101
- return value.trim()
151
+ if (typeof fn !== 'function') throw new Error('注册的必须是函数')
152
+ if (!override && this.functions[name]) {
153
+ console.warn(`[ExprEvaluator] 函数 ${name} 已存在,使用 override=true 覆盖`)
154
+ return
155
+ }
156
+ this.functions[name] = fn
157
+ }
158
+
159
+ extendOperator(symbol, config, override = false) {
160
+ if (!config.precedence || !config.associativity || !config.fn) {
161
+ throw new Error('运算符配置必须包含 precedence、associativity、fn')
102
162
  }
103
- // 2. 处理数字类型(含数字对象)
104
- if (typeof value === 'number' || (value && typeof value === 'object' && value.constructor === Number)) {
105
- return Number(value)
163
+ if (!override && this.operators[symbol]) {
164
+ console.warn(`[ExprEvaluator] 运算符 ${symbol} 已存在,使用 override=true 覆盖`)
165
+ return
106
166
  }
107
- // 3. 其他类型(布尔值、null、undefined等)转字符串
108
- return String(value)
167
+ this.operators[symbol] = config
109
168
  }
110
169
 
111
- /**
112
- * 懒加载初始化 - 仅首次调用evaluate时执行
113
- * @private
114
- */
115
- _lazyInit() {
116
- if (this._isInited) return
117
- const utils = utilsModule.__esModule ? utilsModule.default : utilsModule
118
-
119
- // 1. 初始化数学函数(仅保留核心)
120
- ExprEvaluator.MATH_METHODS.forEach(method => {
121
- this.functions[method] = Math[method]
122
- })
123
-
124
- // 2. 初始化工具函数
125
- this._cachedUtilMethods = Object.values(ExprEvaluator.UTIL_METHODS).flat()
126
- this._cachedUtilMethods.forEach(method => {
127
- if (typeof utils[method] === 'function') {
128
- this.functions[method] = utils[method]
129
- } else if (process.env.NODE_ENV === 'development') {
130
- console.warn(`[ExprEvaluator] 工具方法不存在: ${method}`)
131
- }
132
- })
133
-
134
- // 3. 初始化核心运算符
135
- this.operators = {
136
- '?:': { precedence: 1, associativity: 'right', ternary: true, fn: (c, a, b) => (c ? a : b) },
137
- '||': { precedence: 1, associativity: 'left', fn: (a, b) => a || b },
138
- '&&': { precedence: 2, associativity: 'left', fn: (a, b) => a && b },
139
- '|': { precedence: 3, associativity: 'left', fn: (a, b) => a | b },
140
- '^': { precedence: 4, associativity: 'left', fn: (a, b) => a ^ b },
141
- '&': { precedence: 5, associativity: 'left', fn: (a, b) => a & b },
142
- '==': { precedence: 6, associativity: 'left', fn: (a, b) => a == b },
143
- '!=': { precedence: 6, associativity: 'left', fn: (a, b) => a != b },
144
- '!==': { precedence: 6, associativity: 'left', fn: (a, b) => a !== b },
145
- '<': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) < this._normalizeCompareValue(b) },
146
- '>': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) > this._normalizeCompareValue(b) },
147
- '<=': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) <= this._normalizeCompareValue(b) },
148
- '>=': { precedence: 7, associativity: 'left', fn: (a, b) => this._normalizeCompareValue(a) >= this._normalizeCompareValue(b) },
149
- '===': { precedence: 6, associativity: 'left', fn: utils.isEqual },
150
- '+': { precedence: 9, associativity: 'left', fn: utils.add },
151
- '-': { precedence: 9, associativity: 'left', fn: utils.subtract },
152
- '*': { precedence: 10, associativity: 'left', fn: utils.multiply },
153
- '/': { precedence: 10, associativity: 'left', fn: utils.divide },
154
- '%': { precedence: 10, associativity: 'left', fn: (a, b) => a % b },
155
- '!': { precedence: 12, associativity: 'right', prefix: true, fn: a => !a },
156
- '~': { precedence: 12, associativity: 'right', prefix: true, fn: a => ~a }
170
+ // 创建日志条目
171
+ addLogEntry(expr, result) {
172
+ if (!this.enableLog) return null
173
+
174
+ const id = this.idCounter++
175
+ const parentId = this.parentStack.length > 0 ? this.parentStack[this.parentStack.length - 1] : null
176
+
177
+ const logEntry = {
178
+ id,
179
+ parentId,
180
+ expr,
181
+ result,
182
+ children: []
157
183
  }
158
184
 
159
- this._isInited = true
185
+ this.executionLog.push(logEntry)
186
+ return id
160
187
  }
161
188
 
162
- /**
163
- * 解析函数参数
164
- * @private
165
- * @param {string} closeChar 闭合字符
166
- * @returns {Array} 参数列表
167
- */
168
- parseFunctionArgs(closeChar) {
169
- const args = []
170
- this.pos++
171
-
172
- if (this.tokens[this.pos] !== closeChar) {
173
- args.push(this.parseTernary())
174
- while (this.tokens[this.pos] === ',') {
175
- this.pos++
176
- if (this.tokens[this.pos] === closeChar) break
177
- args.push(this.parseTernary())
178
- }
179
- }
189
+ // 进入上下文
190
+ enterContext(id) {
191
+ this.parentStack.push(id)
192
+ }
193
+
194
+ // 退出上下文
195
+ exitContext() {
196
+ this.parentStack.pop()
197
+ }
198
+
199
+ parse(tokens, enableLog = true) {
200
+ this.tokens = tokens
201
+ this.pos = 0
202
+ this.enableLog = enableLog
203
+
204
+ // 重置状态
205
+ this.executionLog = []
206
+ this.idCounter = 1
207
+ this.parentStack = []
208
+
209
+ const result = this.parseExpression()
180
210
 
181
- if (this.tokens[this.pos] !== closeChar) {
182
- throw new Error(`函数参数未闭合:缺少 ${closeChar}(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
211
+ if (this.pos < tokens.length) {
212
+ const remaining = tokens
213
+ .slice(this.pos)
214
+ .map(t => t.raw)
215
+ .join('')
216
+ throw new Error(`表达式多余内容: ${remaining}`)
183
217
  }
184
- this.pos++
185
- return args
218
+
219
+ return { result, executionLog: this.executionLog }
186
220
  }
187
221
 
188
- /**
189
- * 解析数组字面量
190
- * @private
191
- * @returns {Array} 解析后的数组
192
- */
193
- parseArrayLiteral() {
222
+ parseExpression(precedence = 1) {
194
223
  const startPos = this.pos
195
- this.pos++
196
- const arr = []
224
+ let left = this.parsePrimary()
225
+
226
+ while (this.peek() && this.isOperator(this.peek()) && this.getOperatorPrecedence(this.peek()) >= precedence) {
227
+ const opToken = this.consume()
228
+ const opConfig = this.operators[opToken.value]
229
+
230
+ if (opConfig?.isTernary) {
231
+ // 三元运算符特殊处理
232
+ const condition = left
233
+ const conditionExpr = tokensToExpr(this.tokens, startPos, this.pos - 1)
234
+
235
+ // 记录条件
236
+ const conditionId = this.addLogEntry(conditionExpr, condition)
237
+
238
+ // 记录三元表达式开始
239
+ const ternaryStartPos = startPos
240
+
241
+ // 处理真分支
242
+ this.enterContext(conditionId)
243
+ const trueBranch = this.parseExpression(1)
244
+ this.exitContext()
245
+
246
+ this.consumeToken('OPERATOR', ':')
197
247
 
198
- if (this.tokens[this.pos] !== ']') {
199
- arr.push(this.parseTernary())
200
- while (this.tokens[this.pos] === ',') {
201
- this.pos++
202
- if (this.tokens[this.pos] === ']') break
203
- arr.push(this.parseTernary())
248
+ // 处理假分支
249
+ this.enterContext(conditionId)
250
+ const falseBranch = this.parseExpression(1)
251
+ this.exitContext()
252
+
253
+ const result = opConfig.fn(condition, trueBranch, falseBranch)
254
+
255
+ // 记录完整的三元表达式
256
+ const fullExpr = tokensToExpr(this.tokens, ternaryStartPos, this.pos)
257
+ this.addLogEntry(fullExpr, result)
258
+
259
+ left = result
260
+ continue
204
261
  }
205
- }
206
262
 
207
- if (this.tokens[this.pos] !== ']') {
208
- throw new Error(`数组未闭合:在位置 ${startPos} 开始的数组缺少 ](当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
209
- }
210
- this.pos++
211
- return arr
212
- }
263
+ const nextPrecedence = opConfig.associativity === 'left' ? opConfig.precedence + 1 : opConfig.precedence
264
+ const right = this.parseExpression(nextPrecedence)
213
265
 
214
- /**
215
- * 校验JSON格式
216
- * @private
217
- * @param {string} jsonStr JSON字符串
218
- * @returns {boolean} 是否有效
219
- */
220
- _isValidJson(jsonStr) {
221
- if (!jsonStr) return false
222
- try {
223
- JSON.parse(jsonStr)
224
- return true
225
- } catch {
226
- return false
266
+ // 记录运算符表达式
267
+ if (this.enableLog) {
268
+ const leftStr = typeof left === 'object' ? JSON.stringify(left) : String(left)
269
+ const rightStr = typeof right === 'object' ? JSON.stringify(right) : String(right)
270
+ const expr = `${leftStr} ${opToken.value} ${rightStr}`
271
+ this.addLogEntry(expr, opConfig.fn(left, right))
272
+ }
273
+
274
+ left = opConfig.fn(left, right)
227
275
  }
276
+
277
+ return left
228
278
  }
229
279
 
230
- /**
231
- * 解析基础Token
232
- * @private
233
- * @returns {any} 解析后的值
234
- */
235
280
  parsePrimary() {
236
- if (this.pos >= this.tokens.length) throw new Error('表达式意外结束')
237
- const currentToken = this.tokens[this.pos]
238
-
239
- // 解析双标记JSON
240
- if (typeof currentToken === 'string' && currentToken.includes('#JSON#')) {
241
- this.pos++
242
- const jsonMatch = currentToken.match(/#JSON#([\s\S]*?)#JSON#/)
243
- if (!jsonMatch || !this._isValidJson(jsonMatch[1])) {
244
- throw new Error(`JSON解析失败:${jsonMatch?.[1] || currentToken}(原Token:${currentToken})`)
245
- }
246
- return JSON.parse(jsonMatch[1])
281
+ const token = this.peek()
282
+ if (!token) throw new Error('表达式意外结束')
283
+
284
+ // if-else 表达式
285
+ if (token.type === 'KEYWORD' && token.value === 'if') {
286
+ return this.parseIfElse()
247
287
  }
248
288
 
249
- // 解析字符串字面量
250
- if (typeof currentToken === 'string' && (currentToken.startsWith('"') || currentToken.startsWith("'"))) {
251
- this.pos++
252
- return currentToken.slice(1, -1)
289
+ // 括号表达式
290
+ if (token.type === 'OPERATOR' && token.value === '(') {
291
+ return this.parseParenthesizedExpression()
253
292
  }
254
293
 
255
- // 解析数组字面量
256
- if (currentToken === '[') return this.parseArrayLiteral()
294
+ // JSON
295
+ if (token.type === 'JSON') {
296
+ return this.parseJsonLiteral()
297
+ }
257
298
 
258
- // 解析括号表达式
259
- if (currentToken === '(') {
260
- this.pos++
261
- const res = this.parseTernary()
262
- if (this.tokens[this.pos] !== ')') {
263
- throw new Error(`括号未闭合:缺少 )(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
299
+ // 字面量
300
+ if (['STRING', 'NUMBER', 'KEYWORD'].includes(token.type)) {
301
+ const value = this.consume().value
302
+ if (this.enableLog && token.type !== 'KEYWORD') {
303
+ this.addLogEntry(token.raw, value)
264
304
  }
265
- this.pos++
266
- return res
305
+ return value
267
306
  }
268
307
 
269
- // 解析函数调用
270
- if (typeof currentToken === 'string' && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(currentToken)) {
271
- const funcName = currentToken
272
- this.pos++
308
+ // 一元运算符
309
+ if (this.isUnaryOperator(token)) {
310
+ const opToken = this.consume()
311
+ const opConfig = this.operators[opToken.value]
312
+ const operand = this.parsePrimary()
313
+ const result = opConfig.fn(operand)
273
314
 
274
- const callType = this.tokens[this.pos]
275
- if (callType === '(' || callType === '[') {
276
- const args = this.parseFunctionArgs(callType === '(' ? ')' : ']')
277
- if (!this.functions[funcName]) throw new Error(`未定义函数: ${funcName}`)
278
- return this.functions[funcName](...args)
315
+ if (this.enableLog) {
316
+ const expr = `${opToken.value}${operand}`
317
+ this.addLogEntry(expr, result)
279
318
  }
280
319
 
281
- throw new Error(`不支持变量: ${funcName}(仅支持函数调用和字面量)`)
320
+ return result
282
321
  }
283
322
 
284
- // 解析数字
285
- if (typeof currentToken === 'number' || /^\d+\.?\d*|\.\d+$/.test(currentToken)) {
286
- this.pos++
287
- return Number(currentToken)
323
+ // 数组
324
+ if (token.type === 'OPERATOR' && token.value === '[') {
325
+ return this.parseArrayLiteral()
288
326
  }
289
327
 
290
- throw new Error(`无效Token: ${currentToken}(位置:${this.pos})`)
291
- }
292
-
293
- // ========== 精简后的解析链(仅保留核心运算) ==========
294
- /**
295
- * 解析乘/除/取模运算
296
- * @private
297
- * @returns {number} 运算结果
298
- */
299
- parseMultiplicative() {
300
- let res = this.parsePrimary()
301
- while (ExprEvaluator.OP_MAP.arithmetic[this.tokens[this.pos]] && ['*', '/', '%'].includes(this.tokens[this.pos])) {
302
- const op = this.tokens[this.pos]
303
- this.pos++
304
- res = this.operators[op].fn(res, this.parsePrimary())
328
+ // 函数调用
329
+ if (token.type === 'IDENTIFIER') {
330
+ return this.parseFunctionCall()
305
331
  }
306
- return res
307
- }
308
332
 
309
- /**
310
- * 解析加/减运算
311
- * @private
312
- * @returns {number} 运算结果
313
- */
314
- parseAdditive() {
315
- let res = this.parseMultiplicative()
316
- while (ExprEvaluator.OP_MAP.arithmetic[this.tokens[this.pos]] && ['+', '-'].includes(this.tokens[this.pos])) {
317
- const op = this.tokens[this.pos]
318
- this.pos++
319
- res = this.operators[op].fn(res, this.parseMultiplicative())
320
- }
321
- return res
333
+ throw new Error(`无效Token: ${token.raw}`)
322
334
  }
323
335
 
324
- /**
325
- * 解析关系运算(<、>、<=、>=)
326
- * @private
327
- * @returns {boolean} 运算结果
328
- */
329
- parseRelational() {
330
- let res = this.parseAdditive()
331
- while (ExprEvaluator.OP_MAP.relational[this.tokens[this.pos]]) {
332
- const op = this.tokens[this.pos]
333
- this.pos++
334
- res = this.operators[op].fn(res, this.parseAdditive())
335
- }
336
- return res
337
- }
336
+ parseParenthesizedExpression() {
337
+ const startPos = this.pos
338
+ this.consumeToken('OPERATOR', '(')
338
339
 
339
- /**
340
- * 解析相等运算(==、!=、===、!==)
341
- * @private
342
- * @returns {boolean} 运算结果
343
- */
344
- parseEquality() {
345
- let res = this.parseRelational()
346
- while (ExprEvaluator.OP_MAP.equality[this.tokens[this.pos]]) {
347
- const op = this.tokens[this.pos]
348
- this.pos++
349
- res = this.operators[op].fn(res, this.parseRelational())
350
- }
351
- return res
352
- }
340
+ // 记录括号开始
341
+ const parentId = this.addLogEntry('(', null)
342
+ this.enterContext(parentId)
353
343
 
354
- /**
355
- * 解析按位与运算
356
- * @private
357
- * @returns {number} 运算结果
358
- */
359
- parseBitwiseAnd() {
360
- let res = this.parseEquality()
361
- while (this.tokens[this.pos] === '&') {
362
- this.pos++
363
- res = this.operators['&'].fn(res, this.parseEquality())
344
+ let result
345
+ if (this.matchToken('KEYWORD', 'if')) {
346
+ result = this.parseIfElse()
347
+ } else {
348
+ result = this.parseExpression(1)
364
349
  }
365
- return res
366
- }
367
350
 
368
- /**
369
- * 解析按位异或运算
370
- * @private
371
- * @returns {number} 运算结果
372
- */
373
- parseBitwiseXor() {
374
- let res = this.parseBitwiseAnd()
375
- while (this.tokens[this.pos] === '^') {
376
- this.pos++
377
- res = this.operators['^'].fn(res, this.parseBitwiseAnd())
378
- }
379
- return res
380
- }
351
+ this.consumeToken('OPERATOR', ')')
381
352
 
382
- /**
383
- * 解析按位或运算
384
- * @private
385
- * @returns {number} 运算结果
386
- */
387
- parseBitwiseOr() {
388
- let res = this.parseBitwiseXor()
389
- while (this.tokens[this.pos] === '|') {
390
- this.pos++
391
- res = this.operators['|'].fn(res, this.parseBitwiseXor())
353
+ // 更新括号表达式
354
+ const expr = tokensToExpr(this.tokens, startPos, this.pos)
355
+ const log = this.executionLog.find(l => l.id === parentId)
356
+ if (log) {
357
+ log.expr = expr
358
+ log.result = result
392
359
  }
393
- return res
360
+
361
+ this.exitContext()
362
+ return result
394
363
  }
395
364
 
396
- /**
397
- * 解析逻辑与运算
398
- * @private
399
- * @returns {boolean} 运算结果
400
- */
401
- parseLogicalAnd() {
402
- let res = this.parseBitwiseOr()
403
- while (this.tokens[this.pos] === '&&') {
404
- this.pos++
405
- res = this.operators['&&'].fn(res, this.parseBitwiseOr())
365
+ parseJsonLiteral() {
366
+ const token = this.consume()
367
+ try {
368
+ const jsonStr = token.raw.slice(6, -6)
369
+ const result = JSON.parse(jsonStr)
370
+
371
+ if (this.enableLog) {
372
+ this.addLogEntry(token.raw, result)
373
+ }
374
+
375
+ return result
376
+ } catch (e) {
377
+ throw new Error(`JSON解析失败: ${token.raw},原因:${e.message}`)
406
378
  }
407
- return res
408
379
  }
409
380
 
410
- /**
411
- * 解析逻辑或运算
412
- * @private
413
- * @returns {boolean} 运算结果
414
- */
415
- parseLogicalOr() {
416
- let res = this.parseLogicalAnd()
417
- while (this.tokens[this.pos] === '||') {
418
- this.pos++
419
- res = this.operators['||'].fn(res, this.parseLogicalAnd())
381
+ parseArrayLiteral() {
382
+ const startPos = this.pos
383
+ this.consumeToken('OPERATOR', '[')
384
+
385
+ // 记录数组开始
386
+ const arrayId = this.addLogEntry('[', null)
387
+ this.enterContext(arrayId)
388
+
389
+ const arr = []
390
+
391
+ if (!this.matchToken('OPERATOR', ']')) {
392
+ arr.push(this.parseExpression())
393
+ while (this.matchToken('OPERATOR', ',')) {
394
+ this.consumeToken('OPERATOR', ',')
395
+ arr.push(this.parseExpression())
396
+ }
420
397
  }
421
- return res
422
- }
423
398
 
424
- /**
425
- * 解析三元运算核心逻辑
426
- * @private
427
- * @returns {any} 运算结果
428
- */
429
- parseTernaryCore() {
430
- let res = this.parseLogicalOr()
431
- if (this.tokens[this.pos] === '?') {
432
- this.pos++
433
- const a = this.parseTernaryCore()
434
- if (this.tokens[this.pos] !== ':') throw new Error('三元运算符缺少冒号')
435
- this.pos++
436
- const b = this.parseTernaryCore()
437
- res = this.operators['?:'].fn(res, a, b)
399
+ this.consumeToken('OPERATOR', ']')
400
+
401
+ // 更新数组表达式
402
+ const expr = tokensToExpr(this.tokens, startPos, this.pos)
403
+ const log = this.executionLog.find(l => l.id === arrayId)
404
+ if (log) {
405
+ log.expr = expr
406
+ log.result = arr
438
407
  }
439
- return res
408
+
409
+ this.exitContext()
410
+ return arr
440
411
  }
441
412
 
442
- /**
443
- * 解析if/else和三元运算
444
- * @private
445
- * @returns {any} 运算结果
446
- */
447
413
  parseIfElse() {
448
- if (this.tokens[this.pos] !== 'if') return this.parseTernaryCore()
449
- this.pos++
414
+ const startPos = this.pos
450
415
 
451
- if (this.tokens[this.pos] !== '(') {
452
- throw new Error(`if语法错误:缺少左括号(当前Token:${this.tokens[this.pos] || ''}, 位置:${this.pos})`)
453
- }
454
- this.pos++
416
+ this.consumeToken('KEYWORD', 'if')
417
+ this.consumeToken('OPERATOR', '(')
455
418
 
456
- const condition = this.parseTernaryCore()
457
- if (this.tokens[this.pos] !== ')') {
458
- throw new Error(`if语法错误:缺少右括号(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
459
- }
460
- this.pos++
419
+ const condition = this.parseExpression()
420
+ this.consumeToken('OPERATOR', ')')
461
421
 
462
- const thenValue = this.parseTernaryCore()
463
- if (this.tokens[this.pos] !== 'else') {
464
- throw new Error(`if语法错误:缺少else关键字(当前Token:${this.tokens[this.pos] || '空'}, 位置:${this.pos})`)
465
- }
466
- this.pos++
422
+ const ifExpr = this.parseExpression()
467
423
 
468
- const elseValue = this.parseTernaryCore()
469
- return condition ? thenValue : elseValue
470
- }
424
+ let elseExpr = undefined
471
425
 
472
- /**
473
- * 入口解析方法
474
- * @private
475
- * @returns {any} 运算结果
476
- */
477
- parseTernary() {
478
- return this.parseIfElse()
479
- }
426
+ if (this.matchToken('KEYWORD', 'else')) {
427
+ this.consumeToken('KEYWORD', 'else')
480
428
 
481
- /**
482
- * 分词处理
483
- * @private
484
- * @param {string} expr 表达式
485
- * @returns {Array} 分词结果
486
- */
487
- _tokenize(expr) {
488
- const tokens = []
489
- const reg = new RegExp(ExprEvaluator.TOKEN_REG.source, 'g')
490
- let match
491
-
492
- while ((match = reg.exec(expr)) !== null) {
493
- const token = match[0].trim()
494
- if (!token) continue
495
-
496
- if (token.includes('#JSON#')) {
497
- tokens.push(token)
498
- } else if (token.startsWith('"') || token.startsWith("'")) {
499
- tokens.push(token)
500
- } else if (/^\d+\.?\d*|\.\d+$/.test(token)) {
501
- tokens.push(Number(token))
429
+ if (this.matchToken('KEYWORD', 'if')) {
430
+ elseExpr = this.parseIfElse()
502
431
  } else {
503
- tokens.push(token)
432
+ elseExpr = this.parseExpression()
504
433
  }
505
434
  }
506
435
 
507
- if (tokens.length === 0) throw new Error('表达式为空')
508
- return tokens
436
+ const result = condition ? ifExpr : elseExpr
437
+
438
+ if (this.enableLog) {
439
+ const fullExpr = tokensToExpr(this.tokens, startPos, this.pos)
440
+ this.addLogEntry(fullExpr, result)
441
+ }
442
+
443
+ return result
509
444
  }
510
445
 
511
- /**
512
- * 对外求值方法
513
- * @public
514
- * @param {string} expr 表达式
515
- * @returns {any} 结果
516
- */
517
- evaluate(expr) {
518
- this._lazyInit()
446
+ parseFunctionCall() {
447
+ const startPos = this.pos
448
+ const funcName = this.consume().value
449
+ const openChar = this.matchToken('OPERATOR', '(') ? '(' : this.matchToken('OPERATOR', '[') ? '[' : null
450
+ if (!openChar) throw new Error(`不支持变量: ${funcName}(仅支持函数调用)`)
451
+ const closeChar = openChar === '(' ? ')' : ']'
519
452
 
520
- if (typeof expr !== 'string') throw new Error('表达式必须是字符串')
521
- const normalizedExpr = expr.replace(/[\n\r]/g, ' ').trim()
522
- if (!normalizedExpr) throw new Error('表达式不能为空')
453
+ // 记录函数调用开始
454
+ const funcId = this.addLogEntry(`${funcName}${openChar}`, null)
455
+ this.enterContext(funcId)
523
456
 
524
- try {
525
- this.tokens = this._tokenize(normalizedExpr)
526
- this.pos = 0
527
- const result = this.parseTernary()
457
+ this.consumeToken('OPERATOR', openChar)
528
458
 
529
- if (this.pos < this.tokens.length) {
530
- throw new Error(`表达式多余内容: ${this.tokens.slice(this.pos).join('')}(位置:${this.pos})`)
459
+ // 收集参数
460
+ const args = []
461
+ if (!this.matchToken('OPERATOR', closeChar)) {
462
+ args.push(this.parseExpression())
463
+ while (this.matchToken('OPERATOR', ',')) {
464
+ this.consumeToken('OPERATOR', ',')
465
+ args.push(this.parseExpression())
531
466
  }
467
+ }
468
+
469
+ this.consumeToken('OPERATOR', closeChar)
470
+
471
+ // 执行函数调用
472
+ if (!this.functions[funcName]) {
473
+ throw new Error(`未定义函数: ${funcName}`)
474
+ }
475
+
476
+ const result = this.functions[funcName](...args)
532
477
 
478
+ // 更新函数调用表达式
479
+ const expr = tokensToExpr(this.tokens, startPos, this.pos)
480
+ const log = this.executionLog.find(l => l.id === funcId)
481
+ if (log) {
482
+ log.expr = expr
483
+ log.result = result
484
+ }
485
+
486
+ this.exitContext()
487
+ return result
488
+ }
489
+
490
+ // ======================== 工具方法 ========================
491
+ peek() {
492
+ return this.tokens[this.pos]
493
+ }
494
+ consume() {
495
+ return this.tokens[this.pos++]
496
+ }
497
+ matchToken(type, value) {
498
+ const token = this.peek()
499
+ return token && token.type === type && token.value === value
500
+ }
501
+ consumeToken(type, value) {
502
+ if (!this.matchToken(type, value)) throw new Error(`缺少Token: ${value}`)
503
+ return this.consume()
504
+ }
505
+ isOperator(token) {
506
+ return token.type === 'OPERATOR' && !!this.operators[token.value]
507
+ }
508
+ isUnaryOperator(token) {
509
+ return this.isOperator(token) && this.operators[token.value]?.isUnary
510
+ }
511
+ getOperatorPrecedence(token) {
512
+ return this.operators[token.value]?.precedence || 0
513
+ }
514
+ }
515
+
516
+ // ======================== 求值器 ========================
517
+ class ExprEvaluator {
518
+ constructor() {
519
+ this.tokenizer = new Tokenizer()
520
+ this.parser = new Parser()
521
+ }
522
+ registerFunction(name, fn, override = false) {
523
+ this.parser.registerFunction(name, fn, override)
524
+ }
525
+ extendOperator(symbol, config, override = false) {
526
+ this.parser.extendOperator(symbol, config, override)
527
+ }
528
+ evaluateLog(expr, enableLog = true) {
529
+ try {
530
+ const tokens = this.tokenizer.tokenize(expr)
531
+ const { result, executionLog } = this.parser.parse(tokens, enableLog)
532
+ return { result, log: utils.orderBy(executionLog, 'parentId'), treeLog: utils.toArrayTree(executionLog) }
533
+ } catch (error) {
534
+ throw new Error(`[ExprEvaluator] ${error.message}(原表达式:${expr})`)
535
+ }
536
+ }
537
+ evaluate(expr) {
538
+ try {
539
+ const tokens = this.tokenizer.tokenize(expr)
540
+ const { result } = this.parser.parse(tokens, false)
533
541
  return result
534
542
  } catch (error) {
535
- throw new Error(`表达式计算失败: ${error.message}(原表达式:${expr})`)
543
+ throw new Error(`[ExprEvaluator] ${error.message}(原表达式:${expr})`)
536
544
  }
537
545
  }
538
546
  }
539
547
 
540
- // 单例导出
541
- const evaluator = new ExprEvaluator()
542
- export default evaluator
548
+ // ======================== 单例导出 ========================
549
+ const exprEvaluator = new ExprEvaluator()
550
+ export default exprEvaluator