crisp_runtime/
lib.rs

1pub mod parsing;
2use std::{fmt::Debug, ops::{Add, Div, Mul, Sub}, sync::Arc};
3use parsing::*;
4use pest::iterators::{Pair, Pairs};
5use proc_macro2::TokenStream;
6use quote::quote;
7
8#[derive(Clone)]
9pub enum Value {
10    String(String),
11    Number(f32),
12    Bool(bool),
13    List(Vec<Value>),
14    Function(Arc<dyn Fn(&[Value]) -> Value>),
15}
16impl Value {
17    fn as_string(&self) -> Result<String, String> {
18        if let Value::String(s) = self {
19            Ok(s.clone())
20        } else {
21            Err("Not a string".to_string())
22        }
23    }
24    fn as_number(&self) -> Result<f32, String> {
25        if let Value::Number(f) = self {
26            Ok(*f)
27        } else {
28            Err("Not a number".to_string())
29        }
30    }
31    fn as_bool(&self) -> Result<bool, String> {
32        if let Value::Bool(b) = self {
33            Ok(*b)
34        } else {
35            Err("Not a bool".to_string())
36        }
37    }
38    fn as_list(&self) -> Result<Vec<Value>, String> {
39        if let Value::List(f) = self {
40            Ok(f.clone())
41        } else {
42            Err("Not a list".to_string())
43        }
44    }
45    fn as_function(&self) -> Result<Arc<dyn Fn(&[Value]) -> Value>, String> {
46        if let Value::Function(f) = self {
47            Ok(f.clone())
48        } else {
49            Err("Not a function".to_string())
50        }
51    }
52}
53impl PartialEq for Value {
54    fn eq(&self, other: &Self) -> bool {
55        match (self, other) {
56            (Value::String(s1), Value::String(s2)) => s1 == s2,
57            (Value::Number(n1), Value::Number(n2)) => n1 == n2,
58            (Value::Bool(b1), Value::Bool(b2)) => b1 == b2,
59            (Value::List(l1), Value::List(l2)) => l1 == l2,
60            (Value::Function(_), Value::Function(_)) => true,
61            _ => panic!("Cannot compare functions."),
62        }
63    }
64}
65impl PartialOrd for Value {
66    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
67        match (self, other) {
68            (Value::String(s1), Value::String(s2)) => s1.partial_cmp(s2),
69            (Value::Number(n1), Value::Number(n2)) => n1.partial_cmp(n2),
70            (Value::Bool(b1), Value::Bool(b2)) => b1.partial_cmp(b2),
71            (Value::List(_), Value::List(_)) => panic!("Cannot compare lists."),
72            (Value::Function(_), Value::Function(_)) => panic!("Cannot compare functions."),
73            _ => panic!("Cannot compare these types."),
74        }
75    }
76}
77impl Debug for Value {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Value::String(s) => write!(f, "{}", s),
81            Value::Number(n) => write!(f, "{}", n),
82            Value::Bool(b) => write!(f, "{}", b),
83            Value::List(l) => write!(f, "{:?}", l),
84            Value::Function(_) => panic!("Cannot debug print functions."),
85        }
86    }
87}
88impl From<Value> for String {
89    fn from(value: Value) -> Self {
90        return value.as_string().unwrap();
91    }
92}
93impl From<Value> for f32 {
94    fn from(value: Value) -> Self {
95        return value.as_number().unwrap();
96    }
97}
98impl From<f32> for Value {
99    fn from(value: f32) -> Self {
100        return Value::Number(value);
101    }
102}
103impl From<String> for Value {
104    fn from(value: String) -> Self {
105        return Value::String(value);
106    }
107}
108impl From<i32> for Value {
109    fn from(value: i32) -> Self {
110        return Value::Number(value as f32);
111    }
112}
113impl From<bool> for Value {
114    fn from(value: bool) -> Self {
115        return Value::Bool(value);
116    }
117}
118impl From<Value> for bool {
119    fn from(value: Value) -> Self {
120        return value.as_bool().unwrap();
121    }
122}
123impl Add<f32> for Value {
124    type Output = Value;
125    fn add(self, other: f32) -> Self::Output {
126        match self {
127            Value::Number(s) => Value::Number(s + other),
128            _ => {
129                panic!("Cannot add these types")
130            }
131        }
132    }
133}
134impl Add<Value> for f32 {
135    type Output = f32;
136    fn add(self, other: Value) -> Self::Output {
137        match other {
138            Value::Number(s) => s + other,
139            _ => {
140                panic!("Cannot add these types")
141            }
142        }
143    }
144}
145impl Add<String> for Value {
146    type Output = Value;
147    fn add(self, other: String) -> Self::Output {
148        match self {
149            Value::String(s) => Value::String(s + other.as_str()),
150            _ => {
151                panic!("Cannot add these types")
152            }
153        }
154    }
155}
156impl Add<Value> for String {
157    type Output = Value;
158    fn add(self, other: Value) -> Self::Output {
159        match other {
160            Value::String(s) => Value::String(self + s.as_str()),
161            _ => {
162                panic!("Cannot add these types")
163            }
164        }
165    }
166}
167impl Add<Value> for Value {
168    type Output = Value;
169    fn add(self, other: Value) -> Self::Output {
170        match self {
171            Value::Number(s) => Value::Number(s + other.as_number().unwrap()),
172            Value::String(s) => Value::String(s + other.as_string().unwrap().as_str()),
173            _ => {
174                panic!("Cannot add these types")
175            }
176        }
177    }
178}
179impl Sub<Value> for Value {
180    type Output = Value;
181    fn sub(self, other: Value) -> Self::Output {
182        match self {
183            Value::Number(s) => Value::Number(s - other.as_number().unwrap()),
184            _ => {
185                panic!("Cannot subtract these types")
186            }
187        }
188    }
189}
190impl Mul<Value> for Value {
191    type Output = Value;
192    fn mul(self, other: Value) -> Self::Output {        
193        match self {
194            Value::Number(s) => Value::Number(s * other.as_number().unwrap()),
195            _ => {
196                panic!("Cannot multiply these types")
197            }
198        }
199    }
200}
201impl Div<Value> for Value {
202    type Output = Value;
203    fn div(self, other: Value) -> Self::Output {
204        match self {
205            Value::Number(s) => Value::Number(s / other.as_number().unwrap()),
206            _ => {
207                panic!("Cannot divide these types")
208            }
209        }
210    }
211}
212
213pub fn transpile_to_rust(pairs: Pairs<'_, Rule>) -> TokenStream {
214    let mut result = TokenStream::new();
215    for pair in pairs {
216        match pair.as_rule() {
217            Rule::fun => {
218                let mut inner = pair.into_inner();
219                let mut params = Vec::new();
220                while inner.len() > 1 {
221                    let param = inner.next().unwrap();
222                    params.push(match param.as_rule() {
223                        Rule::symbol_type => parse_typed_identifier(param),
224                        Rule::symbol => {
225                            let symbol = syn::parse_str::<syn::Ident>(param.as_str())
226                                .expect("Invalid symbol");
227                            quote! {#symbol: Value}
228                        }
229                        _ => {
230                            panic!("Invalid function parameter")
231                        }
232                    });
233                }
234                let body = transpile_to_rust(inner.next().unwrap().into_inner());
235                let indices = 0..params.len();
236                result.extend(quote! {Value::Function(Arc::new(|args: &[Value]| {
237                     #(let #params = args[#indices].clone().into();)*
238                     #body 
239                }));});
240            }
241            Rule::def => {
242                let mut inner = pair.into_inner();
243                let var_name =
244                    syn::parse_str::<syn::Ident>(inner.next().unwrap().as_str()).unwrap();
245                let var_def = transpile_to_rust(inner.next().unwrap().into_inner());
246                result.extend(quote! {let #var_name: Value = #var_def;});
247            }
248            Rule::defn => {
249                let mut inner = pair.into_inner();
250                let var_name =
251                    syn::parse_str::<syn::Ident>(inner.next().unwrap().as_str()).unwrap();
252                let mut params = Vec::new();
253                while inner.len() > 1 {
254                    let param = inner.next().unwrap();
255                    params.push(match param.as_rule() {
256                        Rule::symbol_type => parse_typed_identifier(param),
257                        Rule::symbol => {
258                            let symbol = syn::parse_str::<syn::Ident>(param.as_str())
259                                .expect("Invalid symbol");
260                            quote! {#symbol: Value}
261                        }
262                        _ => {
263                            panic!("Invalid function parameter")
264                        }
265                    });
266                }
267                let body = transpile_to_rust(inner.next().unwrap().into_inner());
268                let indices = 0..params.len();
269                result.extend(quote! {let #var_name = Value::Function(Arc::new(|args: &[Value]| {
270                     #(let #params = args[#indices].clone().into();)*
271                     (#body).into() 
272                }));});
273            }
274            Rule::tfun => {
275                let mut inner = pair.into_inner();
276                let mut params = Vec::new();
277                while inner.len() > 1 {
278                    let param = inner.next().unwrap();
279                    params.push(syn::parse_str::<syn::Ident>(param.as_str()).unwrap());
280                }
281                let body = transpile_to_rust(inner.next().unwrap().into_inner());
282                let indices = 0..params.len();
283                result.extend(quote! {Value::Function(Arc::new(|args: &[Value]| {
284                     #(let #params = args[#indices].clone().into();)*
285                     #body 
286                }));});
287            }
288            Rule::tdef => {
289                let mut inner = pair.into_inner();
290                let var_name = syn::parse_str::<syn::Ident>(inner.next().unwrap().as_str())
291                    .expect("Invalid typed variable name");
292                let var_def = transpile_to_rust(inner.next().unwrap().into_inner());
293                result.extend(quote! {let #var_name = #var_def;});
294            }
295            Rule::tdefn => {
296                let mut inner = pair.into_inner();
297                let var_name = syn::parse_str::<syn::Ident>(
298                    inner.next().expect("Expected typed function name").as_str(),
299                )
300                .expect("Invalid typed function name");
301                let mut params = Vec::new();
302                while inner.len() > 1 {
303                    let param = inner.next().expect("Expected typed function parameter");
304                    params.push(parse_typed_identifier(param.clone()));
305                }
306                let body =
307                    transpile_to_rust(inner.next().expect("Error parsing body").into_inner());
308                let indices = 0..params.len();
309                result.extend(quote! {let #var_name = Value::Function(Arc::new(Box::new(|args: &[Value]| {
310                     #(let #params = args[#indices].clone().into();)*
311                     (#body).into() 
312                })));});
313            }
314            Rule::ifb => {
315                let mut inner = pair.into_inner();
316                let cond = transpile_to_rust(inner.next().unwrap().into_inner());
317                let if_true = transpile_to_rust(inner.next().unwrap().into_inner());
318                let if_false = transpile_to_rust(inner.next().unwrap().into_inner());
319                result.extend(quote! {if #cond {#if_true} else {#if_false}});
320            }
321            Rule::opvar => {
322                let mut inner = pair.into_inner();
323                let operator = transpile_to_rust(inner.next().unwrap().into_inner());
324                let mut operands = Vec::new();
325                for pair in inner {
326                    operands.push(transpile_to_rust(pair.into_inner()));
327                }
328                let first_operand = operands.first().unwrap();
329                result.extend(quote! {#first_operand});
330                for op in operands.iter().skip(1) {
331                    result.extend(quote! {#operator #op});
332                }
333            }
334            Rule::list => {
335                let inner = pair.into_inner();
336                let transpiled = transpile_to_rust(inner);
337                result.extend(quote! {{#transpiled}});
338            }
339            Rule::symbol => {
340                let inner = syn::parse_str::<syn::Ident>(pair.as_str()).expect("Invalid symbol");
341                result.extend(quote! {#inner});
342            }
343            Rule::add => {
344                result.extend(quote! {+});
345            }
346            Rule::sub => {
347                result.extend(quote! {-});
348            }
349            Rule::mul => {
350                result.extend(quote! {*});
351            }
352            Rule::div => {
353                result.extend(quote! {/});
354            }
355            Rule::less => {
356                result.extend(quote! {<});
357            }
358            Rule::more => {
359                result.extend(quote! {>});
360            }
361            Rule::equal => {
362                result.extend(quote! {==});
363            }
364            Rule::number => {
365                let inner = syn::parse_str::<syn::Lit>(pair.as_str()).unwrap();
366                result.extend(quote! {Value::from(#inner)});
367            }
368            Rule::boolean => {
369                let inner = syn::parse_str::<syn::LitBool>(pair.as_str()).unwrap();
370                result.extend(quote! {Value::from(#inner)});
371            }
372            Rule::EOI => return result,
373            _ => {
374                let inner = pair.into_inner();
375                result.extend(transpile_to_rust(inner));
376            }
377        }
378    }
379    result
380}
381
382fn parse_typed_identifier(ident: Pair<'_, Rule>) -> TokenStream {
383    let mut inner = ident.into_inner();
384    let symbol =
385        syn::parse_str::<syn::Ident>(inner.next().expect("Expected typed symbol").as_str())
386            .expect("Could not parse typed symbol");
387    let t = inner.next().expect("Expected type").as_str();
388    let t_token = match t {
389        "String" => {
390            quote! {String}
391        }
392        "Number" => {
393            quote! {f32}
394        }
395        "Bool" => {
396            quote! {bool}
397        }
398        "List" => {
399            quote! {Vec<Value>}
400        }
401        "Function" => {
402            quote! {Box<dyn Fn(&[Value]) -> Value>}
403        }
404        _ => quote! { #t },
405    };
406    quote! {#symbol: #t_token}
407}