aether/builtins/string.rs
1// src/builtins/string.rs
2//! String manipulation built-in functions
3
4use crate::evaluator::RuntimeError;
5use crate::value::Value;
6
7/// 分割字符串
8///
9/// # 功能
10/// 使用指定的分隔符将字符串分割成数组。
11///
12/// # 参数
13/// - `string`: String - 要分割的字符串
14/// - `separator`: String - 分隔符
15///
16/// # 返回值
17/// Array - 包含分割后的子字符串的数组
18///
19/// # 示例
20/// ```aether
21/// Set TEXT "apple,banana,cherry"
22/// Set FRUITS SPLIT(TEXT, ",") // ["apple", "banana", "cherry"]
23/// Set SENTENCE "Hello World"
24/// Set WORDS SPLIT(SENTENCE, " ") // ["Hello", "World"]
25/// Set CSV "a|b|c|d"
26/// Set PARTS SPLIT(CSV, "|") // ["a", "b", "c", "d"]
27/// ```
28pub fn split(args: &[Value]) -> Result<Value, RuntimeError> {
29 if args.len() != 2 {
30 return Err(RuntimeError::WrongArity {
31 expected: 2,
32 got: args.len(),
33 });
34 }
35
36 match (&args[0], &args[1]) {
37 (Value::String(s), Value::String(sep)) => {
38 let parts: Vec<Value> = s
39 .split(sep.as_str())
40 .map(|p| Value::String(p.to_string()))
41 .collect();
42 Ok(Value::Array(parts))
43 }
44 _ => Err(RuntimeError::TypeErrorDetailed {
45 expected: "String, String".to_string(),
46 got: format!("{:?}, {:?}", args[0], args[1]),
47 }),
48 }
49}
50
51/// 转换为大写
52///
53/// # 功能
54/// 将字符串中的所有字母转换为大写形式。
55///
56/// # 参数
57/// - `string`: String - 要转换的字符串
58///
59/// # 返回值
60/// String - 大写形式的字符串
61///
62/// # 示例
63/// ```aether
64/// Set TEXT "hello world"
65/// Set UPPER UPPER(TEXT) // "HELLO WORLD"
66/// Set MIXED "Hello123"
67/// Set UPPER UPPER(MIXED) // "HELLO123"
68/// ```
69pub fn upper(args: &[Value]) -> Result<Value, RuntimeError> {
70 if args.len() != 1 {
71 return Err(RuntimeError::WrongArity {
72 expected: 1,
73 got: args.len(),
74 });
75 }
76
77 match &args[0] {
78 Value::String(s) => Ok(Value::String(s.to_uppercase())),
79 _ => Err(RuntimeError::TypeErrorDetailed {
80 expected: "String".to_string(),
81 got: format!("{:?}", args[0]),
82 }),
83 }
84}
85
86/// 转换为小写
87///
88/// # 功能
89/// 将字符串中的所有字母转换为小写形式。
90///
91/// # 参数
92/// - `string`: String - 要转换的字符串
93///
94/// # 返回值
95/// String - 小写形式的字符串
96///
97/// # 示例
98/// ```aether
99/// Set TEXT "HELLO WORLD"
100/// Set LOWER LOWER(TEXT) // "hello world"
101/// Set MIXED "Hello123"
102/// Set LOWER LOWER(MIXED) // "hello123"
103/// ```
104pub fn lower(args: &[Value]) -> Result<Value, RuntimeError> {
105 if args.len() != 1 {
106 return Err(RuntimeError::WrongArity {
107 expected: 1,
108 got: args.len(),
109 });
110 }
111
112 match &args[0] {
113 Value::String(s) => Ok(Value::String(s.to_lowercase())),
114 _ => Err(RuntimeError::TypeErrorDetailed {
115 expected: "String".to_string(),
116 got: format!("{:?}", args[0]),
117 }),
118 }
119}
120
121/// 去除首尾空白字符
122///
123/// # 功能
124/// 移除字符串开头和结尾的空白字符(空格、制表符、换行符等)。
125///
126/// # 参数
127/// - `string`: String - 要处理的字符串
128///
129/// # 返回值
130/// String - 去除首尾空白后的字符串
131///
132/// # 示例
133/// ```aether
134/// Set TEXT " hello world "
135/// Set TRIMMED TRIM(TEXT) // "hello world"
136/// Set TEXT "\t\ntest\n\t"
137/// Set TRIMMED TRIM(TEXT) // "test"
138/// ```
139pub fn trim(args: &[Value]) -> Result<Value, RuntimeError> {
140 if args.len() != 1 {
141 return Err(RuntimeError::WrongArity {
142 expected: 1,
143 got: args.len(),
144 });
145 }
146
147 match &args[0] {
148 Value::String(s) => Ok(Value::String(s.trim().to_string())),
149 _ => Err(RuntimeError::TypeErrorDetailed {
150 expected: "String".to_string(),
151 got: format!("{:?}", args[0]),
152 }),
153 }
154}
155
156/// 检查是否包含子字符串
157///
158/// # 功能
159/// 检查字符串是否包含指定的子字符串。
160///
161/// # 参数
162/// - `string`: String - 要检查的字符串
163/// - `substring`: String - 要查找的子字符串
164///
165/// # 返回值
166/// Boolean - 如果包含返回 `True`,否则返回 `False`
167///
168/// # 示例
169/// ```aether
170/// Set TEXT "Hello World"
171/// Set HAS CONTAINS(TEXT, "World") // True
172/// Set HAS CONTAINS(TEXT, "Python") // False
173/// Set EMAIL "user@example.com"
174/// Set HAS CONTAINS(EMAIL, "@") // True
175/// ```
176pub fn contains(args: &[Value]) -> Result<Value, RuntimeError> {
177 if args.len() != 2 {
178 return Err(RuntimeError::WrongArity {
179 expected: 2,
180 got: args.len(),
181 });
182 }
183
184 match (&args[0], &args[1]) {
185 // String contains substring
186 (Value::String(s), Value::String(substr)) => {
187 Ok(Value::Boolean(s.contains(substr.as_str())))
188 }
189 // Array contains element
190 (Value::Array(arr), item) => {
191 for elem in arr.iter() {
192 if values_equal(elem, item) {
193 return Ok(Value::Boolean(true));
194 }
195 }
196 Ok(Value::Boolean(false))
197 }
198 // Dict contains key
199 (Value::Dict(dict), Value::String(key)) => Ok(Value::Boolean(dict.contains_key(key))),
200 _ => Err(RuntimeError::TypeErrorDetailed {
201 expected: "(String, String) or (Array, Any) or (Dict, String)".to_string(),
202 got: format!("{:?}, {:?}", args[0], args[1]),
203 }),
204 }
205}
206
207// Helper function to compare values for equality
208fn values_equal(a: &Value, b: &Value) -> bool {
209 a.equals(b)
210}
211
212/// 检查是否以指定前缀开头
213///
214/// # 功能
215/// 检查字符串是否以指定的前缀开头。
216///
217/// # 参数
218/// - `string`: String - 要检查的字符串
219/// - `prefix`: String - 前缀字符串
220///
221/// # 返回值
222/// Boolean - 如果以该前缀开头返回 `True`,否则返回 `False`
223///
224/// # 示例
225/// ```aether
226/// Set FILENAME "test.txt"
227/// Set STARTS STARTS_WITH(FILENAME, "test") // True
228/// Set STARTS STARTS_WITH(FILENAME, "data") // False
229/// Set URL "https://example.com"
230/// Set ISHTTPS STARTS_WITH(URL, "https://") // True
231/// ```
232pub fn starts_with(args: &[Value]) -> Result<Value, RuntimeError> {
233 if args.len() != 2 {
234 return Err(RuntimeError::WrongArity {
235 expected: 2,
236 got: args.len(),
237 });
238 }
239
240 match (&args[0], &args[1]) {
241 (Value::String(s), Value::String(prefix)) => {
242 Ok(Value::Boolean(s.starts_with(prefix.as_str())))
243 }
244 _ => Err(RuntimeError::TypeErrorDetailed {
245 expected: "String, String".to_string(),
246 got: format!("{:?}, {:?}", args[0], args[1]),
247 }),
248 }
249}
250
251/// 检查是否以指定后缀结尾
252///
253/// # 功能
254/// 检查字符串是否以指定的后缀结尾。
255///
256/// # 参数
257/// - `string`: String - 要检查的字符串
258/// - `suffix`: String - 后缀字符串
259///
260/// # 返回值
261/// Boolean - 如果以该后缀结尾返回 `True`,否则返回 `False`
262///
263/// # 示例
264/// ```aether
265/// Set FILENAME "document.pdf"
266/// Set ISPDF ENDS_WITH(FILENAME, ".pdf") // True
267/// Set ISTXT ENDS_WITH(FILENAME, ".txt") // False
268/// Set EMAIL "user@gmail.com"
269/// Set ISGMAIL ENDS_WITH(EMAIL, "@gmail.com") // True
270/// ```
271pub fn ends_with(args: &[Value]) -> Result<Value, RuntimeError> {
272 if args.len() != 2 {
273 return Err(RuntimeError::WrongArity {
274 expected: 2,
275 got: args.len(),
276 });
277 }
278
279 match (&args[0], &args[1]) {
280 (Value::String(s), Value::String(suffix)) => {
281 Ok(Value::Boolean(s.ends_with(suffix.as_str())))
282 }
283 _ => Err(RuntimeError::TypeErrorDetailed {
284 expected: "String, String".to_string(),
285 got: format!("{:?}, {:?}", args[0], args[1]),
286 }),
287 }
288}
289
290/// 替换字符串中的所有匹配项
291///
292/// # 功能
293/// 将字符串中所有出现的子字符串替换为新的字符串。
294///
295/// # 参数
296/// - `string`: String - 原始字符串
297/// - `from`: String - 要被替换的子字符串
298/// - `to`: String - 替换后的新字符串
299///
300/// # 返回值
301/// String - 替换后的字符串
302///
303/// # 示例
304/// ```aether
305/// Set TEXT "Hello World"
306/// Set REPLACED REPLACE(TEXT, "World", "Aether") // "Hello Aether"
307/// Set TEXT "foo bar foo"
308/// Set REPLACED REPLACE(TEXT, "foo", "baz") // "baz bar baz"
309/// Set PATH "C:\\Users\\Name"
310/// Set FIXED REPLACE(PATH, "\\", "/") // "C:/Users/Name"
311/// ```
312pub fn replace(args: &[Value]) -> Result<Value, RuntimeError> {
313 if args.len() != 3 {
314 return Err(RuntimeError::WrongArity {
315 expected: 3,
316 got: args.len(),
317 });
318 }
319
320 match (&args[0], &args[1], &args[2]) {
321 (Value::String(s), Value::String(from), Value::String(to)) => {
322 Ok(Value::String(s.replace(from.as_str(), to.as_str())))
323 }
324 _ => Err(RuntimeError::TypeErrorDetailed {
325 expected: "String, String, String".to_string(),
326 got: format!("{:?}, {:?}, {:?}", args[0], args[1], args[2]),
327 }),
328 }
329}
330
331/// 重复字符串
332///
333/// # 功能
334/// 将字符串重复指定的次数。
335///
336/// # 参数
337/// - `string`: String - 要重复的字符串
338/// - `count`: Number - 重复次数(必须是非负整数)
339///
340/// # 返回值
341/// String - 重复后的字符串
342///
343/// # 错误
344/// - 重复次数为负数或非整数时抛出错误
345///
346/// # 示例
347/// ```aether
348/// Set STR "Ha"
349/// Set LAUGH REPEAT(STR, 3) // "HaHaHa"
350/// Set DASH "-"
351/// Set LINE REPEAT(DASH, 10) // "----------"
352/// Set SPACE " "
353/// Set INDENT REPEAT(SPACE, 4) // " "
354/// ```
355pub fn repeat(args: &[Value]) -> Result<Value, RuntimeError> {
356 if args.len() != 2 {
357 return Err(RuntimeError::WrongArity {
358 expected: 2,
359 got: args.len(),
360 });
361 }
362
363 match (&args[0], &args[1]) {
364 (Value::String(s), Value::Number(n)) => {
365 if *n < 0.0 || n.fract() != 0.0 {
366 return Err(RuntimeError::InvalidOperation(format!(
367 "Repeat count must be a non-negative integer, got {}",
368 n
369 )));
370 }
371 let count = *n as usize;
372 Ok(Value::String(s.repeat(count)))
373 }
374 _ => Err(RuntimeError::TypeErrorDetailed {
375 expected: "String, Number".to_string(),
376 got: format!("{:?}, {:?}", args[0], args[1]),
377 }),
378 }
379}
380
381/// 字符串切片
382///
383/// # 功能
384/// 提取字符串的子串(基于 **Unicode 字符** 索引)。
385///
386/// # 参数
387/// - `string`: String - 原始字符串
388/// - `start`: Number - 起始索引(包含,从 0 开始;负数从尾部数)
389/// - `end`: Number - 结束索引(不包含;负数从尾部数)
390///
391/// # 返回值
392/// String - 提取的子串;越界端点钳制到范围内,start >= end 返回空串
393///
394/// # 示例
395/// ```aether
396/// Set TEXT "Hello World"
397/// Set A STRSLICE(TEXT, 0, 5) // "Hello"
398/// Set B STRSLICE(TEXT, 6, 11) // "World"
399/// Set C STRSLICE("你好世界", 0, 2) // "你好"(字符语义,非字节)
400/// Set D STRSLICE("你好世界", -2, 4) // "世界"
401/// ```
402pub fn substr(args: &[Value]) -> Result<Value, RuntimeError> {
403 if args.len() != 3 {
404 return Err(RuntimeError::WrongArity {
405 expected: 3,
406 got: args.len(),
407 });
408 }
409
410 match (&args[0], &args[1], &args[2]) {
411 (Value::String(s), Value::Number(start), Value::Number(end)) => {
412 if start.fract() != 0.0 || end.fract() != 0.0 {
413 return Err(RuntimeError::InvalidOperation(
414 "String indices must be integers".to_string(),
415 ));
416 }
417
418 let len = s.chars().count() as i64;
419 // 负索引从尾部数(按字符),越界钳制到 [0, len]
420 let clamp = |idx: i64| -> i64 {
421 let i = if idx < 0 { len + idx } else { idx };
422 i.clamp(0, len)
423 };
424 let start_idx = clamp(*start as i64);
425 let end_idx = clamp(*end as i64);
426
427 if start_idx >= end_idx {
428 return Ok(Value::String(String::new()));
429 }
430
431 let result: String = s
432 .chars()
433 .skip(start_idx as usize)
434 .take((end_idx - start_idx) as usize)
435 .collect();
436 Ok(Value::String(result))
437 }
438 _ => Err(RuntimeError::TypeErrorDetailed {
439 expected: "String, Number, Number".to_string(),
440 got: format!("{:?}, {:?}, {:?}", args[0], args[1], args[2]),
441 }),
442 }
443}
444
445/// 获取字符串长度
446///
447/// # 功能
448/// 返回字符串的**字符数**(多字节字符按 1 个字符计)。
449///
450/// # 参数
451/// - `string`: String - 要测量的字符串
452///
453/// # 返回值
454/// Number - 字符串长度
455///
456/// # 示例
457/// ```aether
458/// Set TEXT "Hello"
459/// Set A STRLEN(TEXT) // 5
460/// Set B STRLEN("你好") // 2(字符语义,非 6 字节)
461/// ```
462pub fn strlen(args: &[Value]) -> Result<Value, RuntimeError> {
463 if args.len() != 1 {
464 return Err(RuntimeError::WrongArity {
465 expected: 1,
466 got: args.len(),
467 });
468 }
469
470 match &args[0] {
471 Value::String(s) => Ok(Value::Number(s.chars().count() as f64)),
472 _ => Err(RuntimeError::TypeErrorDetailed {
473 expected: "String".to_string(),
474 got: format!("{:?}", args[0]),
475 }),
476 }
477}
478
479/// 查找子串位置
480///
481/// # 功能
482/// 查找子串在字符串中首次出现的**字符**位置,未找到返回 -1。
483///
484/// # 参数
485/// - `string`: String - 原始字符串
486/// - `substring`: String - 要查找的子串
487///
488/// # 返回值
489/// Number - 子串起始字符位置(从 0 开始),未找到返回 -1
490///
491/// # 示例
492/// ```aether
493/// Set TEXT "Hello World"
494/// Set A INDEXOF(TEXT, "World") // 6
495/// Set B INDEXOF(TEXT, "xyz") // -1
496/// Set C INDEXOF(TEXT, "l") // 2(第一个 l)
497/// Set D INDEXOF("héllo", "l") // 2(字符位置)
498/// ```
499pub fn index_of(args: &[Value]) -> Result<Value, RuntimeError> {
500 if args.len() != 2 {
501 return Err(RuntimeError::WrongArity {
502 expected: 2,
503 got: args.len(),
504 });
505 }
506
507 match (&args[0], &args[1]) {
508 (Value::String(s), Value::String(substr)) => match s.find(substr.as_str()) {
509 // find 返回字节偏移,换算为字符位置
510 Some(byte_pos) => Ok(Value::Number(s[..byte_pos].chars().count() as f64)),
511 None => Ok(Value::Number(-1.0)),
512 },
513 _ => Err(RuntimeError::TypeErrorDetailed {
514 expected: "String, String".to_string(),
515 got: format!("{:?}, {:?}", args[0], args[1]),
516 }),
517 }
518}
519
520/// 获取指定位置的字符
521///
522/// # 功能
523/// 获取字符串中指定**字符**位置的字符。
524/// 负索引从尾部数(-1 是最后一个字符);越界报错(与 `S[I]` 对齐)。
525///
526/// # 参数
527/// - `string`: String - 原始字符串
528/// - `index`: Number - 字符位置(从 0 开始)
529///
530/// # 返回值
531/// String - 该位置的单个字符
532///
533/// # 错误
534/// - 索引越界(含负索引超出尾部范围)
535///
536/// # 示例
537/// ```aether
538/// Set A CHARAT("Hello", 0) // "H"
539/// Set B CHARAT("Hello", -1) // "o"(从尾部数)
540/// Set C CHARAT("你好", -1) // "好"
541/// ```
542pub fn char_at(args: &[Value]) -> Result<Value, RuntimeError> {
543 if args.len() != 2 {
544 return Err(RuntimeError::WrongArity {
545 expected: 2,
546 got: args.len(),
547 });
548 }
549
550 match (&args[0], &args[1]) {
551 (Value::String(s), Value::Number(idx)) => {
552 if idx.fract() != 0.0 {
553 return Err(RuntimeError::InvalidOperation(
554 "Index must be an integer".to_string(),
555 ));
556 }
557
558 let len = s.chars().count() as i64;
559 let index = *idx as i64;
560 // 负索引从尾部数(按字符)
561 let index = if index < 0 { len + index } else { index };
562 if index < 0 || index >= len {
563 return Err(RuntimeError::InvalidOperation(format!(
564 "CharAt index {idx} out of range for string of {len} chars"
565 )));
566 }
567
568 let ch = s.chars().nth(index as usize).expect("已校验范围内");
569 Ok(Value::String(ch.to_string()))
570 }
571 _ => Err(RuntimeError::TypeErrorDetailed {
572 expected: "String, Number".to_string(),
573 got: format!("{:?}, {:?}", args[0], args[1]),
574 }),
575 }
576}