Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/reflex-base/news/7565.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raising a negative number or a negated var to a power, such as `(-State.x) ** 2`, now compiles to valid JavaScript instead of failing the frontend build with "A unary expression with the '-' operator cannot be used as the left operand of an exponentiation expression".
11 changes: 10 additions & 1 deletion packages/reflex-base/src/reflex_base/vars/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import decimal
import json
import math
import re
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, NoReturn, TypeVar, overload

Expand Down Expand Up @@ -647,6 +648,9 @@ def number_modulo_operation(lhs: NumberVar, rhs: NumberVar):
return f"({lhs!s} % {rhs!s})"


_STARTS_WITH_UNARY_OPERATOR = re.compile(r"[-+!~]|(?:typeof|void|delete|await)\b")


@binary_number_operation
def number_exponent_operation(lhs: NumberVar, rhs: NumberVar):
"""Exponentiate two numbers.
Expand All @@ -658,7 +662,12 @@ def number_exponent_operation(lhs: NumberVar, rhs: NumberVar):
Returns:
The number exponent operation.
"""
return f"({lhs!s} ** {rhs!s})"
base = str(lhs)
# JavaScript rejects a unary expression as the base of `**` (`-2 ** 2` is a
# SyntaxError), so a negative literal or a negated var must be parenthesized.
if _STARTS_WITH_UNARY_OPERATOR.match(base):
base = f"({base})"
return f"({base} ** {rhs!s})"
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


@var_operation
Expand Down
15 changes: 15 additions & 0 deletions tests/units/reflex_base/vars/test_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Tests for reflex_base.vars.number."""

from reflex_base.vars.base import Var
from reflex_base.vars.number import LiteralNumberVar


def test_exponent_parenthesizes_a_unary_base():
"""JavaScript rejects a unary expression as the base of `**` (`-2 ** 2` is a SyntaxError)."""
x = Var(_js_expr="x").to(int)
assert str(LiteralNumberVar.create(-2) ** 3) == "((-2) ** 3)"
assert str(LiteralNumberVar.create(-2.5) ** x) == "((-2.5) ** x)"
assert str((-x) ** 2) == "((-(x)) ** 2)"
assert str(-(x**2)) == "-((x ** 2))"
assert str(x**-1) == "(x ** -1)"
assert str(2**-x) == "(2 ** -(x))"
Loading