LibJS: Apply the correct precedence for unary + and - operators
When determining the precedence of the + and - operators, the parser always returned the precedence using these operators in a binary expression (lower than division!). The context of whether the operator is used in a unary or binary expression must be taken into account.
This commit is contained in:
parent
18c54d8d40
commit
073eb46824
Notes:
sideshowbarker
2024-07-17 06:54:15 +09:00
Author: https://github.com/samkravitz 🔰 Commit: https://github.com/SerenityOS/serenity/commit/073eb46824 Pull-request: https://github.com/SerenityOS/serenity/pull/20419 Reviewed-by: https://github.com/awesomekling
2 changed files with 17 additions and 1 deletions
|
@ -503,6 +503,18 @@ public:
|
|||
return p;
|
||||
}
|
||||
|
||||
constexpr int get_unary(TokenType token) const
|
||||
{
|
||||
constexpr int operator_precedence_unary_plus_minus = 17;
|
||||
switch (token) {
|
||||
case TokenType::Minus:
|
||||
case TokenType::Plus:
|
||||
return operator_precedence_unary_plus_minus;
|
||||
default:
|
||||
return get(token);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
int m_token_precedence[cs_num_of_js_tokens];
|
||||
|
||||
|
@ -1791,7 +1803,7 @@ static bool is_simple_assignment_target(Expression const& expression, bool allow
|
|||
NonnullRefPtr<Expression const> Parser::parse_unary_prefixed_expression()
|
||||
{
|
||||
auto rule_start = push_start();
|
||||
auto precedence = g_operator_precedence.get(m_state.current_token.type());
|
||||
auto precedence = g_operator_precedence.get_unary(m_state.current_token.type());
|
||||
auto associativity = operator_associativity(m_state.current_token.type());
|
||||
switch (m_state.current_token.type()) {
|
||||
case TokenType::PlusPlus: {
|
||||
|
|
|
@ -12,3 +12,7 @@ test("basic functionality", () => {
|
|||
expect((typeof "x" === "string") === true).toBeTrue();
|
||||
expect(!(typeof "x" === "string") === false).toBeTrue();
|
||||
});
|
||||
|
||||
test("unary +/- operators bind higher than binary", () => {
|
||||
expect(10 ** -3 / 2).toEqual(0.0005);
|
||||
});
|
||||
|
|
Loading…
Add table
Reference in a new issue