Browse Source

Add variable declarations

github-actions
Garrit Franke 3 years ago
parent
commit
101ad0878d
  1. 3
      examples/hello_world.fx
  2. 8
      src/lexer/mod.rs
  3. 4
      src/lexer/tests.rs
  4. 23
      src/parser/mod.rs

3
examples/hello_world.fx

@ -1,8 +1,9 @@
// This is a comment
fn main() {
let x = 2;
let y;
return 1;
}
fn fib() {}

8
src/lexer/mod.rs

@ -43,9 +43,9 @@ pub enum TokenKind {
/// ";"
SemiColon,
/// "="
Equals,
Assign,
/// "=="
DeepEquals,
Equals,
/// "<"
SmallerThen,
/// ">"
@ -147,8 +147,8 @@ impl Cursor<'_> {
_ => Slash,
},
'=' => match self.first() {
'=' => DeepEquals,
_ => Equals,
'=' => Equals,
_ => Assign,
},
':' => Colon,
';' => SemiColon,

4
src/lexer/tests.rs

@ -28,7 +28,7 @@ mod tests {
tokens.nth(0).unwrap(),
Token {
len: 1,
kind: TokenKind::Equals,
kind: TokenKind::Assign,
raw: "=".to_owned()
}
);
@ -69,7 +69,7 @@ mod tests {
tokens.nth(0).unwrap(),
Token {
len: 1,
kind: TokenKind::Equals,
kind: TokenKind::Assign,
raw: "=".to_owned()
}
);

23
src/parser/mod.rs

@ -146,6 +146,12 @@ impl Parser {
let token = self.next_token();
println!("parse_statement: {:?}", token);
match token.kind {
TokenKind::Keyword(Keyword::Let) => {
let state = self.parse_declare();
self.match_token(TokenKind::SemiColon)?;
state
}
TokenKind::Keyword(Keyword::Return) => {
let state = Statement::Return(self.parse_expression()?);
self.match_token(TokenKind::SemiColon)?;
@ -166,6 +172,23 @@ impl Parser {
other => Err(format!("Expected Expression, found {:?}", other)),
}
}
fn parse_declare(&mut self) -> Result<Statement, String> {
match (
self.next_token().kind,
self.peek().ok_or("Expected ; or =")?.kind,
) {
(TokenKind::Identifier(name), TokenKind::SemiColon) => {
Ok(Statement::Declare(Variable { name }, None))
}
(TokenKind::Identifier(name), TokenKind::Assign) => {
self.drop(1);
let exp = self.parse_expression().ok();
Ok(Statement::Declare(Variable { name }, exp))
}
other => Err(format!("Expected identifier, found {:?}", other)),
}
}
}
pub fn parse(tokens: Vec<Token>) -> Result<node_type::Program, String> {

Loading…
Cancel
Save