feat: 添加对const关键字的支持,允许定义不可变变量并增强相关错误处理

This commit is contained in:
0264408
2026-06-16 17:24:17 +08:00
parent 284a29a4be
commit c2d6c518fc
8 changed files with 254 additions and 102 deletions
+77 -10
View File
@@ -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
// =========================================================================