88 lines
2.6 KiB
Rust
88 lines
2.6 KiB
Rust
pub mod builtins;
|
|
pub mod env;
|
|
pub mod interpreter;
|
|
|
|
pub use env::Env;
|
|
pub use interpreter::Interpreter;
|
|
|
|
use std::collections::HashMap;
|
|
use std::rc::Rc;
|
|
use std::cell::RefCell;
|
|
use std::fmt;
|
|
|
|
pub type NativeFn = fn(Vec<Value>) -> Result<Value, crate::error::RuntimeError>;
|
|
|
|
#[derive(Clone)]
|
|
pub enum Value {
|
|
Number(f64),
|
|
String(String),
|
|
Bool(bool),
|
|
Nil,
|
|
Object(Rc<RefCell<HashMap<String, Value>>>),
|
|
Array(Rc<RefCell<Vec<Value>>>),
|
|
Function(Rc<Function>),
|
|
NativeFunction(NativeFn),
|
|
}
|
|
|
|
pub enum Signal {
|
|
None, // 正常执行
|
|
Return(Value), // return 语句携带的返回值
|
|
Break, // break 信号
|
|
Continue, // continue 信号
|
|
}
|
|
|
|
impl std::fmt::Debug for Value {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
match self {
|
|
Value::Number(n) => write!(f, "Number({:?})", n),
|
|
Value::String(s) => write!(f, "String({:?})", s),
|
|
Value::Bool(b) => write!(f, "Bool({:?})", b),
|
|
Value::Nil => write!(f, "Nil"),
|
|
Value::Object(_) => write!(f, "Object(...)"),
|
|
Value::Array(_) => write!(f, "Array(...)"),
|
|
Value::Function(_) => write!(f, "Function(...)"),
|
|
Value::NativeFunction(_) => write!(f, "NativeFunction(...)"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Value {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match self {
|
|
Value::Number(n) => write!(f, "{}", n),
|
|
Value::String(s) => write!(f, "{}", s),
|
|
Value::Bool(b) => write!(f, "{}", b),
|
|
Value::Nil => write!(f, "nil"),
|
|
Value::Object(obj) => {
|
|
let obj = obj.borrow();
|
|
write!(f, "{{ ")?;
|
|
for (key, value) in obj.iter() {
|
|
write!(f, "{}: {}, ", key, value)?;
|
|
}
|
|
write!(f, "}}")
|
|
},
|
|
Value::Array(arr) => {
|
|
let arr = arr.borrow();
|
|
write!(f, "[")?;
|
|
for (i, val) in arr.iter().enumerate() {
|
|
if i > 0 {
|
|
write!(f, ", ")?;
|
|
}
|
|
write!(f, "{}", val)?;
|
|
}
|
|
write!(f, "]")
|
|
},
|
|
Value::Function(_) => write!(f, "<function>"),
|
|
Value::NativeFunction(_) => write!(f, "<native function>"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Function {
|
|
pub params: Vec<String>,
|
|
pub body: Vec<crate::ast::Stmt>,
|
|
pub env: Rc<RefCell<Env>>, // 闭包捕获环境
|
|
pub name: Option<String>,
|
|
}
|