Files
ts-parser/src/parse/mod.rs

95 lines
2.7 KiB
Rust
Raw Normal View History

2025-05-29 01:03:39 +02:00
mod expression;
2025-05-28 03:41:40 +02:00
mod macros;
use crate::{
2025-05-29 01:03:39 +02:00
ast, expect_any_keyword, expect_identifier, expect_keyword, expect_token, match_token,
peek_keyword, peek_match,
2025-05-28 03:41:40 +02:00
token::{KeywordKind, Token, TokenKind},
};
pub struct Parser {
tokens: Vec<Token>,
current: usize,
}
impl Parser {
pub fn new(tokens: Vec<Token>) -> Parser {
2025-05-29 01:03:39 +02:00
let tokens = tokens
.into_iter()
.filter(|t| !matches!(t.kind, TokenKind::NewLine))
.collect::<Vec<_>>();
2025-05-28 03:41:40 +02:00
Self { tokens, current: 0 }
}
2025-05-29 01:03:39 +02:00
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 {
2025-05-28 03:41:40 +02:00
if peek_keyword!(self, KeywordKind::function) {
return self.function_declaration();
}
2025-05-29 01:03:39 +02:00
self.expression_statement()
2025-05-28 03:41:40 +02:00
}
fn function_declaration(&mut self) -> ast::Statement {
expect_keyword!(self, KeywordKind::function);
let id = expect_identifier!(self);
2025-05-29 01:03:39 +02:00
expect_token!(self, TokenKind::LeftParen, "LeftParen");
2025-05-28 03:41:40 +02:00
let mut parameters = Vec::new();
while peek_match!(self, TokenKind::Identifier(_)) {
let name = expect_identifier!(self);
2025-05-29 01:03:39 +02:00
expect_token!(self, TokenKind::Colon, "Colon");
2025-05-28 03:41:40 +02:00
let typename = expect_any_keyword!(self);
let parameter = ast::ParameterDeclaration {
name: name.clone(),
typename: typename.clone(),
};
parameters.push(parameter);
}
2025-05-29 01:03:39 +02:00
expect_token!(self, TokenKind::RightParen, "RightParen");
2025-05-28 03:41:40 +02:00
2025-05-29 01:03:39 +02:00
expect_token!(self, TokenKind::LeftCurly, "LeftCurly");
2025-05-28 03:41:40 +02:00
let mut statements = Vec::new();
while !peek_match!(self, TokenKind::RightCurly) {
let statement = self.statement();
statements.push(statement);
}
2025-05-29 01:03:39 +02:00
expect_token!(self, TokenKind::RightCurly, "RightCurly");
2025-05-28 03:41:40 +02:00
ast::Statement::FunctionDeclaration {
name: id.clone(),
parameters,
statements,
}
}
fn expression_statement(&mut self) -> ast::Statement {
2025-05-29 01:03:39 +02:00
let e = self.expression();
expect_token!(self, TokenKind::Semicolon, "Semicolon");
ast::Statement::Expression(e)
2025-05-28 03:41:40 +02:00
}
}
impl Parser {
2025-05-29 01:03:39 +02:00
fn peek(&self) -> Option<&Token> {
self.tokens.get(self.current)
2025-05-28 03:41:40 +02:00
}
2025-05-29 01:03:39 +02:00
fn consume(&mut self) -> Option<Token> {
let token = self.peek().cloned();
2025-05-28 03:41:40 +02:00
self.current += 1;
2025-05-29 01:03:39 +02:00
token
2025-05-28 03:41:40 +02:00
}
}