Skip to content

Commit

Permalink
fix(gnolang): allow floats in inc/dec statements (#1221)
Browse files Browse the repository at this point in the history
Fixes #1151
  • Loading branch information
thehowl authored Nov 21, 2023
1 parent 6688d1d commit 902e678
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
47 changes: 45 additions & 2 deletions gnovm/pkg/gnolang/op_inc_dec.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package gnolang

import (
"fmt"
"math/big"

"github.com/cockroachdb/apd"
)

func (m *Machine) doOpInc() {
s := m.PopStmt().(*IncDecStmt)

Expand Down Expand Up @@ -42,8 +49,26 @@ func (m *Machine) doOpInc() {
lv.SetUint32(lv.GetUint32() + 1)
case Uint64Type:
lv.SetUint64(lv.GetUint64() + 1)
case Float32Type:
lv.SetFloat32(lv.GetFloat32() + 1)
case Float64Type:
lv.SetFloat64(lv.GetFloat64() + 1)
case BigintType, UntypedBigintType:
lb := lv.GetBigInt()
lb = big.NewInt(0).Add(lb, big.NewInt(1))
lv.V = BigintValue{V: lb}
case BigdecType, UntypedBigdecType:
lb := lv.GetBigDec()
sum := apd.New(0, 0)
cond, err := apd.BaseContext.WithPrecision(0).Add(sum, lb, apd.New(1, 0))
if err != nil {
panic(fmt.Sprintf("bigdec addition error: %v", err))
} else if cond.Inexact() {
panic(fmt.Sprintf("bigdec addition inexact: %v + 1", lb))
}
lv.V = BigdecValue{V: sum}
default:
panic("unexpected type in in operation")
panic(fmt.Sprintf("unexpected type %s in inc/dec operation", lv.T))
}

// Mark dirty in realm.
Expand Down Expand Up @@ -94,8 +119,26 @@ func (m *Machine) doOpDec() {
lv.SetUint32(lv.GetUint32() - 1)
case Uint64Type:
lv.SetUint64(lv.GetUint64() - 1)
case Float32Type:
lv.SetFloat32(lv.GetFloat32() - 1)
case Float64Type:
lv.SetFloat64(lv.GetFloat64() - 1)
case BigintType, UntypedBigintType:
lb := lv.GetBigInt()
lb = big.NewInt(0).Sub(lb, big.NewInt(1))
lv.V = BigintValue{V: lb}
case BigdecType, UntypedBigdecType:
lb := lv.GetBigDec()
sum := apd.New(0, 0)
cond, err := apd.BaseContext.WithPrecision(0).Sub(sum, lb, apd.New(1, 0))
if err != nil {
panic(fmt.Sprintf("bigdec addition error: %v", err))
} else if cond.Inexact() {
panic(fmt.Sprintf("bigdec addition inexact: %v + 1", lb))
}
lv.V = BigdecValue{V: sum}
default:
panic("unexpected type in in operation")
panic(fmt.Sprintf("unexpected type %s in inc/dec operation", lv.T))
}

// Mark dirty in realm.
Expand Down
File renamed without changes.
15 changes: 15 additions & 0 deletions gnovm/tests/files/inc1.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

func main() {
var i float64 = 899
i++
println(i)

j := float32(901)
j--
println(j)
}

// Output:
// 900
// 900

0 comments on commit 902e678

Please sign in to comment.