Paren some expressions mate

This commit is contained in:
Robert Bendun 2022-05-10 14:20:23 +02:00
parent f17f3dc49f
commit a25719c987
3 changed files with 45 additions and 2 deletions

View File

@ -317,6 +317,7 @@ struct Parser
Result<Ast> parse_binary_operator();
Result<Ast> parse_literal();
Result<Token::Type> peek_type() const;
Token consume();
// Tests if current token has given type

View File

@ -44,8 +44,28 @@ Result<Ast> Parser::parse_binary_operator()
Result<Ast> Parser::parse_literal()
{
Try(ensure(Token::Type::Numeric));
switch (Try(peek_type())) {
case Token::Type::Numeric:
return Ast::literal(consume());
case Token::Type::Open_Paren:
consume();
return parse_expression().and_then([&](Ast ast) -> tl::expected<Ast, Error> {
Try(ensure(Token::Type::Close_Paren));
consume();
return ast;
});
default:
unimplemented();
}
}
Result<Token::Type> Parser::peek_type() const
{
return token_id >= tokens.size()
? errors::unexpected_end_of_source(tokens.back().location)
: Result<Token::Type>(tokens[token_id].type);
}
Token Parser::consume()

View File

@ -56,4 +56,26 @@ suite parser_test = [] {
Ast::literal({ Token::Type::Numeric, "303", {} })
));
};
"Grouping expressions in parentheses"_test = [] {
expect_ast("(101 + 202) * 303", Ast::binary(
Token { Token::Type::Operator, "*", {} },
Ast::binary(
Token { Token::Type::Operator, "+", {} },
Ast::literal({ Token::Type::Numeric, "101", {} }),
Ast::literal({ Token::Type::Numeric, "202", {} })
),
Ast::literal({ Token::Type::Numeric, "303", {} })
));
expect_ast("101 * (202 + 303)", Ast::binary(
Token { Token::Type::Operator, "*", {} },
Ast::literal({ Token::Type::Numeric, "101", {} }),
Ast::binary(
Token { Token::Type::Operator, "+", {} },
Ast::literal({ Token::Type::Numeric, "202", {} }),
Ast::literal({ Token::Type::Numeric, "303", {} })
)
));
};
};