Files
aster/src/interpreter/builtins/mod.rs
T
2026-06-17 15:57:45 +08:00

53 lines
2.5 KiB
Rust

//! 内置函数模块:按功能分组注册,便于扩展和维护。
mod core;
mod io;
mod os;
pub mod string;
use crate::interpreter::{Env, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
/// 向全局环境注册所有标准库(io、os 等)
pub fn register_all(env: &Rc<RefCell<Env>>) {
let mut e = env.borrow_mut();
// io
let mut io = HashMap::new();
io.insert("print".into(), Value::NativeFunction(Rc::new(io::print)));
io.insert("input".into(), Value::NativeFunction(Rc::new(io::input)));
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(Rc::new(io::print)), true);
e.define("input".into(), Value::NativeFunction(Rc::new(io::input)), true);
// os
let mut os = HashMap::new();
os.insert("clock".into(), Value::NativeFunction(Rc::new(os::clock)));
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(Rc::new(os::clock)), true);
// core — len, typeof, push, pop
e.define("len".into(), Value::NativeFunction(Rc::new(core::len)), true);
e.define("typeof".into(), Value::NativeFunction(Rc::new(core::typeof_fn)), true);
e.define("push".into(), Value::NativeFunction(Rc::new(core::push)), true);
e.define("pop".into(), Value::NativeFunction(Rc::new(core::pop)), true);
// require — module loader
e.define("require".into(), Value::NativeFunction(Rc::new(super::module::require_fn)), true);
// string — split, trim, substring, replace, contains, upper, lower, starts_with, ends_with
e.define("split".into(), Value::NativeFunction(Rc::new(string::split)), true);
e.define("trim".into(), Value::NativeFunction(Rc::new(string::trim)), true);
e.define("substring".into(), Value::NativeFunction(Rc::new(string::substring)), true);
e.define("replace".into(), Value::NativeFunction(Rc::new(string::replace)), true);
e.define("contains".into(), Value::NativeFunction(Rc::new(string::contains)), true);
e.define("upper".into(), Value::NativeFunction(Rc::new(string::upper)), true);
e.define("lower".into(), Value::NativeFunction(Rc::new(string::lower)), true);
e.define("starts_with".into(), Value::NativeFunction(Rc::new(string::starts_with)), true);
e.define("ends_with".into(), Value::NativeFunction(Rc::new(string::ends_with)), true);
}