diff --git a/examples/hello_world.fx b/examples/hello_world.fx index e51bafe..ea4b419 100644 --- a/examples/hello_world.fx +++ b/examples/hello_world.fx @@ -1,6 +1,6 @@ fn main() { + return 1; } -fn fib() { -} \ No newline at end of file +fn fib() {} \ No newline at end of file diff --git a/src/lexer/mod.rs b/src/lexer/mod.rs index 5415898..311dbc4 100644 --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs @@ -81,6 +81,7 @@ pub enum Keyword { Let, If, Else, + Return, Function, Boolean, Unknown, @@ -161,7 +162,6 @@ impl Cursor<'_> { '}' => CurlyBracesClose, c if is_id_start(c) => { let kind = self.identifier(c); - println!("Identifier Type: {:?}", kind); if kind == Keyword::Unknown { let mut ch: String = original_chars.collect(); ch.truncate(self.len_consumed()); @@ -229,6 +229,7 @@ impl Cursor<'_> { c if c == "fn" => Keyword::Function, c if c == "true" || c == "false" => Keyword::Boolean, c if c == "let" => Keyword::Let, + c if c == "return" => Keyword::Return, _ => Keyword::Unknown, } } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 07371c2..f1eebea 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,5 +1,5 @@ use crate::lexer::Keyword; -use crate::lexer::{Token, TokenKind}; +use crate::lexer::{Token, TokenKind, Value}; use crate::parser::node_type::*; use std::iter::Peekable; use std::vec::IntoIter; @@ -87,10 +87,6 @@ impl Parser { fn match_keyword(&mut self, keyword: Keyword) -> Result<(), String> { let token = self.next_token(); - println!( - "match_identifier_kind: Token: {:?}, identifier_kind: {:?}", - token, keyword - ); match token.kind { TokenKind::Keyword(_) => Ok(()), @@ -128,14 +124,48 @@ impl Parser { self.match_token(TokenKind::BraceOpen)?; self.match_token(TokenKind::BraceClose)?; self.match_token(TokenKind::CurlyBracesOpen)?; + + let mut statements = vec![]; + + while let Err(_) = self.peek_token(TokenKind::CurlyBracesClose) { + let statement = self.parse_statement()?; + println!("{:?}", statement); + statements.push(statement); + } + self.match_token(TokenKind::CurlyBracesClose)?; Ok(Function { name: name, arguments: Vec::new(), - statements: Vec::new(), + statements: statements, }) } + + fn parse_statement(&mut self) -> Result { + let token = self.next_token(); + println!("parse_statement: {:?}", token); + match token.kind { + TokenKind::Keyword(Keyword::Return) => { + let state = Statement::Return(self.parse_expression()?); + self.match_token(TokenKind::SemiColon)?; + + Ok(state) + } + other => Err(format!("Expected Statement, found {:?}", other)), + } + } + + fn parse_expression(&mut self) -> Result { + let token = self.next_token(); + match token.kind { + TokenKind::Literal(Value::Int) => { + let state = Expression::Int(token.raw.parse::().map_err(|e| e.to_string())?); + Ok(state) + } + other => Err(format!("Expected Expression, found {:?}", other)), + } + } } pub fn parse(tokens: Vec) -> Result {