@@ -467,6 +467,12 @@ def parse_unary(tokens: typing.List[Token], p: float) -> "Object":
467
467
# Precedence was chosen to be higher than function application so that
468
468
# -a b is (-a) b and not -(a b).
469
469
r = parse_binary (tokens , HIGHEST_PREC + 1 )
470
+ if isinstance (r , Int ):
471
+ assert r .value >= 0 , "Tokens should never have negative values"
472
+ return Int (- r .value )
473
+ if isinstance (r , Float ):
474
+ assert r .value >= 0 , "Tokens should never have negative values"
475
+ return Float (- r .value )
470
476
return Binop (BinopKind .SUB , Int (0 ), r )
471
477
else :
472
478
raise ParseError (f"unexpected token { token !r} " )
@@ -1859,10 +1865,10 @@ def test_parse_digit_returns_int(self) -> None:
1859
1865
def test_parse_digits_returns_int (self ) -> None :
1860
1866
self .assertEqual (parse ([IntLit (123 )]), Int (123 ))
1861
1867
1862
- def test_parse_negative_int_returns_binary_sub_int (self ) -> None :
1863
- self .assertEqual (parse ([Operator ("-" ), IntLit (123 )]), Binop ( BinopKind . SUB , Int (0 ), Int ( 123 ) ))
1868
+ def test_parse_negative_int_returns_negative_int (self ) -> None :
1869
+ self .assertEqual (parse ([Operator ("-" ), IntLit (123 )]), Int (- 123 ))
1864
1870
1865
- def test_parse_negative_var_returns_binary_sub_int (self ) -> None :
1871
+ def test_parse_negative_var_returns_binary_sub_var (self ) -> None :
1866
1872
self .assertEqual (parse ([Operator ("-" ), Name ("x" )]), Binop (BinopKind .SUB , Int (0 ), Var ("x" )))
1867
1873
1868
1874
def test_parse_negative_int_binds_tighter_than_plus (self ) -> None :
@@ -1893,7 +1899,7 @@ def test_parse_decimal_returns_float(self) -> None:
1893
1899
self .assertEqual (parse ([FloatLit (3.14 )]), Float (3.14 ))
1894
1900
1895
1901
def test_parse_negative_float_returns_binary_sub_float (self ) -> None :
1896
- self .assertEqual (parse ([Operator ("-" ), FloatLit (3.14 )]), Binop ( BinopKind . SUB , Int ( 0 ), Float (3.14 ) ))
1902
+ self .assertEqual (parse ([Operator ("-" ), FloatLit (3.14 )]), Float (- 3.14 ))
1897
1903
1898
1904
def test_parse_var_returns_var (self ) -> None :
1899
1905
self .assertEqual (parse ([Name ("abc_123" )]), Var ("abc_123" ))
0 commit comments