Skip to main content

aether/builtins/
help.rs

1// src/builtins/help.rs
2//! 帮助文档系统
3
4use crate::evaluator::RuntimeError;
5use crate::value::Value;
6use std::collections::HashMap;
7use std::sync::OnceLock;
8
9/// 全局函数文档存储
10static FUNCTION_DOCS: OnceLock<HashMap<String, FunctionDocData>> = OnceLock::new();
11
12/// 函数文档数据
13#[derive(Debug, Clone)]
14pub struct FunctionDocData {
15    /// 函数名称
16    pub name: String,
17    /// 函数描述
18    pub description: String,
19    /// 参数列表(参数名和描述)
20    pub params: Vec<(String, String)>,
21    /// 返回值描述
22    pub returns: String,
23    /// 使用示例
24    pub example: Option<String>,
25}
26
27/// 初始化函数文档
28pub fn init_docs() -> HashMap<String, FunctionDocData> {
29    let mut docs = HashMap::new();
30
31    // 精确计算函数
32    docs.insert(
33        "TO_FRACTION".to_string(),
34        FunctionDocData {
35            name: "TO_FRACTION".to_string(),
36            description: "将数字转换为分数,用于精确计算".to_string(),
37            params: vec![("value".to_string(), "要转换的数字或分数".to_string())],
38            returns: "转换后的分数值".to_string(),
39            example: Some("TO_FRACTION(0.5)  => 1/2\nTO_FRACTION(0.333)  => 333/1000".to_string()),
40        },
41    );
42
43    docs.insert(
44        "TO_FLOAT".to_string(),
45        FunctionDocData {
46            name: "TO_FLOAT".to_string(),
47            description: "将分数转换为浮点数".to_string(),
48            params: vec![("fraction".to_string(), "要转换的分数值".to_string())],
49            returns: "转换后的浮点数".to_string(),
50            example: Some("TO_FLOAT(TO_FRACTION(1/3))  => 0.333...".to_string()),
51        },
52    );
53
54    docs.insert(
55        "FRAC_ADD".to_string(),
56        FunctionDocData {
57            name: "FRAC_ADD".to_string(),
58            description: "分数加法运算,保证精确计算".to_string(),
59            params: vec![
60                ("a".to_string(), "第一个加数(数字或分数)".to_string()),
61                ("b".to_string(), "第二个加数(数字或分数)".to_string()),
62            ],
63            returns: "两个分数相加的精确结果".to_string(),
64            example: Some("FRAC_ADD(0.1, 0.2)  => 3/10 (而非 0.30000000000000004)".to_string()),
65        },
66    );
67
68    docs.insert(
69        "FRAC_SUB".to_string(),
70        FunctionDocData {
71            name: "FRAC_SUB".to_string(),
72            description: "分数减法运算,保证精确计算".to_string(),
73            params: vec![
74                ("a".to_string(), "被减数(数字或分数)".to_string()),
75                ("b".to_string(), "减数(数字或分数)".to_string()),
76            ],
77            returns: "两个分数相减的精确结果".to_string(),
78            example: Some("FRAC_SUB(0.5, 0.25)  => 1/4".to_string()),
79        },
80    );
81
82    docs.insert(
83        "FRAC_MUL".to_string(),
84        FunctionDocData {
85            name: "FRAC_MUL".to_string(),
86            description: "分数乘法运算,保证精确计算".to_string(),
87            params: vec![
88                ("a".to_string(), "第一个乘数(数字或分数)".to_string()),
89                ("b".to_string(), "第二个乘数(数字或分数)".to_string()),
90            ],
91            returns: "两个分数相乘的精确结果".to_string(),
92            example: Some("FRAC_MUL(0.1, 0.3)  => 3/100".to_string()),
93        },
94    );
95
96    docs.insert(
97        "FRAC_DIV".to_string(),
98        FunctionDocData {
99            name: "FRAC_DIV".to_string(),
100            description: "分数除法运算,保证精确计算,除数不能为零".to_string(),
101            params: vec![
102                ("a".to_string(), "被除数(数字或分数)".to_string()),
103                ("b".to_string(), "除数(数字或分数,不能为零)".to_string()),
104            ],
105            returns: "两个分数相除的精确结果".to_string(),
106            example: Some("FRAC_DIV(1, 3)  => 1/3".to_string()),
107        },
108    );
109
110    docs.insert(
111        "NUMERATOR".to_string(),
112        FunctionDocData {
113            name: "NUMERATOR".to_string(),
114            description: "获取分数的分子".to_string(),
115            params: vec![("fraction".to_string(), "分数值".to_string())],
116            returns: "分数的分子(浮点数)".to_string(),
117            example: Some("NUMERATOR(TO_FRACTION(3/4))  => 3".to_string()),
118        },
119    );
120
121    docs.insert(
122        "DENOMINATOR".to_string(),
123        FunctionDocData {
124            name: "DENOMINATOR".to_string(),
125            description: "获取分数的分母".to_string(),
126            params: vec![("fraction".to_string(), "分数值".to_string())],
127            returns: "分数的分母(浮点数)".to_string(),
128            example: Some("DENOMINATOR(TO_FRACTION(3/4))  => 4".to_string()),
129        },
130    );
131
132    docs.insert(
133        "GCD".to_string(),
134        FunctionDocData {
135            name: "GCD".to_string(),
136            description: "计算两个整数的最大公约数(Greatest Common Divisor)".to_string(),
137            params: vec![
138                ("a".to_string(), "第一个整数".to_string()),
139                ("b".to_string(), "第二个整数".to_string()),
140            ],
141            returns: "两个数的最大公约数".to_string(),
142            example: Some("GCD(12, 18)  => 6\nGCD(7, 13)  => 1".to_string()),
143        },
144    );
145
146    docs.insert(
147        "LCM".to_string(),
148        FunctionDocData {
149            name: "LCM".to_string(),
150            description: "计算两个整数的最小公倍数(Least Common Multiple)".to_string(),
151            params: vec![
152                ("a".to_string(), "第一个整数".to_string()),
153                ("b".to_string(), "第二个整数".to_string()),
154            ],
155            returns: "两个数的最小公倍数".to_string(),
156            example: Some("LCM(4, 6)  => 12\nLCM(3, 5)  => 15".to_string()),
157        },
158    );
159
160    // I/O 函数
161    docs.insert(
162        "PRINT".to_string(),
163        FunctionDocData {
164            name: "PRINT".to_string(),
165            description: "输出内容到控制台(不换行)".to_string(),
166            params: vec![("value".to_string(), "要输出的值".to_string())],
167            returns: "null".to_string(),
168            example: Some("PRINT(\"Hello\")  => 输出: Hello".to_string()),
169        },
170    );
171
172    docs.insert(
173        "PRINTLN".to_string(),
174        FunctionDocData {
175            name: "PRINTLN".to_string(),
176            description: "输出内容到控制台并换行".to_string(),
177            params: vec![("value".to_string(), "要输出的值".to_string())],
178            returns: "null".to_string(),
179            example: Some("PRINTLN(\"Hello World\")  => 输出: Hello World\\n".to_string()),
180        },
181    );
182
183    docs.insert(
184        "INPUT".to_string(),
185        FunctionDocData {
186            name: "INPUT".to_string(),
187            description: "从控制台读取用户输入".to_string(),
188            params: vec![("prompt".to_string(), "提示信息".to_string())],
189            returns: "用户输入的字符串".to_string(),
190            example: Some("name = INPUT(\"请输入姓名: \")".to_string()),
191        },
192    );
193
194    docs.insert(
195        "TRACE".to_string(),
196        FunctionDocData {
197            name: "TRACE".to_string(),
198            description: "记录调试信息到引擎内存缓冲区(宿主可读取,不产生 IO)".to_string(),
199            params: vec![("value".to_string(), "要记录的值(任意类型)".to_string())],
200            returns: "null".to_string(),
201            example: Some("TRACE(\"x=\" + TO_STRING(X))\nTRACE({\"a\": 1})".to_string()),
202        },
203    );
204
205    // 数组函数
206    docs.insert(
207        "RANGE".to_string(),
208        FunctionDocData {
209            name: "RANGE".to_string(),
210            description: "生成数字范围数组".to_string(),
211            params: vec![(
212                "end".to_string(),
213                "结束值(可选: start, end, step)".to_string(),
214            )],
215            returns: "数字数组".to_string(),
216            example: Some("RANGE(5)  => [0,1,2,3,4]\nRANGE(2, 8, 2)  => [2,4,6]".to_string()),
217        },
218    );
219
220    docs.insert(
221        "LEN".to_string(),
222        FunctionDocData {
223            name: "LEN".to_string(),
224            description: "获取数组、字符串或字典的长度".to_string(),
225            params: vec![("value".to_string(), "数组、字符串或字典".to_string())],
226            returns: "长度值".to_string(),
227            example: Some("LEN([1,2,3])  => 3\nLEN(\"hello\")  => 5".to_string()),
228        },
229    );
230
231    docs.insert(
232        "PUSH".to_string(),
233        FunctionDocData {
234            name: "PUSH".to_string(),
235            description: "向数组末尾添加元素".to_string(),
236            params: vec![
237                ("array".to_string(), "目标数组".to_string()),
238                ("element".to_string(), "要添加的元素".to_string()),
239            ],
240            returns: "新数组".to_string(),
241            example: Some("PUSH([1,2], 3)  => [1,2,3]".to_string()),
242        },
243    );
244
245    docs.insert(
246        "POP".to_string(),
247        FunctionDocData {
248            name: "POP".to_string(),
249            description: "移除并返回数组最后一个元素".to_string(),
250            params: vec![("array".to_string(), "目标数组".to_string())],
251            returns: "被移除的元素".to_string(),
252            example: Some("POP([1,2,3])  => 3".to_string()),
253        },
254    );
255
256    docs.insert(
257        "REVERSE".to_string(),
258        FunctionDocData {
259            name: "REVERSE".to_string(),
260            description: "反转数组元素顺序".to_string(),
261            params: vec![("array".to_string(), "要反转的数组".to_string())],
262            returns: "反转后的数组".to_string(),
263            example: Some("REVERSE([1,2,3])  => [3,2,1]".to_string()),
264        },
265    );
266
267    docs.insert(
268        "SORT".to_string(),
269        FunctionDocData {
270            name: "SORT".to_string(),
271            description: "对数组进行排序".to_string(),
272            params: vec![("array".to_string(), "要排序的数组".to_string())],
273            returns: "排序后的数组".to_string(),
274            example: Some("SORT([3,1,2])  => [1,2,3]".to_string()),
275        },
276    );
277
278    docs.insert(
279        "SUM".to_string(),
280        FunctionDocData {
281            name: "SUM".to_string(),
282            description: "计算数组元素之和".to_string(),
283            params: vec![("array".to_string(), "数字数组".to_string())],
284            returns: "总和".to_string(),
285            example: Some("SUM([1,2,3,4])  => 10".to_string()),
286        },
287    );
288
289    docs.insert(
290        "MAX".to_string(),
291        FunctionDocData {
292            name: "MAX".to_string(),
293            description: "找出数组中的最大值".to_string(),
294            params: vec![("array".to_string(), "数字数组".to_string())],
295            returns: "最大值".to_string(),
296            example: Some("MAX([1,5,3,2])  => 5".to_string()),
297        },
298    );
299
300    docs.insert(
301        "MIN".to_string(),
302        FunctionDocData {
303            name: "MIN".to_string(),
304            description: "找出数组中的最小值".to_string(),
305            params: vec![("array".to_string(), "数字数组".to_string())],
306            returns: "最小值".to_string(),
307            example: Some("MIN([1,5,3,2])  => 1".to_string()),
308        },
309    );
310
311    // 字符串函数
312    docs.insert(
313        "SPLIT".to_string(),
314        FunctionDocData {
315            name: "SPLIT".to_string(),
316            description: "按分隔符分割字符串".to_string(),
317            params: vec![
318                ("string".to_string(), "要分割的字符串".to_string()),
319                ("separator".to_string(), "分隔符".to_string()),
320            ],
321            returns: "字符串数组".to_string(),
322            example: Some("SPLIT(\"a,b,c\", \",\")  => [\"a\",\"b\",\"c\"]".to_string()),
323        },
324    );
325
326    docs.insert(
327        "UPPER".to_string(),
328        FunctionDocData {
329            name: "UPPER".to_string(),
330            description: "将字符串转换为大写".to_string(),
331            params: vec![("string".to_string(), "源字符串".to_string())],
332            returns: "大写字符串".to_string(),
333            example: Some("UPPER(\"hello\")  => \"HELLO\"".to_string()),
334        },
335    );
336
337    docs.insert(
338        "LOWER".to_string(),
339        FunctionDocData {
340            name: "LOWER".to_string(),
341            description: "将字符串转换为小写".to_string(),
342            params: vec![("string".to_string(), "源字符串".to_string())],
343            returns: "小写字符串".to_string(),
344            example: Some("LOWER(\"HELLO\")  => \"hello\"".to_string()),
345        },
346    );
347
348    docs.insert(
349        "TRIM".to_string(),
350        FunctionDocData {
351            name: "TRIM".to_string(),
352            description: "去除字符串首尾空白字符".to_string(),
353            params: vec![("string".to_string(), "源字符串".to_string())],
354            returns: "去除空白后的字符串".to_string(),
355            example: Some("TRIM(\"  hello  \")  => \"hello\"".to_string()),
356        },
357    );
358
359    // 数学函数 - 基础
360    docs.insert(
361        "ABS".to_string(),
362        FunctionDocData {
363            name: "ABS".to_string(),
364            description: "计算绝对值".to_string(),
365            params: vec![("x".to_string(), "数字".to_string())],
366            returns: "绝对值".to_string(),
367            example: Some("ABS(-5)  => 5".to_string()),
368        },
369    );
370
371    docs.insert(
372        "SQRT".to_string(),
373        FunctionDocData {
374            name: "SQRT".to_string(),
375            description: "计算平方根".to_string(),
376            params: vec![("x".to_string(), "数字".to_string())],
377            returns: "平方根".to_string(),
378            example: Some("SQRT(16)  => 4".to_string()),
379        },
380    );
381
382    docs.insert(
383        "POW".to_string(),
384        FunctionDocData {
385            name: "POW".to_string(),
386            description: "计算幂次方".to_string(),
387            params: vec![
388                ("base".to_string(), "底数".to_string()),
389                ("exponent".to_string(), "指数".to_string()),
390            ],
391            returns: "幂运算结果".to_string(),
392            example: Some("POW(2, 10)  => 1024".to_string()),
393        },
394    );
395
396    docs.insert(
397        "FLOOR".to_string(),
398        FunctionDocData {
399            name: "FLOOR".to_string(),
400            description: "向下取整".to_string(),
401            params: vec![("x".to_string(), "数字".to_string())],
402            returns: "不大于x的最大整数".to_string(),
403            example: Some("FLOOR(3.7)  => 3".to_string()),
404        },
405    );
406
407    docs.insert(
408        "CEIL".to_string(),
409        FunctionDocData {
410            name: "CEIL".to_string(),
411            description: "向上取整".to_string(),
412            params: vec![("x".to_string(), "数字".to_string())],
413            returns: "不小于x的最小整数".to_string(),
414            example: Some("CEIL(3.2)  => 4".to_string()),
415        },
416    );
417
418    docs.insert(
419        "ROUND".to_string(),
420        FunctionDocData {
421            name: "ROUND".to_string(),
422            description: "四舍五入到最接近的整数".to_string(),
423            params: vec![("x".to_string(), "数字".to_string())],
424            returns: "四舍五入后的整数".to_string(),
425            example: Some("ROUND(3.6)  => 4".to_string()),
426        },
427    );
428
429    // 数学函数 - 三角函数
430    docs.insert(
431        "SIN".to_string(),
432        FunctionDocData {
433            name: "SIN".to_string(),
434            description: "计算正弦值(弧度)".to_string(),
435            params: vec![("x".to_string(), "角度(弧度)".to_string())],
436            returns: "正弦值".to_string(),
437            example: Some("SIN(PI()/2)  => 1".to_string()),
438        },
439    );
440
441    docs.insert(
442        "COS".to_string(),
443        FunctionDocData {
444            name: "COS".to_string(),
445            description: "计算余弦值(弧度)".to_string(),
446            params: vec![("x".to_string(), "角度(弧度)".to_string())],
447            returns: "余弦值".to_string(),
448            example: Some("COS(0)  => 1".to_string()),
449        },
450    );
451
452    docs.insert(
453        "TAN".to_string(),
454        FunctionDocData {
455            name: "TAN".to_string(),
456            description: "计算正切值(弧度)".to_string(),
457            params: vec![("x".to_string(), "角度(弧度)".to_string())],
458            returns: "正切值".to_string(),
459            example: Some("TAN(PI()/4)  => 1".to_string()),
460        },
461    );
462
463    // 数学常数
464    docs.insert(
465        "PI".to_string(),
466        FunctionDocData {
467            name: "PI".to_string(),
468            description: "圆周率 π ≈ 3.14159...".to_string(),
469            params: vec![],
470            returns: "π 的值".to_string(),
471            example: Some("PI()  => 3.141592653589793".to_string()),
472        },
473    );
474
475    docs.insert(
476        "E".to_string(),
477        FunctionDocData {
478            name: "E".to_string(),
479            description: "自然常数 e ≈ 2.71828...".to_string(),
480            params: vec![],
481            returns: "e 的值".to_string(),
482            example: Some("E()  => 2.718281828459045".to_string()),
483        },
484    );
485
486    // 统计函数
487    docs.insert(
488        "MEAN".to_string(),
489        FunctionDocData {
490            name: "MEAN".to_string(),
491            description: "计算数组的平均值".to_string(),
492            params: vec![("array".to_string(), "数字数组".to_string())],
493            returns: "平均值".to_string(),
494            example: Some("MEAN([1,2,3,4,5])  => 3".to_string()),
495        },
496    );
497
498    docs.insert(
499        "MEDIAN".to_string(),
500        FunctionDocData {
501            name: "MEDIAN".to_string(),
502            description: "计算数组的中位数".to_string(),
503            params: vec![("array".to_string(), "数字数组".to_string())],
504            returns: "中位数".to_string(),
505            example: Some("MEDIAN([1,2,3,4,5])  => 3".to_string()),
506        },
507    );
508
509    docs.insert(
510        "VARIANCE".to_string(),
511        FunctionDocData {
512            name: "VARIANCE".to_string(),
513            description: "计算数组的方差".to_string(),
514            params: vec![("array".to_string(), "数字数组".to_string())],
515            returns: "方差".to_string(),
516            example: Some("VARIANCE([1,2,3,4,5])  => 2".to_string()),
517        },
518    );
519
520    docs.insert(
521        "STD".to_string(),
522        FunctionDocData {
523            name: "STD".to_string(),
524            description: "计算数组的标准差".to_string(),
525            params: vec![("array".to_string(), "数字数组".to_string())],
526            returns: "标准差".to_string(),
527            example: Some("STD([1,2,3,4,5])  => 1.414...".to_string()),
528        },
529    );
530
531    // 类型转换函数
532    docs.insert(
533        "TYPE".to_string(),
534        FunctionDocData {
535            name: "TYPE".to_string(),
536            description: "获取值的类型".to_string(),
537            params: vec![("value".to_string(), "任意值".to_string())],
538            returns: "类型名称字符串".to_string(),
539            example: Some("TYPE(123)  => \"Number\"\nTYPE(\"hello\")  => \"String\"".to_string()),
540        },
541    );
542
543    docs.insert(
544        "TO_STRING".to_string(),
545        FunctionDocData {
546            name: "TO_STRING".to_string(),
547            description: "将值转换为字符串".to_string(),
548            params: vec![("value".to_string(), "要转换的值".to_string())],
549            returns: "字符串".to_string(),
550            example: Some("TO_STRING(123)  => \"123\"".to_string()),
551        },
552    );
553
554    docs.insert(
555        "TO_NUMBER".to_string(),
556        FunctionDocData {
557            name: "TO_NUMBER".to_string(),
558            description: "将字符串转换为数字".to_string(),
559            params: vec![("string".to_string(), "数字字符串".to_string())],
560            returns: "数字".to_string(),
561            example: Some("TO_NUMBER(\"123\")  => 123".to_string()),
562        },
563    );
564
565    docs
566}
567
568/// HELP 函数实现
569///
570/// 用法:
571/// - HELP() - 列出所有可用函数
572/// - HELP("函数名") - 显示特定函数的详细文档
573pub fn help(args: &[Value]) -> Result<Value, RuntimeError> {
574    // 初始化文档(只执行一次)
575    let docs = FUNCTION_DOCS.get_or_init(init_docs);
576
577    if args.is_empty() {
578        // 列出所有函数
579        let mut output = String::from("=== Aether 内置函数列表 ===\n\n");
580
581        // 按类别组织函数
582        let categories = vec![
583            (
584                "精确计算",
585                vec![
586                    "TO_FRACTION",
587                    "TO_FLOAT",
588                    "FRAC_ADD",
589                    "FRAC_SUB",
590                    "FRAC_MUL",
591                    "FRAC_DIV",
592                    "NUMERATOR",
593                    "DENOMINATOR",
594                    "GCD",
595                    "LCM",
596                ],
597            ),
598            ("输入输出", vec!["PRINT", "PRINTLN", "INPUT"]),
599            ("调试", vec!["TRACE"]),
600            (
601                "数组操作",
602                vec![
603                    "RANGE", "LEN", "PUSH", "POP", "REVERSE", "SORT", "SUM", "MAX", "MIN",
604                ],
605            ),
606            (
607                "字符串操作",
608                vec![
609                    "SPLIT",
610                    "UPPER",
611                    "LOWER",
612                    "TRIM",
613                    "CONTAINS",
614                    "STARTS_WITH",
615                    "ENDS_WITH",
616                    "REPLACE",
617                    "REPEAT",
618                    "JOIN",
619                ],
620            ),
621            (
622                "数学函数 - 基础",
623                vec!["ABS", "SQRT", "POW", "FLOOR", "CEIL", "ROUND"],
624            ),
625            (
626                "数学函数 - 三角",
627                vec!["SIN", "COS", "TAN", "ASIN", "ACOS", "ATAN", "ATAN2"],
628            ),
629            ("数学函数 - 对数", vec!["LOG", "LN", "LOG2", "EXP", "EXP2"]),
630            ("数学常数", vec!["PI", "E", "TAU", "PHI"]),
631            (
632                "统计分析",
633                vec!["MEAN", "MEDIAN", "VARIANCE", "STD", "QUANTILE"],
634            ),
635            (
636                "向量运算",
637                vec!["DOT", "NORM", "CROSS", "DISTANCE", "NORMALIZE"],
638            ),
639            (
640                "矩阵运算",
641                vec!["MATMUL", "TRANSPOSE", "DETERMINANT", "INVERSE"],
642            ),
643            ("线性回归", vec!["LINEAR_REGRESSION"]),
644            ("概率分布", vec!["NORMAL_PDF", "NORMAL_CDF", "POISSON_PMF"]),
645            (
646                "精度计算",
647                vec![
648                    "ROUND_TO",
649                    "ADD_WITH_PRECISION",
650                    "SUB_WITH_PRECISION",
651                    "MUL_WITH_PRECISION",
652                    "DIV_WITH_PRECISION",
653                ],
654            ),
655            ("类型转换", vec!["TYPE", "TO_STRING", "TO_NUMBER"]),
656            ("字典操作", vec!["KEYS", "VALUES", "HAS", "MERGE"]),
657        ];
658
659        // 补齐分类清单之外的已注册函数(薪酬/工资折算/IO/结构化跟踪/
660        // 生成器/高级数学/字符串与数组补充等)——HELP() 必须覆盖全部
661        // 注册函数,防止「存在但不可发现」
662        let extra_categories: Vec<(&str, Vec<&str>)> = vec![
663            ("生成器", vec!["NEXT", "DONE"]),
664            (
665                "结构化跟踪",
666                vec!["TRACE_DEBUG", "TRACE_INFO", "TRACE_WARN", "TRACE_ERROR"],
667            ),
668            (
669                "字符串操作(补充)",
670                vec!["CHARAT", "STRLEN", "STRSLICE", "INDEXOF"],
671            ),
672            ("数组与函数式", vec!["FILTER", "MAP", "REDUCE"]),
673            ("JSON 处理", vec!["JSON_PARSE", "JSON_STRINGIFY"]),
674            (
675                "高级数学",
676                vec![
677                    "SIGN",
678                    "CLAMP",
679                    "FACTORIAL",
680                    "ERF",
681                    "GAMMA",
682                    "HYPOT",
683                    "SINH",
684                    "COSH",
685                    "TANH",
686                    "EXPM1",
687                    "LOG1P",
688                ],
689            ),
690            (
691                "精确计算(补充)",
692                vec![
693                    "SET_PRECISION",
694                    "ADD_WITH_PRECISION",
695                    "SUB_WITH_PRECISION",
696                    "MUL_WITH_PRECISION",
697                    "DIV_WITH_PRECISION",
698                ],
699            ),
700            (
701                "文件操作",
702                vec![
703                    "READ_FILE",
704                    "WRITE_FILE",
705                    "APPEND_FILE",
706                    "DELETE_FILE",
707                    "FILE_EXISTS",
708                    "LIST_DIR",
709                    "CREATE_DIR",
710                ],
711            ),
712            (
713                "工资折算",
714                vec![
715                    "ANNUAL_TO_MONTHLY",
716                    "MONTHLY_TO_ANNUAL",
717                    "DAILY_TO_MONTHLY",
718                    "MONTHLY_TO_DAILY",
719                    "HOURLY_TO_MONTHLY",
720                    "MONTHLY_TO_HOURLY",
721                ],
722            ),
723            (
724                "薪酬计算",
725                vec![
726                    "CALC_BASE_SALARY",
727                    "CALC_GROSS_SALARY",
728                    "CALC_NET_SALARY",
729                    "CALC_HOURLY_PAY",
730                    "CALC_DAILY_PAY",
731                    "CALC_MONTHLY_FROM_HOURLY",
732                    "CALC_ONBOARDING_SALARY",
733                    "CALC_RESIGNATION_SALARY",
734                    "CALC_13TH_SALARY",
735                    "CALC_14TH_SALARY",
736                    "CALC_PERFORMANCE_PAY",
737                    "CALC_SALES_COMMISSION",
738                    "CALC_PROJECT_BONUS",
739                    "CALC_ANNUAL_BONUS",
740                    "CALC_ANNUAL_SALARY",
741                    "CALC_ANNUAL_BONUS_TAX",
742                ],
743            ),
744            (
745                "个税与社保",
746                vec![
747                    "CALC_PERSONAL_TAX",
748                    "CALC_TAXABLE_INCOME",
749                    "CALC_EFFECTIVE_TAX_RATE",
750                    "CALC_TAX_REFUND",
751                    "CALC_GROSS_FROM_NET",
752                    "CALC_PENSION_INSURANCE",
753                    "CALC_MEDICAL_INSURANCE",
754                    "CALC_UNEMPLOYMENT_INSURANCE",
755                    "CALC_INJURY_INSURANCE",
756                    "CALC_MATERNITY_INSURANCE",
757                    "CALC_HOUSING_FUND",
758                    "CALC_SOCIAL_INSURANCE",
759                    "CALC_SOCIAL_BASE_LOWER",
760                    "CALC_SOCIAL_BASE_UPPER",
761                    "ADJUST_SOCIAL_BASE",
762                ],
763            ),
764            (
765                "加班与考勤",
766                vec![
767                    "CALC_OVERTIME_PAY",
768                    "CALC_WEEKDAY_OVERTIME",
769                    "CALC_WEEKEND_OVERTIME",
770                    "CALC_HOLIDAY_OVERTIME",
771                    "CALC_TOTAL_OVERTIME",
772                    "CALC_LATE_DEDUCTION",
773                    "CALC_EARLY_LEAVE_DEDUCTION",
774                    "CALC_ABSENT_DEDUCTION",
775                    "CALC_LEAVE_DEDUCTION",
776                    "CALC_UNPAID_LEAVE_DEDUCTION",
777                    "CALC_SICK_LEAVE_PAY",
778                    "CALC_ATTENDANCE_BONUS",
779                    "CALC_ATTENDANCE_RATE",
780                ],
781            ),
782            (
783                "津贴补贴",
784                vec![
785                    "CALC_MEAL_ALLOWANCE",
786                    "CALC_TRANSPORT_ALLOWANCE",
787                    "CALC_COMMUNICATION_ALLOWANCE",
788                    "CALC_POSITION_ALLOWANCE",
789                    "CALC_HOUSING_ALLOWANCE",
790                    "CALC_HIGH_TEMP_ALLOWANCE",
791                    "CALC_NIGHT_SHIFT_ALLOWANCE",
792                ],
793            ),
794            (
795                "薪酬统计",
796                vec![
797                    "CALC_SALARY_AVERAGE",
798                    "CALC_SALARY_MEDIAN",
799                    "CALC_SALARY_RANGE",
800                    "CALC_SALARY_STD_DEV",
801                    "CALC_SALARY_DISTRIBUTION",
802                    "CALC_PERCENTILE",
803                ],
804            ),
805            (
806                "日期与折算比例",
807                vec![
808                    "CALC_NATURAL_DAYS",
809                    "CALC_WEEKEND_DAYS",
810                    "CALC_WORK_HOURS",
811                    "CALC_MONTHLY_WORK_HOURS",
812                    "IS_WEEKEND",
813                    "IS_WORKDAY",
814                    "PRORATE_BY_NATURAL_DAYS",
815                    "PRORATE_BY_WORKDAYS",
816                    "PRORATE_BY_LEGAL_DAYS",
817                ],
818            ),
819            ("帮助", vec!["HELP"]),
820        ];
821        let mut categories = categories;
822        categories.extend(extra_categories);
823
824        for (category, funcs) in categories {
825            output.push_str(&format!("【{}】\n", category));
826            for func_name in funcs {
827                match docs.get(func_name) {
828                    Some(doc) => {
829                        output.push_str(&format!("  {} - {}\n", doc.name, doc.description))
830                    }
831                    // 无详细文档的函数也必须列出(可发现性优先),
832                    // 用 HELP("名字") 查询时同样会提示文档待补
833                    None => output.push_str(&format!("  {}\n", func_name)),
834                }
835            }
836            output.push('\n');
837        }
838
839        output.push_str("使用 HELP(\"函数名\") 查看详细文档\n");
840        output.push_str("例如: HELP(\"TO_FRACTION\")\n");
841
842        Ok(Value::String(output))
843    } else if args.len() == 1 {
844        // 显示特定函数的文档
845        match &args[0] {
846            Value::String(func_name) => {
847                let func_name_upper = func_name.to_uppercase();
848
849                if let Some(doc) = docs.get(&func_name_upper) {
850                    let mut output = "=".repeat(50);
851                    output.push_str(&format!("\n函数: {}\n", doc.name));
852                    output.push_str(&"=".repeat(50));
853                    output.push_str(&format!("\n\n描述:\n  {}\n\n", doc.description));
854
855                    if !doc.params.is_empty() {
856                        output.push_str("参数:\n");
857                        for (param_name, param_desc) in &doc.params {
858                            output.push_str(&format!("  - {}: {}\n", param_name, param_desc));
859                        }
860                        output.push('\n');
861                    }
862
863                    output.push_str(&format!("返回值:\n  {}\n\n", doc.returns));
864
865                    if let Some(example) = &doc.example {
866                        output.push_str("示例:\n");
867                        for line in example.lines() {
868                            output.push_str(&format!("  {}\n", line));
869                        }
870                    }
871
872                    output.push_str(&"=".repeat(50));
873                    output.push('\n');
874
875                    Ok(Value::String(output))
876                } else {
877                    Err(RuntimeError::InvalidOperation(format!(
878                        "函数 '{}' 不存在。使用 HELP() 查看所有可用函数。",
879                        func_name
880                    )))
881                }
882            }
883            _ => Err(RuntimeError::TypeErrorDetailed {
884                expected: "String".to_string(),
885                got: format!("{:?}", args[0]),
886            }),
887        }
888    } else {
889        Err(RuntimeError::WrongArity {
890            expected: 0, // or 1
891            got: args.len(),
892        })
893    }
894}