Parse if-expressions

This commit is contained in:
2023-06-28 16:26:08 -06:00
parent 1264aca7f3
commit ba5283694e
5 changed files with 42 additions and 1 deletions

View File

@@ -143,6 +143,7 @@ class Parser
private Expr sum() => binaryLeft(product, TokenType.Minus, TokenType.Plus);
private Expr product() => binaryLeft(unary, TokenType.Slash, TokenType.Asterisk);
private Expr unary()
{
if (match(TokenType.Bang, TokenType.Minus))
@@ -151,6 +152,21 @@ class Parser
Expr right = unary();
return new Unary { Op = op, Right = right };
}
return ifExpr();
}
private Expr ifExpr()
{
if (match(TokenType.If))
{
Expr condition = expression();
consume(TokenType.Then, "Expect 'then' after condition.");
Expr thenCase = expression();
consume(TokenType.Else, "Expect 'else' after 'then' case.");
Expr elseCase = expression();
return new If { Condition = condition, Then = thenCase, Else = elseCase };
}
return primary();
}