aether/builtins/io.rs
1// src/builtins/io.rs
2//! I/O 内置函数模块
3//!
4//! 提供基础的输入输出功能,包括打印和读取用户输入。
5
6use crate::evaluator::RuntimeError;
7use crate::value::Value;
8use std::io::{self, Write};
9
10/// 打印值(不换行)
11///
12/// # 功能
13/// 将一个或多个值输出到标准输出(stdout),不添加换行符。
14/// 多个参数会用空格分隔。所有值会自动转换为字符串。
15///
16/// # 参数
17/// - `values...`: 要打印的值(一个或多个,任意类型)
18///
19/// # 返回值
20/// 返回 `Null`
21///
22/// # 示例
23/// ```aether
24/// Print("Hello") # 输出: Hello
25/// Print("Result:", 42) # 输出: Result: 42
26/// Print("Sum:", 10, "+", 20, "=", 30) # 输出: Sum: 10 + 20 = 30
27/// Print([1, 2, 3]) # 输出: [1, 2, 3]
28/// ```
29pub fn print(args: &[Value]) -> Result<Value, RuntimeError> {
30 if args.is_empty() {
31 return Ok(Value::Null);
32 }
33
34 // 将所有参数转换为字符串并用空格连接
35 let output = args
36 .iter()
37 .map(|v| v.to_string())
38 .collect::<Vec<_>>()
39 .join(" ");
40
41 print!("{}", output);
42 io::stdout().flush().unwrap();
43 Ok(Value::Null)
44}
45
46/// 打印值(带换行)
47///
48/// # 功能
49/// 将一个或多个值输出到标准输出(stdout),并在末尾添加换行符。
50/// 多个参数会用空格分隔。所有值会自动转换为字符串。
51///
52/// # 参数
53/// - `values...`: 要打印的值(一个或多个,任意类型)
54///
55/// # 返回值
56/// 返回 `Null`
57///
58/// # 示例
59/// ```aether
60/// Println("Hello") # 输出: Hello\n
61/// Println("Result:", 42) # 输出: Result: 42\n
62/// Println("x =", 10, "y =", 20) # 输出: x = 10 y = 20\n
63/// Println([1, 2, 3]) # 输出: [1, 2, 3]\n
64/// ```
65pub fn println(args: &[Value]) -> Result<Value, RuntimeError> {
66 if args.is_empty() {
67 println!();
68 return Ok(Value::Null);
69 }
70
71 // 将所有参数转换为字符串并用空格连接
72 let output = args
73 .iter()
74 .map(|v| v.to_string())
75 .collect::<Vec<_>>()
76 .join(" ");
77
78 println!("{}", output);
79 Ok(Value::Null)
80}
81
82/// 读取用户输入
83///
84/// # 功能
85/// 显示提示信息并读取用户从标准输入(stdin)输入的一行文本。
86/// 自动去除行尾的换行符。
87///
88/// # 参数
89/// - `prompt`: 提示信息(字符串)
90///
91/// # 返回值
92/// 返回用户输入的字符串
93///
94/// # 示例
95/// ```aether
96/// Set NAME Input("请输入姓名: ")
97/// Println("你好, " + NAME)
98/// ```
99pub fn input(args: &[Value]) -> Result<Value, RuntimeError> {
100 if args.is_empty() {
101 return Err(RuntimeError::WrongArity {
102 expected: 1,
103 got: 0,
104 });
105 }
106
107 // Print prompt
108 print!("{}", args[0].to_string());
109 io::stdout().flush().unwrap();
110
111 // Read line
112 let mut buffer = String::new();
113 io::stdin()
114 .read_line(&mut buffer)
115 .map_err(|e| RuntimeError::InvalidOperation(format!("Failed to read input: {}", e)))?;
116
117 // Remove trailing newline
118 if buffer.ends_with('\n') {
119 buffer.pop();
120 if buffer.ends_with('\r') {
121 buffer.pop();
122 }
123 }
124
125 Ok(Value::String(buffer))
126}