add return statement and refactor let

This commit is contained in:
Victor Timofei 2023-09-05 20:47:22 +03:00
parent 1da18a14b7
commit e76b4014cd
Signed by: vtimofei
GPG Key ID: B790DCEBE281403A
2 changed files with 23 additions and 21 deletions

View File

@ -4,13 +4,9 @@ use crate::token::Token;
pub trait Node: Debug {}
pub trait Statement: Node {
fn statement_node(&self);
}
pub trait Statement: Node {}
pub trait Expression: Node {
fn expression_node(&self);
}
pub trait Expression: Node {}
pub struct Program {
pub statements: Vec<Rc<dyn Statement>>,
@ -32,19 +28,31 @@ impl Debug for Program {
}
}
// FIXME: rename ExampleStatement structs to Example.
// we already know it's a statement since it impls
// `Statement`, this isn't Java world.
#[derive(Debug)]
pub struct LetStatement {
pub struct Let {
pub token: Token,
pub name: Identifier,
pub value: Rc<dyn Expression>,
}
impl Node for LetStatement {}
impl Node for Let {}
impl Statement for LetStatement {
fn statement_node(&self) {}
impl Statement for Let {}
#[derive(Debug)]
pub struct Return {
pub token: Token,
pub value: Rc<dyn Expression>,
}
impl Statement for Return {}
impl Node for Return {}
#[derive(Debug)]
pub struct Identifier {
pub token: Token,
@ -52,17 +60,11 @@ pub struct Identifier {
impl Node for Identifier {}
impl Expression for Identifier {
fn expression_node(&self) {}
}
impl Expression for Identifier {}
#[derive(Debug)]
pub struct DummyExpression {}
impl Node for DummyExpression {}
impl Expression for DummyExpression {
fn expression_node(&self) {
panic!("this is dummy");
}
}
impl Expression for DummyExpression {}

View File

@ -1,7 +1,7 @@
use std::{fmt, rc::Rc};
use crate::{
ast::{DummyExpression, Expression, Identifier, LetStatement, Program, Statement},
ast::{DummyExpression, Expression, Identifier, Let, Program, Statement},
lexer::Lexer,
token::Token,
};
@ -102,7 +102,7 @@ impl Parser {
let value = self.parse_expression()?;
Some(Rc::new(LetStatement { token, name, value }))
Some(Rc::new(Let { token, name, value }))
}
fn parse_expression(&mut self) -> Option<Rc<dyn Expression>> {
@ -204,7 +204,7 @@ mod tests {
fn test_let_statement(stmt: Rc<dyn Statement>, name: &str) {
assert_eq!(
format!("{stmt:?}"),
format!("LetStatement {{ token: Let, name: Identifier {{ token: Ident(\"{name}\") }}, value: DummyExpression }}"),
format!("Let {{ token: Let, name: Identifier {{ token: Ident(\"{name}\") }}, value: DummyExpression }}"),
);
}