feat: 添加对const关键字的支持,允许定义不可变变量并增强相关错误处理
This commit is contained in:
@@ -16,15 +16,15 @@ pub fn register_all(env: &Rc<RefCell<Env>>) {
|
||||
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))));
|
||||
e.define("io".into(), Value::Object(Rc::new(RefCell::new(io))), true);
|
||||
// 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));
|
||||
e.define("print".into(), Value::NativeFunction(io::print), true);
|
||||
e.define("input".into(), Value::NativeFunction(io::input), true);
|
||||
|
||||
// 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))));
|
||||
e.define("os".into(), Value::Object(Rc::new(RefCell::new(os))), true);
|
||||
// clock can also be used as a global function for convenience
|
||||
e.define("clock".into(), Value::NativeFunction(os::clock));
|
||||
e.define("clock".into(), Value::NativeFunction(os::clock), true);
|
||||
}
|
||||
|
||||
+14
-8
@@ -5,7 +5,8 @@ use std::cell::RefCell;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Env {
|
||||
pub values: HashMap<String, Value>,
|
||||
/// (value, is_mutable) — `is_mutable` is true for `let`, false for `const`.
|
||||
pub values: HashMap<String, (Value, bool)>,
|
||||
pub parent: Option<Rc<RefCell<Env>>>,
|
||||
}
|
||||
|
||||
@@ -17,23 +18,28 @@ impl Env {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn define(&mut self, name: String, val: Value) {
|
||||
self.values.insert(name, val);
|
||||
pub fn define(&mut self, name: String, val: Value, mutable: bool) {
|
||||
self.values.insert(name, (val, mutable));
|
||||
}
|
||||
|
||||
pub fn assign(&mut self, name: &str, val: Value) -> bool {
|
||||
/// Assign a new value to an existing binding. Returns `Err(msg)` if the
|
||||
/// binding exists but was declared with `const` (immutable).
|
||||
pub fn assign(&mut self, name: &str, val: Value) -> Result<bool, String> {
|
||||
if let Some((_, false)) = self.values.get(name) {
|
||||
return Err(format!("Cannot reassign constant '{}'", name));
|
||||
}
|
||||
if self.values.contains_key(name) {
|
||||
self.values.insert(name.to_string(), val);
|
||||
true
|
||||
self.values.insert(name.to_string(), (val, true));
|
||||
Ok(true)
|
||||
} else if let Some(parent) = &self.parent {
|
||||
parent.borrow_mut().assign(name, val)
|
||||
} else {
|
||||
false
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, name: &str) -> Option<Value> {
|
||||
if let Some(val) = self.values.get(name) {
|
||||
if let Some((val, _)) = self.values.get(name) {
|
||||
Some(val.clone())
|
||||
} else if let Some(parent) = &self.parent {
|
||||
parent.borrow().get(name)
|
||||
|
||||
@@ -26,9 +26,9 @@ impl Interpreter {
|
||||
|
||||
fn execute(&mut self, stmt: Stmt) -> Result<Signal, RuntimeError> {
|
||||
match stmt {
|
||||
Stmt::Let { name, initializer } => {
|
||||
Stmt::Let { name, initializer, mutable } => {
|
||||
let val = self.evaluate(initializer)?;
|
||||
self.env.borrow_mut().define(name, val);
|
||||
self.env.borrow_mut().define(name, val, mutable);
|
||||
Ok(Signal::None)
|
||||
}
|
||||
Stmt::ExprStmt(expr) => {
|
||||
@@ -109,7 +109,7 @@ impl Interpreter {
|
||||
env: Rc::clone(&self.env),
|
||||
name: Some(name.clone()),
|
||||
}));
|
||||
self.env.borrow_mut().define(name, func);
|
||||
self.env.borrow_mut().define(name, func, true);
|
||||
Ok(Signal::None)
|
||||
}
|
||||
Stmt::Return(expr_opt) => {
|
||||
@@ -150,11 +150,20 @@ impl Interpreter {
|
||||
self.apply_assign_op(current.clone(), rhs, op)?
|
||||
}
|
||||
};
|
||||
if !self.env.borrow_mut().assign(&name, val.clone()) {
|
||||
return Err(RuntimeError::RuntimeError {
|
||||
message: format!("Undefined variable '{}'", name),
|
||||
token: None,
|
||||
});
|
||||
match self.env.borrow_mut().assign(&name, val.clone()) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
return Err(RuntimeError::RuntimeError {
|
||||
message: format!("Undefined variable '{}'", name),
|
||||
token: None,
|
||||
});
|
||||
}
|
||||
Err(msg) => {
|
||||
return Err(RuntimeError::RuntimeError {
|
||||
message: msg,
|
||||
token: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
@@ -380,12 +389,12 @@ impl Interpreter {
|
||||
let env = Rc::new(RefCell::new(Env::new(Some(Rc::clone(&f.env)))));
|
||||
|
||||
if let Some(name) = &f.name {
|
||||
env.borrow_mut().define(name.clone(), Value::Function(Rc::clone(&f)));
|
||||
env.borrow_mut().define(name.clone(), Value::Function(Rc::clone(&f)), true);
|
||||
}
|
||||
|
||||
for (i,param) in f.params.iter().enumerate() {
|
||||
let val = args.get(i).cloned().unwrap_or(Value::Nil);
|
||||
env.borrow_mut().define(param.clone(), val);
|
||||
env.borrow_mut().define(param.clone(), val, true);
|
||||
}
|
||||
|
||||
let previous = Rc::clone(&self.env);
|
||||
@@ -784,6 +793,64 @@ mod tests {
|
||||
assert_num(&get_var(&interp, "x"), 1.0);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Const
|
||||
// =========================================================================
|
||||
|
||||
#[test]
|
||||
fn eval_const_definition() {
|
||||
let interp = run("const x = 42;");
|
||||
assert_num(&get_var(&interp, "x"), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_const_reassignment() {
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
run("const x = 5; x = 10;");
|
||||
});
|
||||
assert!(result.is_err(), "Expected error for reassigning const");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_const_compound_assignment() {
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
run("const x = 5; x += 1;");
|
||||
});
|
||||
assert!(result.is_err(), "Expected error for compound assignment to const");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_const_shadowing() {
|
||||
// Inner block can shadow outer const with its own binding
|
||||
let interp = run("const x = 10; { let x = 20; }");
|
||||
assert_num(&get_var(&interp, "x"), 10.0); // Outer unchanged
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_const_object_mutation() {
|
||||
// const prevents rebinding, not property mutation
|
||||
let interp = run("const obj = { a: 1 }; obj.a = 2;");
|
||||
match get_var(&interp, "obj") {
|
||||
Value::Object(obj) => {
|
||||
let obj = obj.borrow();
|
||||
assert_num(obj.get("a").unwrap(), 2.0);
|
||||
}
|
||||
v => panic!("Expected Object, got {:?}", v),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_const_array_mutation() {
|
||||
// const prevents rebinding, not index mutation
|
||||
let interp = run("const arr = [1, 2]; arr[0] = 99;");
|
||||
match get_var(&interp, "arr") {
|
||||
Value::Array(arr) => {
|
||||
assert_num(&arr.borrow()[0], 99.0);
|
||||
}
|
||||
v => panic!("Expected Array, got {:?}", v),
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Scope
|
||||
// =========================================================================
|
||||
|
||||
Reference in New Issue
Block a user