parsed ast of basic application

This commit is contained in:
2025-05-29 01:03:39 +02:00
parent 3125ee5a96
commit 94a9cd8cc7
7 changed files with 180 additions and 45 deletions

View File

@ -1,8 +1,9 @@
mod expression;
mod macros;
use crate::{
ast, expect_any_keyword, expect_identifier, expect_keyword, expect_token, peek_keyword,
peek_match,
ast, expect_any_keyword, expect_identifier, expect_keyword, expect_token, match_token,
peek_keyword, peek_match,
token::{KeywordKind, Token, TokenKind},
};
@ -13,26 +14,40 @@ pub struct Parser {
impl Parser {
pub fn new(tokens: Vec<Token>) -> Parser {
let tokens = tokens
.into_iter()
.filter(|t| !matches!(t.kind, TokenKind::NewLine))
.collect::<Vec<_>>();
Self { tokens, current: 0 }
}
pub fn statement(&mut self) -> ast::Statement {
pub fn module(&mut self) -> ast::Module {
let mut statements = Vec::new();
while !match_token!(self, TokenKind::EndOfFile) {
let s = self.statement();
println!("Parsed Statement {s:?}");
statements.push(s);
}
ast::Module { statements }
}
fn statement(&mut self) -> ast::Statement {
if peek_keyword!(self, KeywordKind::function) {
return self.function_declaration();
}
return self.expression_statement();
todo!("No statement");
self.expression_statement()
}
fn function_declaration(&mut self) -> ast::Statement {
expect_keyword!(self, KeywordKind::function);
let id = expect_identifier!(self);
expect_token!(self, TokenKind::LeftParen);
expect_token!(self, TokenKind::LeftParen, "LeftParen");
let mut parameters = Vec::new();
while peek_match!(self, TokenKind::Identifier(_)) {
let name = expect_identifier!(self);
expect_token!(self, TokenKind::Colon);
expect_token!(self, TokenKind::Colon, "Colon");
let typename = expect_any_keyword!(self);
let parameter = ast::ParameterDeclaration {
name: name.clone(),
@ -41,9 +56,9 @@ impl Parser {
parameters.push(parameter);
}
expect_token!(self, TokenKind::RightParen);
expect_token!(self, TokenKind::RightParen, "RightParen");
expect_token!(self, TokenKind::LeftCurly);
expect_token!(self, TokenKind::LeftCurly, "LeftCurly");
let mut statements = Vec::new();
while !peek_match!(self, TokenKind::RightCurly) {
@ -51,7 +66,7 @@ impl Parser {
statements.push(statement);
}
expect_token!(self, TokenKind::RightCurly);
expect_token!(self, TokenKind::RightCurly, "RightCurly");
ast::Statement::FunctionDeclaration {
name: id.clone(),
@ -61,17 +76,19 @@ impl Parser {
}
fn expression_statement(&mut self) -> ast::Statement {
todo!()
let e = self.expression();
expect_token!(self, TokenKind::Semicolon, "Semicolon");
ast::Statement::Expression(e)
}
}
impl Parser {
fn peek(&self) -> &Token {
&self.tokens[self.current]
fn peek(&self) -> Option<&Token> {
self.tokens.get(self.current)
}
fn consume(&mut self) -> Token {
let token = &self.tokens[self.current];
fn consume(&mut self) -> Option<Token> {
let token = self.peek().cloned();
self.current += 1;
token.clone()
token
}
}