rust_ts_json_compiler/
compiler.rs

1use crate::{
2    lexer::{Lexer, Token},
3    syntax_tree::{SyntaxTree, ZodExpression},
4};
5
6pub fn get_syntax_tree(schema: &str) -> Option<ZodExpression> {
7    let mut lx = Lexer::new(schema);
8    let mut tokens = Vec::new();
9
10    loop {
11        let token = lx.next_token();
12        if token == Token::Eof {
13            break;
14        }
15
16        tokens.push(token);
17    }
18
19    SyntaxTree::new(tokens.into_iter().peekable()).parse()
20}
21
22pub fn to_json(zod: &ZodExpression) -> String {
23    match zod {
24        ZodExpression::Object(obj) => {
25            let mut json = String::new();
26            json.push('{');
27            json.push_str(
28                &obj.iter()
29                    .map(|(key, value)| format!("\"{}\": {}", key, to_json(value)))
30                    .collect::<Vec<String>>()
31                    .join(", "),
32            );
33
34            json.push('}');
35            json
36        }
37        ZodExpression::Number => "1".to_string(),
38        ZodExpression::String => "\"string\"".to_string(),
39        ZodExpression::UUID => "\"aa5ac446-7e1d-11ee-b962-0242ac120002\"".to_string(),
40        ZodExpression::Boolean => "true".to_string(),
41        ZodExpression::Array(array) => {
42            let mut json = String::new();
43            json.push('[');
44            json.push_str(&to_json(array));
45            json.push(']');
46            json
47        }
48        ZodExpression::Literal(l) => format!("\"{}\"", l),
49        ZodExpression::Email => "\"admin@admin.com\"".to_string(),
50        ZodExpression::Any => "{}".to_string(),
51        ZodExpression::Enum(e) => format!("\"{}\"", e.first().unwrap()),
52        ZodExpression::Union(u) => to_json(u.first().unwrap()),
53    }
54}