pkl icon indicating copy to clipboard operation
pkl copied to clipboard

Wrong result of unary `-` operation

Open taichi-ishitani opened this issue 1 year ago • 4 comments

Pkl will return the wrong result for the unary - operation like below.

// foo.pkl
a = --1

The result of this operation should be 1 but got -1.

image

taichi-ishitani avatar Sep 16 '24 14:09 taichi-ishitani

Thanks for the report; definitely looks like bug. Haven't looked into it yet, but this looks parser related. Unary minus otherwise works as expected:

negativeOne = -1
a = -negativeOne

Produces:

negativeOne = -1
a = 1

bioball avatar Sep 16 '24 15:09 bioball

This is fun!

madrob avatar Sep 16 '24 16:09 madrob

Double unary minus could be easily confused with a decrement.

Java, JavaScript, Golang, .NET all fail to compile --1 expression either expecting parentheses around (-1) or expecting a variable to be decremented instead of a literal. Increment/decrement ++ and -- are deprecated in Swift 2.2 and removed in Swift 3. Python, however, handles x = --1 correctly.

I think pkl should follow the simplest solution and expect ++a or --a to fail with a clear message . An alternative is to start supporting prefix (and postfix for symmetry?) increments and decrements:

  • Expect --a to fail when a is numerical literal
  • Expect --a to mean "decrease a by 1 and return the new value of a as result" when a is a variable

What do you think?

DFrenkel avatar Sep 19 '24 05:09 DFrenkel

This bug extends through parentheses as well:

x = -(-1)
// x = -1

A decrement operator of any kind seems like the wrong choice for Pkl as it implies some form of imperative mutation that doesn't exist in the language.

HT154 avatar Sep 21 '24 01:09 HT154

Good point, @DFrenkel. I'm sympathetic to the idea that --a should hard-fail, because it might be confused with decrement.

bioball avatar Oct 11 '24 15:10 bioball