78 lines
2.0 KiB
Rust
78 lines
2.0 KiB
Rust
|
mod macros;
|
||
|
|
||
|
use crate::{
|
||
|
ast, expect_any_keyword, expect_identifier, expect_keyword, expect_token, peek_keyword,
|
||
|
peek_match,
|
||
|
token::{KeywordKind, Token, TokenKind},
|
||
|
};
|
||
|
|
||
|
pub struct Parser {
|
||
|
tokens: Vec<Token>,
|
||
|
current: usize,
|
||
|
}
|
||
|
|
||
|
impl Parser {
|
||
|
pub fn new(tokens: Vec<Token>) -> Parser {
|
||
|
Self { tokens, current: 0 }
|
||
|
}
|
||
|
|
||
|
pub fn statement(&mut self) -> ast::Statement {
|
||
|
if peek_keyword!(self, KeywordKind::function) {
|
||
|
return self.function_declaration();
|
||
|
}
|
||
|
return self.expression_statement();
|
||
|
todo!("No statement");
|
||
|
}
|
||
|
|
||
|
fn function_declaration(&mut self) -> ast::Statement {
|
||
|
expect_keyword!(self, KeywordKind::function);
|
||
|
let id = expect_identifier!(self);
|
||
|
expect_token!(self, TokenKind::LeftParen);
|
||
|
|
||
|
let mut parameters = Vec::new();
|
||
|
while peek_match!(self, TokenKind::Identifier(_)) {
|
||
|
let name = expect_identifier!(self);
|
||
|
expect_token!(self, TokenKind::Colon);
|
||
|
let typename = expect_any_keyword!(self);
|
||
|
let parameter = ast::ParameterDeclaration {
|
||
|
name: name.clone(),
|
||
|
typename: typename.clone(),
|
||
|
};
|
||
|
parameters.push(parameter);
|
||
|
}
|
||
|
|
||
|
expect_token!(self, TokenKind::RightParen);
|
||
|
|
||
|
expect_token!(self, TokenKind::LeftCurly);
|
||
|
|
||
|
let mut statements = Vec::new();
|
||
|
while !peek_match!(self, TokenKind::RightCurly) {
|
||
|
let statement = self.statement();
|
||
|
statements.push(statement);
|
||
|
}
|
||
|
|
||
|
expect_token!(self, TokenKind::RightCurly);
|
||
|
|
||
|
ast::Statement::FunctionDeclaration {
|
||
|
name: id.clone(),
|
||
|
parameters,
|
||
|
statements,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn expression_statement(&mut self) -> ast::Statement {
|
||
|
todo!()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Parser {
|
||
|
fn peek(&self) -> &Token {
|
||
|
&self.tokens[self.current]
|
||
|
}
|
||
|
fn consume(&mut self) -> Token {
|
||
|
let token = &self.tokens[self.current];
|
||
|
self.current += 1;
|
||
|
token.clone()
|
||
|
}
|
||
|
}
|