Browse Source

feat: nested expressions

github-actions
Garrit Franke 1 year ago
parent
commit
9447888a4f
  1. 1
      TODO
  2. 5
      examples/playground.sb
  3. 20
      src/parser/rules.rs
  4. 13
      src/parser/tests.rs

1
TODO

@ -6,7 +6,6 @@
- stdlib moves line of file, which makes error reporting impossible
# Features
- Nested expressions like (1 + (2 * 2))
- Nested arrays like [[1, 2, 3], [1, 2, 3]]
- Break and Continue keywords
- Type inference

5
examples/playground.sb

@ -1,7 +1,4 @@
fn main() {
another_function(5)
}
fn another_function(x: int) {
let x = (1 + 2 * (3 + 2))
println(x)
}

20
src/parser/rules.rs

@ -198,6 +198,11 @@ impl Parser {
fn parse_expression(&mut self) -> Result<Expression, String> {
let token = self.next()?;
match token.kind {
TokenKind::BraceOpen => {
let expr = self.parse_expression()?;
self.match_token(TokenKind::BraceClose)?;
Ok(expr)
}
TokenKind::Keyword(Keyword::Boolean) => {
let state = match BinOp::try_from(self.peek()?.kind) {
Ok(_) => self.parse_bin_op(None)?,
@ -308,7 +313,14 @@ impl Parser {
let expr = self.parse_expression()?;
let body = self.parse_block()?;
Ok(Statement::For(Variable {name: ident, ty: None}, expr, Box::new(body)))
Ok(Statement::For(
Variable {
name: ident,
ty: None,
},
expr,
Box::new(body),
))
}
fn parse_conditional_statement(&mut self) -> Result<Statement, String> {
@ -381,13 +393,11 @@ impl Parser {
match self.peek()?.kind {
TokenKind::Assign => {
self.match_token(TokenKind::Assign)?;
self.match_token(TokenKind::Assign)?;
let expr = self.parse_expression()?;
Ok(Statement::Declare(Variable { name, ty }, Some(expr)))
},
_ => {
Ok(Statement::Declare(Variable {name, ty}, None))
}
_ => Ok(Statement::Declare(Variable { name, ty }, None)),
}
}

13
src/parser/tests.rs

@ -693,3 +693,16 @@ fn test_nested_array() {
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}
#[test]
fn test_simple_nested_expression() {
let raw = "
fn main() {
let x = (1 + 2 * (3 + 2))
println(x)
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok());
}

Loading…
Cancel
Save