#!/usr/bin/env python3 # -*- coding: utf-8 -*- """gen-function-catalog.py —— 从官方 Java 枚举**生成**本仓的函数/变量目录。 为什么要生成而不是手抄 -------------------- `FunctionTypeEnum`(100+ 条)与 `SystemVariateEnum`(18 条)是**纯数据**: 公式编辑器(`variate.ts` 的三个元数据端点)靠它们出下拉与帮助文本。手抄两条风险: ① 漏条 —— 前端某个函数在帮助里点不开,但没人发现; ② 抄错 HTML 描述 —— 帮助面板显示成乱码/错行,且没有闸门能发现。 所以:**官方枚举是唯一真源**,本脚本把它转成 `src/backend/src/platform/variate_catalog.rs`。 改了官方枚举就重跑;`--check` 用于闸门(生成物与真源不一致 ⇒ 非零退出)。 用法 ---- python3 scripts/gen-function-catalog.py # 写入(生成物) python3 scripts/gen-function-catalog.py --check # 只校验,不写 退出码:0 一致 / 1 有差异 / 2 前置缺失 """ from __future__ import annotations import pathlib import re import sys ROOT = pathlib.Path(__file__).resolve().parent.parent JAVA_DIR = pathlib.Path( "/Users/xs/Desktop/workspace/jnpf/jnpf-java-boot/jnpf-system/" "jnpf-system-entity/src/main/java/jnpf/base/model/variate" ) OUT = ROOT / "src" / "backend" / "src" / "platform" / "variate_catalog.rs" def read(path: pathlib.Path) -> str: if not path.exists(): sys.exit(f"缺少官方真源:{path}") return path.read_text(encoding="utf-8", errors="replace") def split_top_level(body: str) -> list[str]: """按**顶层**逗号切分(跳过字符串字面量与括号)。""" parts: list[str] = [] buf: list[str] = [] depth = 0 i = 0 in_str = False while i < len(body): c = body[i] if in_str: buf.append(c) if c == "\\": buf.append(body[i + 1]) i += 2 continue if c == '"': in_str = False i += 1 continue if c == '"': in_str = True buf.append(c) elif c == "(": depth += 1 buf.append(c) elif c == ")": depth -= 1 buf.append(c) elif c == "," and depth == 0: parts.append("".join(buf).strip()) buf = [] else: buf.append(c) i += 1 tail = "".join(buf).strip() if tail: parts.append(tail) return parts def parse_java_string(expr: str) -> str: """把 Java 的字符串表达式(含 `+` 拼接)求值成纯文本。""" expr = expr.strip() chunks = re.findall(r'"((?:[^"\\]|\\.)*)"', expr) out = [] for chunk in chunks: out.append( chunk.replace("\\n", "\n") .replace("\\t", "\t") .replace('\\"', '"') .replace("\\\\", "\\") ) return "".join(out) def rust_str(s: str) -> str: """Rust 字符串字面量(用 r#"…"# 避免 HTML 里的引号转义地狱)。""" if '"#' not in s: return 'r#"' + s + '"#' return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' def parse_enum_entries(text: str, enum_name: str) -> list[tuple[str, list[str]]]: """解析 `enum X { A(...), B(...); ... }` ⇒ [(枚举名, [参数原文…]), …]。""" start = text.index(f"enum {enum_name}") brace = text.index("{", start) depth = 0 end = brace for i in range(brace, len(text)): if text[i] == "{": depth += 1 elif text[i] == "}": depth -= 1 if depth == 0: end = i break body = text[brace + 1 : end] # 枚举体在第一个**顶层** `;` 处结束(之后是字段与方法) depth = 0 in_str = False cut = len(body) i = 0 while i < len(body): c = body[i] if in_str: if c == "\\": i += 2 continue if c == '"': in_str = False elif c == '"': in_str = True elif c in "([{": depth += 1 elif c in ")]}": depth -= 1 elif c == ";" and depth == 0: cut = i break i += 1 entries_text = body[:cut] entries: list[list[str]] = [] depth = 0 in_str = False buf: list[str] = [] i = 0 while i < len(entries_text): c = entries_text[i] if in_str: buf.append(c) if c == "\\": buf.append(entries_text[i + 1]) i += 2 continue if c == '"': in_str = False i += 1 continue if c == '"': in_str = True buf.append(c) elif c == "(": depth += 1 buf.append(c) elif c == ")": depth -= 1 buf.append(c) if depth == 0: raw = "".join(buf) head = raw[: raw.index("(")].strip() args = raw[raw.index("(") + 1 : raw.rindex(")")] entries.append((head, split_top_level(args))) buf = [] elif depth == 0: # 条目名与空白:丢掉(名字只是 Java 侧标识) if c not in ",\n\r\t ": buf.append(c) else: buf.append(c) i += 1 return entries def gen() -> str: funcs_text = read(JAVA_DIR / "FunctionTypeEnum.java") variates_text = read(JAVA_DIR / "SystemVariateEnum.java") categories_text = read(JAVA_DIR / "FunctionCategory.java") cats = parse_enum_entries(categories_text, "FunctionCategory") cat_map = {name: parse_java_string(args[0]) for name, args in cats} funcs = parse_enum_entries(funcs_text, "FunctionTypeEnum") variates = parse_enum_entries(variates_text, "SystemVariateEnum") lines: list[str] = [] lines.append("//! 公式编辑器的**函数目录**与**系统变量目录**。") lines.append("//!") lines.append("//! 🔴 **本文件是生成物,不许手改** —— 由 `scripts/gen-function-catalog.py`") lines.append("//! 从官方 Java 枚举逐条转出:") lines.append("//! `jnpf-system-entity/.../model/variate/{FunctionTypeEnum,SystemVariateEnum}.java`") lines.append("//! 改了官方枚举就重跑脚本;`gen-function-catalog.py --check` 是闸门。") lines.append("//!") lines.append("//! 为什么值得生成:这 100+ 条是**前端公式编辑器的下拉与帮助文本**(含 HTML),") lines.append("//! 手抄漏一条不会有任何编译/测试报错,只会让某个函数在帮助里点不开。") lines.append("") lines.append("/// 一条公式函数。") lines.append("pub struct FuncEntry {") lines.append(" /// 函数名(`SUM` / `ROUND` …),也是表达式里的写法。") lines.append(" pub name: &'static str,") lines.append(" /// 帮助文本(**HTML 片段**,前端直接 v-html 渲染)。") lines.append(" pub description: &'static str,") lines.append(" /// 分类枚举名(`MATH` / `TIME` …)。") lines.append(" pub category: &'static str,") lines.append(" /// 分类中文名(`数学函数` …)—— 与 `category` 一一对应,冗余存一份。") lines.append(" pub sub_category: &'static str,") lines.append("}") lines.append("") lines.append("/// 一条系统变量(`@userId` 之类,公式里可直接引用)。") lines.append("pub struct VariateEntry {") lines.append(" /// 变量名(含 `@` 前缀)。") lines.append(" pub field: &'static str,") lines.append(" /// 中文说明。") lines.append(" pub description: &'static str,") lines.append("}") lines.append("") # 分类(含「全部函数」——官方 `FunctionCategory.ALL` 在树里被排除) lines.append("/// 函数分类(官方 `FunctionCategory` 全量,**含** `ALL`)。") lines.append("pub const FUNCTION_CATEGORIES: &[(&str, &str)] = &[") for name, label in cat_map.items(): lines.append(f" ({rust_str(name)}, {rust_str(label)}),") lines.append("];") lines.append("") lines.append(f"/// 公式函数目录({len(funcs)} 条,官方 `FunctionTypeEnum` 逐条)。") lines.append("pub const FUNCTIONS: &[FuncEntry] = &[") for _name, args in funcs: if len(args) < 4: continue fname = parse_java_string(args[0]) desc = parse_java_string(args[1]) cat = args[2].strip().split(".")[-1] sub = parse_java_string(args[3]) lines.append(" FuncEntry {") lines.append(f" name: {rust_str(fname)},") lines.append(f" description: {rust_str(desc)},") lines.append(f" category: {rust_str(cat)},") lines.append(f" sub_category: {rust_str(sub)},") lines.append(" },") lines.append("];") lines.append("") lines.append(f"/// 系统变量目录({len(variates)} 条,官方 `SystemVariateEnum` 逐条)。") lines.append("pub const SYSTEM_VARIATES: &[VariateEntry] = &[") for _name, args in variates: if len(args) < 2: continue field = parse_java_string(args[0]) desc = parse_java_string(args[1]) lines.append(" VariateEntry {") lines.append(f" field: {rust_str(field)},") lines.append(f" description: {rust_str(desc)},") lines.append(" },") lines.append("];") lines.append("") return "\n".join(lines) def main() -> int: text = gen() if "--check" in sys.argv: if not OUT.exists(): print(f"❌ 生成物不存在:{OUT}") return 1 current = OUT.read_text(encoding="utf-8") if current != text: print("❌ 生成物与官方枚举不一致,请重跑 scripts/gen-function-catalog.py") return 1 print("✅ 函数/变量目录与官方枚举一致") return 0 OUT.write_text(text, encoding="utf-8") print(f"已写入 {OUT}({len(text.splitlines())} 行)") return 0 if __name__ == "__main__": raise SystemExit(main())