Skip to content

Commit

Permalink
Add tests for inline functions
Browse files Browse the repository at this point in the history
  • Loading branch information
garritfra committed Apr 5, 2024
1 parent bd5503e commit 0785232
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 13 deletions.
4 changes: 2 additions & 2 deletions examples/greeter.sb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn greet(name: string) = "Hello " + name

fn main() {
println(greet("World"))
}

fn greet(name: string) = "Hello " + name
2 changes: 1 addition & 1 deletion src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl Parser {

pub(super) fn make_hint_msg(&mut self, msg: String) -> String {
let new_lines = "\n".repeat(3);
format!("{new_lines}Hint: {}\n",msg)
format!("{new_lines}Hint: {}\n", msg)
}

pub(super) fn prev(&mut self) -> Option<Token> {
Expand Down
19 changes: 10 additions & 9 deletions src/parser/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,16 +405,17 @@ impl Parser {
};

// Check if the parsed expression continues
if self.peek_token(TokenKind::Dot).is_ok() {
// foo.bar
self.parse_field_access(expr)
} else if BinOp::try_from(self.peek()?.kind).is_ok() {
// 1 + 2
self.parse_bin_op(Some(expr))
} else {
// Nope, the expression was fully parsed
Ok(expr)
if let Ok(next) = self.peek() {
if next.kind == TokenKind::Dot {
// foo.bar
return self.parse_field_access(expr);
} else if BinOp::try_from(next.kind).is_ok() {
// 1 + 2
return self.parse_bin_op(Some(expr));
}
}
// Nope, the expression was fully parsed
Ok(expr)
}

fn parse_field_access(&mut self, lhs: Expression) -> Result<Expression, String> {
Expand Down
22 changes: 21 additions & 1 deletion src/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,27 @@ fn test_parse_function_with_return() {
#[test]
fn test_parse_inline_function() {
let raw = "
fn main() = 1
fn greet(name: string) = \"Hello \" + name
fn main() {
println(greet(\"World\"))
}
";
let tokens = tokenize(raw).unwrap();
let tree = parse(tokens, Some(raw.to_string()), "".into());
assert!(tree.is_ok())
}

#[test]
#[ignore]
// I don't know how this fails yet. It seems to have something to do with how
// `parse_expression` peeks tokens. It tries to peek a token after the
// expression body but it's empty, so it errors out.
fn test_parse_inline_function_as_last_statement() {
let raw = "
fn main() {
println(greet(\"World\"))
}
fn greet(name: string) = \"Hello \" + name
";
let tokens = tokenize(raw).unwrap();
let tree = parse(tokens, Some(raw.to_string()), "".into());
Expand Down

0 comments on commit 0785232

Please sign in to comment.