feat: 添加对const关键字的支持,允许定义不可变变量并增强相关错误处理
This commit is contained in:
+2
-1
@@ -2,10 +2,11 @@ use crate::ast::expr::Expr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Stmt {
|
||||
/// let x = expr;
|
||||
/// let x = expr; or const x = expr;
|
||||
Let {
|
||||
name: String,
|
||||
initializer: Expr,
|
||||
mutable: bool, // true for let, false for const
|
||||
},
|
||||
|
||||
/// 表达式语句:expr;
|
||||
|
||||
@@ -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
|
||||
// =========================================================================
|
||||
|
||||
+3
-2
@@ -315,6 +315,7 @@ impl Lexer {
|
||||
|
||||
let kind = match s.as_str() {
|
||||
"let" => TokenKind::Let,
|
||||
"const" => TokenKind::Const,
|
||||
"fn" => TokenKind::Fn,
|
||||
"if" => TokenKind::If,
|
||||
"else" => TokenKind::Else,
|
||||
@@ -532,9 +533,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn keywords() {
|
||||
let kinds = tokenize("let fn if else while for break continue return true false nil");
|
||||
let kinds = tokenize("let const fn if else while for break continue return true false nil");
|
||||
assert_eq!(kinds, vec![
|
||||
TokenKind::Let, TokenKind::Fn,
|
||||
TokenKind::Let, TokenKind::Const, TokenKind::Fn,
|
||||
TokenKind::If, TokenKind::Else,
|
||||
TokenKind::While, TokenKind::For,
|
||||
TokenKind::Break, TokenKind::Continue,
|
||||
|
||||
@@ -25,6 +25,7 @@ pub enum TokenKind {
|
||||
|
||||
// 关键字
|
||||
Let,
|
||||
Const,
|
||||
Fn,
|
||||
If,
|
||||
Else,
|
||||
|
||||
+19
-5
@@ -31,7 +31,9 @@ impl Parser {
|
||||
|
||||
fn declaration(&mut self) -> Result<Stmt, RuntimeError> {
|
||||
if self.match_kind(&[TokenKind::Let]) {
|
||||
self.let_declaration()
|
||||
self.let_declaration(true)
|
||||
} else if self.match_kind(&[TokenKind::Const]) {
|
||||
self.let_declaration(false)
|
||||
} else if self.match_kind(&[TokenKind::Fn]) {
|
||||
self.fn_declaration()
|
||||
} else {
|
||||
@@ -59,13 +61,13 @@ impl Parser {
|
||||
}
|
||||
}
|
||||
|
||||
fn let_declaration(&mut self) -> Result<Stmt, RuntimeError> {
|
||||
fn let_declaration(&mut self, mutable: bool) -> Result<Stmt, RuntimeError> {
|
||||
let name = self.consume_ident("Expected variable name.")?;
|
||||
self.consume(TokenKind::Equal, "Expected '=' after variable name.")?;
|
||||
let initializer = self.expression()?;
|
||||
self.match_kind(&[TokenKind::Semicolon]); // 分号可选
|
||||
|
||||
Ok(Stmt::Let { name, initializer })
|
||||
Ok(Stmt::Let { name, initializer, mutable })
|
||||
}
|
||||
|
||||
fn fn_declaration(&mut self) -> Result<Stmt, RuntimeError> {
|
||||
@@ -135,7 +137,7 @@ impl Parser {
|
||||
let initializer = if self.match_kind(&[TokenKind::Semicolon]) {
|
||||
None
|
||||
} else if self.match_kind(&[TokenKind::Let]) {
|
||||
Some(self.let_declaration()?)
|
||||
Some(self.let_declaration(true)?)
|
||||
} else {
|
||||
Some(self.expression_statement()?)
|
||||
};
|
||||
@@ -565,6 +567,7 @@ impl Parser {
|
||||
|
||||
match self.peek().kind {
|
||||
TokenKind::Let
|
||||
| TokenKind::Const
|
||||
| TokenKind::Fn
|
||||
| TokenKind::If
|
||||
| TokenKind::While
|
||||
@@ -1106,7 +1109,7 @@ mod tests {
|
||||
#[test]
|
||||
fn parse_let_statement() {
|
||||
match parse_stmt("let x = 5;") {
|
||||
Stmt::Let { name, initializer } => {
|
||||
Stmt::Let { name, initializer, .. } => {
|
||||
assert_eq!(name, "x");
|
||||
assert!(matches!(initializer, Expr::Literal(Literal::Number(5.0))));
|
||||
}
|
||||
@@ -1123,6 +1126,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_const_statement() {
|
||||
match parse_stmt("const x = 5;") {
|
||||
Stmt::Let { name, mutable, .. } => {
|
||||
assert_eq!(name, "x");
|
||||
assert!(!mutable, "const should set mutable=false");
|
||||
}
|
||||
e => panic!("Expected Let (const), got {:?}", e),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_expression_statement() {
|
||||
match parse_stmt("x;") {
|
||||
|
||||
Reference in New Issue
Block a user