Paren some expressions mate
This commit is contained in:
parent
f17f3dc49f
commit
a25719c987
@ -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
|
||||
|
@ -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()
|
||||
|
@ -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", {} })
|
||||
)
|
||||
));
|
||||
};
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user