Files
hose-use/src/domains/platform/workflow/script/mvel-subset.ts
T

204 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ValidationError } from "../../../../core/errors.js";
function unsupported(message: string): never {
throw new ValidationError(`本地 MVEL 子集不支持 ${message};请使用真实 MVEL 运行时验证`);
}
/** 字符串作为完整 token 保留;注释不参与语法转换。 */
function tokenize(source: string): string[] {
const tokens: string[] = [];
const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|>>>=|===|!==|>>>|<<=|>>=|\*\*=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|%=|<<|>>|\*\*|[{}()[\].,;:+*/%=&|^~!<>?-]/y;
let offset = 0;
while (offset < source.length) {
pattern.lastIndex = offset;
const match = pattern.exec(source);
if (!match) unsupported(`字符 ${JSON.stringify(source[offset])}(偏移 ${offset})`);
const token = match[0];
offset = pattern.lastIndex;
if (!/^\s|^\/\//.test(token) && !token.startsWith("/*")) tokens.push(token);
}
return tokens;
}
function closing(tokens: string[], start: number): number {
const stack: string[] = [];
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
for (let i = start; i < tokens.length; i++) {
const token = tokens[i];
if (pairs[token]) stack.push(pairs[token]);
else if ([")", "]", "}"].includes(token)) {
if (stack.pop() !== token) unsupported("不匹配的括号");
if (!stack.length) return i;
}
}
return unsupported("未闭合的括号");
}
type Statement = { start: number; end: number; kind: "expression" | "return" | "declaration" | "compound" | "empty" };
/** 只识别语句边界,不模拟复合语句在 MVEL 中的完成值。 */
function statementAt(tokens: string[], start: number): Statement {
const token = tokens[start];
const finish = (end: number, kind: Statement["kind"]): Statement => ({ start, end, kind });
if (token === ";") return finish(start + 1, "empty");
if (token === "{") return finish(closing(tokens, start) + 1, "compound");
if (["if", "for", "while", "switch"].includes(token)) {
if (tokens[start + 1] !== "(") unsupported(`${token} 语句`);
const conditionEnd = closing(tokens, start + 1);
if (token === "for") {
// 三元表达式仍可使用冒号;没有分号的增强 for 不属于本地子集。
const header = tokens.slice(start + 2, conditionEnd);
if (!header.includes(";") && header.includes(":")) unsupported("增强 for 循环");
}
if (conditionEnd + 1 >= tokens.length) unsupported(`${token} 缺少语句体`);
let end = statementAt(tokens, conditionEnd + 1).end;
if (token === "if" && tokens[end] === "else") end = statementAt(tokens, end + 1).end;
return finish(end, "compound");
}
if (token === "do") {
const bodyEnd = statementAt(tokens, start + 1).end;
if (tokens[bodyEnd] !== "while" || tokens[bodyEnd + 1] !== "(") unsupported("do/while 语句");
const end = closing(tokens, bodyEnd + 1) + 1;
return finish(tokens[end] === ";" ? end + 1 : end, "compound");
}
if (token === "try") {
let end = statementAt(tokens, start + 1).end;
if (tokens[end] === "catch") {
end++;
if (tokens[end] === "(") end = closing(tokens, end) + 1;
end = statementAt(tokens, end).end;
}
if (tokens[end] === "finally") end = statementAt(tokens, end + 1).end;
return finish(end, "compound");
}
if (token === "function" || token === "class") {
let body = start + 1;
while (body < tokens.length && tokens[body] !== "{") {
if (tokens[body] === "(") body = closing(tokens, body);
body++;
}
if (body >= tokens.length) unsupported(`${token} 缺少语句体`);
return finish(closing(tokens, body) + 1, "declaration");
}
if (["catch", "finally", "import", "package"].includes(token)) unsupported(`${token} 语句`);
let end = start;
while (end < tokens.length && tokens[end] !== ";") {
if (["(", "[", "{"].includes(tokens[end])) end = closing(tokens, end);
else if ([")", "]", "}"].includes(tokens[end])) unsupported("不匹配的括号");
end++;
}
if (tokens[end] === ";") end++;
const kind = token === "return" || token === "throw" ? "return" : ["var", "let", "const"].includes(token) ? "declaration" : "expression";
return finish(end, kind);
}
function finalStatement(tokens: string[]): Statement | undefined {
let last: Statement | undefined;
for (let i = 0; i < tokens.length;) {
const statement = statementAt(tokens, i);
if (statement.kind !== "empty") last = statement;
i = statement.end;
}
return last;
}
const declarations = new Set(["String", "int", "Integer", "long", "Long", "double", "Double", "float", "Float", "boolean", "Boolean", "List", "Map", "HashMap", "ArrayList", "Object"]);
/** lint 保留 hasReturn 的显式 return 含义,同时识别可确定的末尾表达式。 */
export function hasMvelFinalExpression(source: string): boolean {
try {
const tokens = tokenize(source);
const tail = finalStatement(tokens);
return tail?.kind === "expression" && !declarations.has(tokens[tail.start]);
} catch {
// 原生 MVEL 可能超出本地子集,静态 lint 不因此宣告其语法非法。
return false;
}
}
function receiverStart(tokens: string[], end: number): number {
let start = end;
if (tokens[end] === ")" || tokens[end] === "]") {
const opening = tokens[end] === ")" ? "(" : "[";
let depth = 1;
while (--start >= 0) {
if (tokens[start] === tokens[end]) depth++;
if (tokens[start] === opening && --depth === 0) break;
}
if (start < 0) unsupported("缺少方法接收对象");
const previous = tokens[start - 1];
const previousIsName = /^[A-Za-z_$][\w$]*$/.test(previous ?? "") && !["return", "throw", "if", "while", "for", "switch"].includes(previous);
// 数组字面量不是索引表达式;不能把前面的 return/赋值运算符当作接收对象。
if (previousIsName || (opening === "[" && [")", "]"].includes(previous))) start = receiverStart(tokens, start - 1);
}
if (tokens[start - 1] === ".") start = receiverStart(tokens, start - 2);
if (start < 0) unsupported("缺少方法接收对象");
return start;
}
const arities: Record<string, number> = { put: 2, get: 1, size: 0, add: 1 };
function rewriteMethods(input: string[]): string[] {
const tokens = [...input];
for (let i = 1; i < tokens.length - 2; i++) {
const method = tokens[i + 1];
if (tokens[i] !== "." || tokens[i + 2] !== "(" || !Object.hasOwn(arities, method)) continue;
const end = closing(tokens, i + 2);
const args: string[][] = [];
let from = i + 3;
for (let j = from; j < end; j++) {
if (["(", "[", "{"].includes(tokens[j])) j = closing(tokens, j);
else if (tokens[j] === ",") { args.push(tokens.slice(from, j)); from = j + 1; }
}
if (from < end) args.push(tokens.slice(from, end));
if (args.length !== arities[method] || args.some(arg => !arg.length)) unsupported(`${method} 的该参数数量`);
const start = receiverStart(tokens, i - 1);
const replacement = [`__hose_mvel_${method}`, "(", ...tokens.slice(start, i)];
for (const arg of args) replacement.push(",", ...rewriteMethods(arg));
replacement.push(")");
tokens.splice(start, end - start + 1, ...replacement);
i = start + replacement.length - 1;
}
return tokens;
}
/** 必要的 MVEL 集合与末尾表达式子集;运算仍由隔离 QuickJS 执行。 */
export function transpileMvelSubset(source: string): string {
const tokens = tokenize(source);
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (/^__hose_mvel_/.test(token)) unsupported("保留的内部标识符");
if (declarations.has(token) && tokens[i + 1] === "<") unsupported("泛型声明");
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
if (declarations.has(token) && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 1] ?? "") && ["=", ";"].includes(tokens[i + 2])) tokens[i] = "var";
// 2. 转换 new HashMap() / new ArrayList(),仅精确扩展两个全限定名零参构造器。
if (token === "new") {
let end = i + 1;
while (/^[A-Za-z_$][\w$]*$/.test(tokens[end] ?? "") && tokens[end + 1] === ".") end += 2;
const kind = tokens.slice(i + 1, end + 1).join("");
const map = ["HashMap", "Map", "java.util.HashMap"].includes(kind);
if ((!map && !["ArrayList", "List", "java.util.ArrayList"].includes(kind)) || tokens[end + 1] !== "(" || tokens[end + 2] !== ")") unsupported("该构造器、泛型或构造参数");
tokens.splice(i, end + 3 - i, ...(map ? ["__hose_mvel_map", "(", ")"] : ["[", "]"]));
}
}
// 3. 常见 Map/List 方法调用模拟:
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
// 注入轻量 helper;按 token 边界处理,避免直接正则冲突,并保留方法返回值。
const rewritten = rewriteMethods(tokens);
const tail = finalStatement(rewritten);
if (!tail || !["return", "expression"].includes(tail.kind)) unsupported("末项复合语句或声明的完成值;请添加明确的末尾结果表达式");
if (tail.kind === "expression") {
const end = rewritten[tail.end - 1] === ";" ? tail.end - 1 : tail.end;
rewritten.splice(tail.start, tail.end - tail.start, "return", "(", ...rewritten.slice(tail.start, end), ")", ";");
}
// 恢复并使用 helper,Map 使用自身属性,避免原型键影响集合语义。
const preamble = `
function __hose_mvel_map() { return Object.create(null); }
function __hose_mvel_put(obj, key, val) { if (!obj || Array.isArray(obj) || typeof obj !== 'object') throw new TypeError('put requires Map'); if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); const old = Object.hasOwn(obj, key) ? obj[key] : null; Object.defineProperty(obj, key, {value:val, writable:true, enumerable:true, configurable:true}); return old; }
function __hose_mvel_get(obj, key) { if (!obj || typeof obj !== 'object') throw new TypeError('get requires Map/List'); if (Array.isArray(obj)) { if (!Number.isInteger(key) || key < 0 || key >= obj.length) throw new RangeError('List index out of bounds'); } else if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); return Object.hasOwn(obj, key) ? obj[key] : null; }
function __hose_mvel_size(obj) { if (!obj || typeof obj !== 'object') throw new TypeError('size requires Map/List'); return Array.isArray(obj) ? obj.length : Object.keys(obj).length; }
function __hose_mvel_add(arr, item) { if (!Array.isArray(arr)) throw new TypeError('add requires List'); arr.push(item); return true; }
`;
return preamble + rewritten.join(" ");
}