//! 标准库:core(len, typeof, push, pop) use crate::error::RuntimeError; use crate::interpreter::{Interpreter, Value}; pub fn len(_interp: &mut Interpreter, args: Vec) -> Result { if args.is_empty() { return Err(RuntimeError::RuntimeError { message: "len() expects 1 argument".into(), token: None, }); } match &args[0] { Value::String(s) => Ok(Value::Number(s.chars().count() as f64)), Value::Array(arr) => Ok(Value::Number(arr.borrow().len() as f64)), Value::Object(obj) => Ok(Value::Number(obj.borrow().len() as f64)), _ => Err(RuntimeError::RuntimeError { message: "len() expects a string, array, or object".into(), token: None, }), } } pub fn typeof_fn(_interp: &mut Interpreter, args: Vec) -> Result { if args.is_empty() { return Err(RuntimeError::RuntimeError { message: "typeof() expects 1 argument".into(), token: None, }); } let s = match &args[0] { Value::Number(_) => "number", Value::String(_) => "string", Value::Bool(_) => "bool", Value::Nil => "nil", Value::Object(_) => "object", Value::Array(_) => "array", Value::Function(_) => "function", Value::NativeFunction(_) => "native_function", }; Ok(Value::String(s.into())) } pub fn push(_interp: &mut Interpreter, args: Vec) -> Result { if args.len() < 2 { return Err(RuntimeError::RuntimeError { message: "push() expects 2 arguments (array, value)".into(), token: None, }); } let val = args[1].clone(); match &args[0] { Value::Array(arr) => { arr.borrow_mut().push(val.clone()); Ok(val) } _ => Err(RuntimeError::RuntimeError { message: "push() expects an array as first argument".into(), token: None, }), } } pub fn pop(_interp: &mut Interpreter, args: Vec) -> Result { if args.is_empty() { return Err(RuntimeError::RuntimeError { message: "pop() expects 1 argument (array)".into(), token: None, }); } match &args[0] { Value::Array(arr) => arr .borrow_mut() .pop() .ok_or_else(|| RuntimeError::RuntimeError { message: "pop() on empty array".into(), token: None, }), _ => Err(RuntimeError::RuntimeError { message: "pop() expects an array as first argument".into(), token: None, }), } }