From 79307db4fed6efaf26afee7c254b01840685441f Mon Sep 17 00:00:00 2001 From: Natapat Samutpong Date: Thu, 17 Feb 2022 23:30:35 +0700 Subject: [PATCH] expr to sexpr (unfinished) --- example/ex.hyc | 13 +------------ src/front/parse.rs | 30 ++++++++++++++++++++++++++++++ src/main.rs | 7 ++++++- 3 files changed, 37 insertions(+), 13 deletions(-) diff --git a/example/ex.hyc b/example/ex.hyc index 64a1f18..3eefb10 100644 --- a/example/ex.hyc +++ b/example/ex.hyc @@ -1,12 +1 @@ -fun foo a b = a * b; -let bar = foo( 3 3 ); -let baz = bar in print(baz); - -if bar == 9 then - do - print(bar); - print(":)"); - end -else - print(":("); -end; \ No newline at end of file +let foo = 1 + 1 in 2 + foo; \ No newline at end of file diff --git a/src/front/parse.rs b/src/front/parse.rs index f21d68f..29243c0 100644 --- a/src/front/parse.rs +++ b/src/front/parse.rs @@ -311,4 +311,34 @@ pub fn parser() -> impl Parser, Error = Simple> + Clone .then_ignore(just(Token::Semicolon)) .repeated() .then_ignore(end()) +} + +impl Expr { + pub fn to_sexpr(&self) -> String { + let mut out = String::new(); + match self { + Self::Int(x) => out.push_str(&x.to_string()), + Self::Float(x) => out.push_str(&x.to_string()), + Self::Boolean(x) => out.push_str(&x.to_string()), + Self::String(x) => out.push_str(&format!("\"{}\"", x)), + Self::Ident(x) => out.push_str(&x), + + Self::Unary{ op, expr } => out.push_str(&format!("({} {})", op, expr.to_sexpr())), + Self::Binary{ op, left, right } => out.push_str( + &format!("({} {} {})", op, left.to_sexpr(), right.to_sexpr()) + ), + + Self::Let{ name, value, then } => { + let then = match *then.clone() { + Some(v) => format!("\n (do {})", v.to_sexpr()), + None => "".to_string(), + }; + out.push_str(&format!("(let\n {}\n {}{})", name, value.clone().to_sexpr(), then)) + }, + + // TODO: finish the rest of the Expr, I'm going to sleep, goodnight. + _ => todo!(), + } + out + } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 3c02e9b..f5c5692 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,7 +22,12 @@ fn main() { let (ast, parse_error) = parser().parse_recovery(Stream::from_iter(len..len + 1, tokens.clone().unwrap().into_iter())); if lex_error.is_empty() { if parse_error.is_empty() { - println!("{:#?}", ast); + match ast { + Some(ast) => { + println!("{}", ast.iter().map(|e| e.to_sexpr()).collect::()) + }, + None => println!("no ast :("), + }; } else { eprintln!("{:#?}\n(Parser error)", parse_error); }