berry-lang / berry

A ultra-lightweight embedded scripting language optimized for microcontrollers.
https://berry-lang.github.io
MIT License
812 stars 97 forks source link

Fix ternary parser bug #404

Closed s-hadinger closed 6 months ago

s-hadinger commented 7 months ago

Fix #396

Details:

The Berry parser does simple optimization in the following pattern:

def f() var a = 1 a = a + 2 end

The raw bytecode generated is:

0000  LDCONST   R0  K0
0001  ADD   R1  R0  K1
0002  MOVE  R0  R1
0002  RET   0

but the optimizer saves the MOVE:

0001  ADD   R1  R0  K1
0002  MOVE  R0  R1
# replaced by
0001  ADD   R0  R0  K1

storing directly the result in R0 instead of storing into a temporary R1 that is discarded right after.

In the case of the ternary operator, only the last ADD is patched, not the first one.

Fix: I added a lastjmp information which point to the further position in PC where a JMP lands. This optimization should not happen at the beginning of a new string of code starting from the target of a JMP.