ocypode_lang/runtime/builtins/
mod.rs

1use super::environment::Environment;
2use crate::{ast::*, errors::Result as OYResult};
3pub mod functions;
4
5/// The builtins functions that are available in the environment.
6#[derive(Debug, Clone, Default)]
7pub struct Builtins {
8    pub functions: Vec<FunctionStatement>,
9}
10
11/// Macro to create match expression for built in functions.
12macro_rules! match_builtin {
13    (call: $call_expr:expr; ident: $fn_ident: expr; args: $args:expr; $($builtin_ident:tt),+,) => {
14        match $fn_ident {
15            $(
16                stringify!($builtin_ident) => functions::$builtin_ident($args, $call_expr),
17            )+
18            _ => unreachable!()
19        }
20    };
21}
22
23impl Builtins {
24    /// Creates a new builtins, with all the builtins functions.
25    pub fn new() -> Self {
26        Self {
27            functions: vec![
28                create_builtin("format", &[("format", false), ("args", true)]),
29                create_builtin("print", &[("values", true)]),
30                create_builtin("println", &[("values", true)]),
31                create_builtin("input", &[("prompt", false)]),
32                create_builtin("len", &[("value", false)]),
33                create_builtin("push", &[("list", false), ("value", false)]),
34                create_builtin("pop", &[("list", false)]),
35            ],
36        }
37    }
38
39    /// Initializes the environment with the builtins functions.
40    pub fn env_init(self, env: &mut Environment) -> OYResult<()> {
41        for function in self.functions {
42            env.add_global_function(function)?;
43        }
44        Ok(())
45    }
46
47    /// Executes the builtin function.
48    pub fn execute_builtin_funtion(
49        fn_ident: &str,
50        call_span: Span,
51        args: Vec<ObjectExpression>,
52    ) -> OYResult<ObjectExpression> {
53        match_builtin!(
54            call: call_span; ident: fn_ident; args: args;
55            format, print, println, input, len, push, pop,
56        )
57    }
58}
59
60fn create_builtin(name: &str, params: &[(&str, bool)]) -> FunctionStatement {
61    FunctionStatement {
62        ident: Some(Ident {
63            ident: name.to_string(),
64            span: Span::new(0, 0),
65        }),
66        params: params
67            .iter()
68            .map(|param| Param {
69                ident: Ident {
70                    ident: param.0.to_string(),
71                    span: Span::new(0, 0),
72                },
73                is_pack: param.1,
74            })
75            .collect(),
76        block: None,
77        visibility: Visibility::Public,
78        span: Span::new(0, 0),
79    }
80}