1
1
Fork 0
mirror of https://github.com/azur1s/bobbylisp.git synced 2024-10-16 02:37:40 -05:00

expr to sexpr (unfinished)

This commit is contained in:
Natapat Samutpong 2022-02-17 23:30:35 +07:00
parent 9344bb1977
commit 79307db4fe
3 changed files with 37 additions and 13 deletions

View file

@ -1,12 +1 @@
fun foo a b = a * b; let foo = 1 + 1 in 2 + foo;
let bar = foo( 3 3 );
let baz = bar in print(baz);
if bar == 9 then
do
print(bar);
print(":)");
end
else
print(":(");
end;

View file

@ -311,4 +311,34 @@ pub fn parser() -> impl Parser<Token, Vec<Expr>, Error = Simple<Token>> + Clone
.then_ignore(just(Token::Semicolon)) .then_ignore(just(Token::Semicolon))
.repeated() .repeated()
.then_ignore(end()) .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
}
} }

View file

@ -22,7 +22,12 @@ fn main() {
let (ast, parse_error) = parser().parse_recovery(Stream::from_iter(len..len + 1, tokens.clone().unwrap().into_iter())); let (ast, parse_error) = parser().parse_recovery(Stream::from_iter(len..len + 1, tokens.clone().unwrap().into_iter()));
if lex_error.is_empty() { if lex_error.is_empty() {
if parse_error.is_empty() { if parse_error.is_empty() {
println!("{:#?}", ast); match ast {
Some(ast) => {
println!("{}", ast.iter().map(|e| e.to_sexpr()).collect::<String>())
},
None => println!("no ast :("),
};
} else { } else {
eprintln!("{:#?}\n(Parser error)", parse_error); eprintln!("{:#?}\n(Parser error)", parse_error);
} }