Parse if-expressions
This commit is contained in:
16
Parser.cs
16
Parser.cs
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user