1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! Implementations of built-in functions

use super::{
    env::Environment,
    error::{Error, IResult},
    convalue::ConValue,
    BuiltIn, Callable,
};
use cl_ast::Sym;
use std::{
    io::{stdout, Write},
    rc::Rc,
};

builtins! {
    const MISC;
    /// Unstable variadic print function
    pub fn print<_, args> () -> IResult<ConValue> {
        let mut out = stdout().lock();
        for arg in args {
            write!(out, "{arg}").ok();
        }
        writeln!(out).ok();
        Ok(ConValue::Empty)
    }
    /// Prints the [Debug](std::fmt::Debug) version of the input values
    pub fn dbg<_, args> () -> IResult<ConValue> {
        let mut out = stdout().lock();
        for arg in args {
            writeln!(out, "{arg:?}").ok();
        }
        Ok(args.into())
    }
    /// Dumps info from the environment
    pub fn dump<env, _>() -> IResult<ConValue> {
        println!("{}", *env);
        Ok(ConValue::Empty)
    }
}
builtins! {
    const BINARY;
    /// Multiplication `a * b`
    pub fn mul(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a * b),
            _ => Err(Error::TypeError)?
        })
    }
    /// Division `a / b`
    pub fn div(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs){
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a / b),
            _ => Err(Error::TypeError)?
        })
    }
    /// Remainder `a % b`
    pub fn rem(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a % b),
            _ => Err(Error::TypeError)?,
        })
    }

    /// Addition `a + b`
    pub fn add(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a + b),
            (ConValue::String(a), ConValue::String(b)) => (a.to_string() + &b.to_string()).into(),
            _ => Err(Error::TypeError)?
        })
    }
    /// Subtraction `a - b`
    pub fn sub(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a - b),
            _ => Err(Error::TypeError)?,
        })
    }

    /// Shift Left `a << b`
    pub fn shl(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a << b),
            _ => Err(Error::TypeError)?,
        })
    }
    /// Shift Right `a >> b`
    pub fn shr(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a >> b),
            _ => Err(Error::TypeError)?,
        })
    }

    /// Bitwise And `a & b`
    pub fn and(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a & b),
            (ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a & b),
            _ => Err(Error::TypeError)?,
        })
    }
    /// Bitwise Or `a | b`
    pub fn or(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a | b),
            (ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a | b),
            _ => Err(Error::TypeError)?,
        })
    }
    /// Bitwise Exclusive Or `a ^ b`
    pub fn xor(lhs, rhs) -> IResult<ConValue> {
        Ok(match (lhs, rhs) {
            (ConValue::Empty, ConValue::Empty) => ConValue::Empty,
            (ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a ^ b),
            (ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a ^ b),
            _ => Err(Error::TypeError)?,
        })
    }

    /// Tests whether `a < b`
    pub fn lt(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, false, <)
    }
    /// Tests whether `a <= b`
    pub fn lt_eq(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, true, <=)
    }
    /// Tests whether `a == b`
    pub fn eq(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, true, ==)
    }
    /// Tests whether `a != b`
    pub fn neq(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, false, !=)
    }
    /// Tests whether `a <= b`
    pub fn gt_eq(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, true, >=)
    }
    /// Tests whether `a < b`
    pub fn gt(lhs, rhs) -> IResult<ConValue> {
        cmp!(lhs, rhs, false, >)
    }
}
builtins! {
    const RANGE;
    /// Exclusive Range `a..b`
    pub fn range_exc(lhs, rhs) -> IResult<ConValue> {
        let (&ConValue::Int(lhs), &ConValue::Int(rhs)) = (lhs, rhs) else {
            Err(Error::TypeError)?
        };
        Ok(ConValue::RangeExc(lhs, rhs.saturating_sub(1)))
    }
    /// Inclusive Range `a..=b`
    pub fn range_inc(lhs, rhs) -> IResult<ConValue> {
        let (&ConValue::Int(lhs), &ConValue::Int(rhs)) = (lhs, rhs) else {
            Err(Error::TypeError)?
        };
        Ok(ConValue::RangeInc(lhs, rhs))
    }
}
builtins! {
    const UNARY;
    /// Negates the ConValue
    pub fn neg(tail) -> IResult<ConValue> {
        Ok(match tail {
            ConValue::Empty => ConValue::Empty,
            ConValue::Int(v) => ConValue::Int(-v),
            _ => Err(Error::TypeError)?,
        })
    }
    /// Inverts the ConValue
    pub fn not(tail) -> IResult<ConValue> {
        Ok(match tail {
            ConValue::Empty => ConValue::Empty,
            ConValue::Int(v) => ConValue::Int(!v),
            ConValue::Bool(v) => ConValue::Bool(!v),
            _ => Err(Error::TypeError)?,
        })
    }
    pub fn deref(tail) -> IResult<ConValue> {
        Ok(match tail {
            ConValue::Ref(v) => Rc::as_ref(v).clone(),
            _ => tail.clone(),
        })
    }
}

/// Turns an argument slice into an array with the (inferred) correct number of elements
pub fn to_args<const N: usize>(args: &[ConValue]) -> IResult<&[ConValue; N]> {
    args.try_into()
        .map_err(|_| Error::ArgNumber { want: N, got: args.len() })
}

/// Turns function definitions into ZSTs which implement [Callable] and [BuiltIn]
macro builtins (
    $(prefix = $prefix:literal)?
    const $defaults:ident $( = [$($additional_builtins:expr),*$(,)?])?;
    $(
        $(#[$meta:meta])*$vis:vis fn $name:ident$(<$env:tt, $args:tt>)? ( $($($arg:tt),+$(,)?)? ) $(-> $rety:ty)?
            $body:block
    )*
) {
    /// Builtins to load when a new interpreter is created
    pub const $defaults: &[&dyn BuiltIn] = &[$(&$name,)* $($additional_builtins)*];
    $(
        $(#[$meta])* #[allow(non_camel_case_types)] #[derive(Clone, Debug)]
        /// ```rust,ignore
        #[doc = stringify!(builtin! fn $name($($($arg),*)?) $(-> $rety)? $body)]
        /// ```
        $vis struct $name;
        impl BuiltIn for $name {
            fn description(&self) -> &str { concat!("builtin ", stringify!($name), stringify!(($($($arg),*)?) )) }
        }
        impl Callable for $name {
            #[allow(unused)]
            fn call(&self, env: &mut Environment, args: &[ConValue]) $(-> $rety)? {
                // println!("{}", stringify!($name), );
                $(let $env = env;
                let $args = args;)?
                $(let [$($arg),*] = to_args(args)?;)?
                $body
            }
            fn name(&self) -> Sym { stringify!($name).into() }
        }
    )*
}

/// Templates comparison functions for [ConValue]
macro cmp ($a:expr, $b:expr, $empty:literal, $op:tt) {
    match ($a, $b) {
        (ConValue::Empty, ConValue::Empty) => Ok(ConValue::Bool($empty)),
        (ConValue::Int(a), ConValue::Int(b)) => Ok(ConValue::Bool(a $op b)),
        (ConValue::Bool(a), ConValue::Bool(b)) => Ok(ConValue::Bool(a $op b)),
        (ConValue::Char(a), ConValue::Char(b)) => Ok(ConValue::Bool(a $op b)),
        (ConValue::String(a), ConValue::String(b)) => Ok(ConValue::Bool(&**a $op &**b)),
        _ => Err(Error::TypeError)
    }
}