feat: 新增对象字面量和属性访问表达式

This commit is contained in:
0264408
2026-02-10 17:13:40 +08:00
parent 5c5ca8600a
commit 521c7006d9
11 changed files with 188 additions and 66 deletions
+24
View File
@@ -0,0 +1,24 @@
//! 标准库:ioprint, input
use crate::interpreter::Value;
pub fn print(args: Vec<Value>) -> Value {
for (i, arg) in args.iter().enumerate() {
if i > 0 {
print!(" ");
}
print!("{}", arg);
}
println!();
Value::Nil
}
pub fn input(args: Vec<Value>) -> Value {
if let Some(prompt) = args.get(0) {
print!("{}", prompt);
std::io::Write::flush(&mut std::io::stdout()).unwrap();
}
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).unwrap();
Value::String(buffer.trim_end().to_string())
}
+28
View File
@@ -0,0 +1,28 @@
//! 内置函数模块:按功能分组注册,便于扩展和维护。
mod io;
mod os;
use crate::interpreter::{Env, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
/// 向全局环境注册所有标准库(io、os 等)
pub fn register_all(env: &Rc<RefCell<Env>>) {
let mut e = env.borrow_mut();
// io
let mut io = HashMap::new();
io.insert("print".into(), Value::NativeFunction(io::print));
io.insert("input".into(), Value::NativeFunction(io::input));
e.define("io".into(), Value::Object(Rc::new(RefCell::new(io))));
// input and print can be used as global functions for convenience
e.define("print".into(), Value::NativeFunction(io::print));
e.define("input".into(), Value::NativeFunction(io::input));
// os
let mut os = HashMap::new();
os.insert("clock".into(), Value::NativeFunction(os::clock));
e.define("os".into(), Value::Object(Rc::new(RefCell::new(os))));
}
+12
View File
@@ -0,0 +1,12 @@
//! 标准库:osclock
use crate::interpreter::Value;
pub fn clock(_args: Vec<Value>) -> Value {
Value::Number(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs_f64(),
)
}