From 5c5ca8600a8a893ea1448129af21a1ea61469316 Mon Sep 17 00:00:00 2001 From: 0264408 Date: Fri, 6 Feb 2026 11:46:27 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E5=86=85=E7=BD=AE?= =?UTF-8?q?=E5=87=BD=E6=95=B0input?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/input.ast | 2 ++ script.ast => examples/script.ast | 0 src/interpreter/interpreter.rs | 20 ++++++++++++++++++-- 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 examples/input.ast rename script.ast => examples/script.ast (100%) diff --git a/examples/input.ast b/examples/input.ast new file mode 100644 index 0000000..1cf4b76 --- /dev/null +++ b/examples/input.ast @@ -0,0 +1,2 @@ +let name = input("Your name: "); +print("Hello, " + name) \ No newline at end of file diff --git a/script.ast b/examples/script.ast similarity index 100% rename from script.ast rename to examples/script.ast diff --git a/src/interpreter/interpreter.rs b/src/interpreter/interpreter.rs index 266c93e..2f1de77 100644 --- a/src/interpreter/interpreter.rs +++ b/src/interpreter/interpreter.rs @@ -11,10 +11,15 @@ pub struct Interpreter { impl Interpreter { pub fn new() -> Self { let env = Rc::new(RefCell::new(Env::new(None))); + + let mut env_mut = env.borrow_mut(); // 注册内置函数 - env.borrow_mut().define("print".to_string(), Value::NativeFunction(native_print)); - env.borrow_mut().define("clock".to_string(), Value::NativeFunction(native_clock)); + env_mut.define("print".to_string(), Value::NativeFunction(native_print)); + env_mut.define("input".to_string(), Value::NativeFunction(native_input)); + env_mut.define("clock".to_string(), Value::NativeFunction(native_clock)); + + drop(env_mut); Self { env } } @@ -283,6 +288,17 @@ fn native_print(args: Vec) -> Value { Value::Nil } +fn native_input(args: Vec) -> Value { + if let Some(prompt) = args.get(0) { + print!("{}", prompt); + use std::io::Write; + std::io::stdout().flush().unwrap(); + } + let mut buffer = String::new(); + std::io::stdin().read_line(&mut buffer).unwrap(); + Value::String(buffer.trim_end().to_string()) +} + // 获取当前时间 fn native_clock(_args: Vec) -> Value { Value::Number(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs_f64())