@@ -467,6 +467,12 @@ def parse_unary(tokens: typing.List[Token], p: float) -> "Object":
467467 # Precedence was chosen to be higher than function application so that
468468 # -a b is (-a) b and not -(a b).
469469 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 )
470476 return Binop (BinopKind .SUB , Int (0 ), r )
471477 else :
472478 raise ParseError (f"unexpected token { token !r} " )
@@ -1859,10 +1865,10 @@ def test_parse_digit_returns_int(self) -> None:
18591865 def test_parse_digits_returns_int (self ) -> None :
18601866 self .assertEqual (parse ([IntLit (123 )]), Int (123 ))
18611867
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 ))
18641870
1865- def test_parse_negative_var_returns_binary_sub_int (self ) -> None :
1871+ def test_parse_negative_var_returns_binary_sub_var (self ) -> None :
18661872 self .assertEqual (parse ([Operator ("-" ), Name ("x" )]), Binop (BinopKind .SUB , Int (0 ), Var ("x" )))
18671873
18681874 def test_parse_negative_int_binds_tighter_than_plus (self ) -> None :
@@ -1893,7 +1899,7 @@ def test_parse_decimal_returns_float(self) -> None:
18931899 self .assertEqual (parse ([FloatLit (3.14 )]), Float (3.14 ))
18941900
18951901 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 ))
18971903
18981904 def test_parse_var_returns_var (self ) -> None :
18991905 self .assertEqual (parse ([Name ("abc_123" )]), Var ("abc_123" ))
0 commit comments