refactoring builtins
parent
71f148139e
commit
621f64d3f1
@ -1,29 +1,36 @@
|
||||
use crate::{
|
||||
error::ExecError,
|
||||
runtime::{State, Value},
|
||||
run::{Call, Context, Value},
|
||||
};
|
||||
use std::{boxed::Box, collections::HashMap, io::Write};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Builtin {
|
||||
Echo,
|
||||
}
|
||||
|
||||
impl Builtin {
|
||||
pub fn lookup(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"echo" => Some(Self::Echo),
|
||||
_ => None,
|
||||
impl Call for Builtin {
|
||||
fn call(&self, ctx: &mut Context, args: &[Value]) -> Result<Value, ExecError> {
|
||||
match self {
|
||||
Builtin::Echo => Echo.call(ctx, args),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call(&self, _: &mut State, args: &Vec<Value>) -> Result<Value, ExecError> {
|
||||
match self {
|
||||
Builtin::Echo => {
|
||||
let args: Result<Vec<String>, ExecError> =
|
||||
args.into_iter().map(|arg| arg.try_as_string()).collect();
|
||||
let args = args?;
|
||||
println!("{}", args.join(" "));
|
||||
Ok(Value::None)
|
||||
}
|
||||
}
|
||||
pub struct Echo;
|
||||
|
||||
impl Call for Echo {
|
||||
fn call(&self, ctx: &mut Context, args: &[Value]) -> Result<Value, ExecError> {
|
||||
let args = args
|
||||
.into_iter()
|
||||
.map(|v| v.try_as_str())
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
_ = write!(ctx.stdout, "{}\n", args.join(" "));
|
||||
Ok(Value::None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> HashMap<&'static str, Builtin> {
|
||||
use Builtin::*;
|
||||
HashMap::from([("echo", Echo)])
|
||||
}
|
||||
|
Loading…
Reference in New Issue