evaluator/
builtins.rs

1use crate::object::{Object, BuiltinFunc};
2use std::rc::Rc;
3use phf::phf_map;
4
5pub static BUILTINS: phf::Map<&'static str, BuiltinFunc> = phf_map! {
6    "len" => len,
7    "puts" => puts,
8    "print" => puts,
9    "first" => first,
10    "last" => last,
11    "rest" => rest,
12    "push" => push,
13};
14
15
16// a failed try
17// rust sucks: https://stackoverflow.com/a/27896014/1713757
18// pub static BUILTINS: HashMap<String, BuiltinFunc> = vec![(String::from("len"), len as BuiltinFunc) ]
19//     .into_iter()
20//     .collect();
21
22pub fn len(args: Vec<Rc<Object>>) -> Rc<Object> {
23    Rc::from(match &*args[0] {
24        Object::String(s) => Object::Integer(s.len() as i64),
25        Object::Array(a) => Object::Integer(a.len() as i64),
26        o => Object::Error(format!("builtin len not supported for for type {}", o))
27    })
28}
29
30pub fn puts(args: Vec<Rc<Object>>) -> Rc<Object> {
31    args.iter().for_each(|obj| println!("{}", obj));
32    Rc::from(Object::Null)
33}
34
35pub fn first(args: Vec<Rc<Object>>) -> Rc<Object> {
36    match &*args[0] {
37        Object::Array(s) => {
38            match s.first() {
39                Some(obj) => Rc::clone(obj),
40                None => Rc::new(Object::Null),
41            }
42        },
43        o => Rc::new(Object::Error(format!("builtin first not supported for for type {}", o)))
44    }
45}
46
47pub fn last(args: Vec<Rc<Object>>) -> Rc<Object> {
48    match &*args[0] {
49        Object::Array(s) => {
50            match s.last() {
51                Some(obj) => Rc::clone(obj),
52                None => Rc::new(Object::Null),
53            }
54        },
55        o => Rc::new(Object::Error(format!("builtin last not supported for for type {}", o)))
56    }
57}
58
59pub fn rest(args: Vec<Rc<Object>>) -> Rc<Object> {
60    match &*args[0] {
61        Object::Array(s) => {
62            let len = s.len();
63            if len > 0 {
64                let new_array = s[1..len].to_vec();
65                return Rc::new(Object::Array(new_array));
66            }
67            return Rc::new(Object::Null)
68        },
69        o => Rc::new(Object::Error(format!("builtin rest not supported for for type {}", o)))
70    }
71}
72
73pub fn push(args: Vec<Rc<Object>>) -> Rc<Object> {
74    let array = args.first().unwrap();
75    let obj = Rc::clone(args.last().unwrap());
76    match &**array {
77        Object::Array(s) => {
78            let mut new_array = s.clone();
79            new_array.push(obj);
80            return Rc::new(Object::Array(new_array));
81        },
82        o => Rc::new(Object::Error(format!("builtin push not supported for for type {}", o)))
83    }
84}