Crystal: The left subexpression in `+=` is evaluated twice

Created on 9 Oct 2016  路  4Comments  路  Source: crystal-lang/crystal

rng = Random.new(1)
arr = [6, 0]
arr[p rng.rand(2)] += 1
p arr

Output in Ruby (correct):

1
[6, 1]

Output in Crystal:

1
0
[6, 7]

As you can guess, my innocent arr[rand(2)] += 1 has turned into arr[rand(2)] = arr[rand(2)] + 1

bug compiler

Most helpful comment

Lovely refactorization! Mutations away from parsing, and into normalizer. :-)

All 4 comments

me too stepped on this ...

def foo
  puts "here"
  1
end
arr = [1, 2, 3, 4]
arr[foo] += 1
p arr

Output:

here
here
[1, 3, 3, 4]

Oops!

Right now a += b is rewritten to a = a + b, always. This is fine for variables, but for methods and indexing we should store the right-hand side first to a temporary variable.

Well, the RHS isn't a problem, the _indexing expression_ should be temped in x[index_expr] += other_expr.

Lovely refactorization! Mutations away from parsing, and into normalizer. :-)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

will picture will  路  3Comments

asterite picture asterite  路  3Comments

ArthurZ picture ArthurZ  路  3Comments

oprypin picture oprypin  路  3Comments

Papierkorb picture Papierkorb  路  3Comments