From 8da48869222875b70e58bb682baf65becc32a3da Mon Sep 17 00:00:00 2001 From: Morgan Date: Mon, 9 Dec 2024 10:14:40 +0100 Subject: [PATCH] fix(gnovm): use strconv.UnquoteChar to parse rune literals (#3296) This fixes a bug, as shown in rune3.gno, whereby rune literals which would not be parsed correctly by `strconv.Unquote` are now parsed correctly. Previously, the test would print out 65533, for the unicode invalid code point. --- gnovm/pkg/gnolang/nodes.go | 1 + gnovm/pkg/gnolang/op_eval.go | 10 ++++------ gnovm/tests/files/rune3.gno | 10 ++++++++++ 3 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 gnovm/tests/files/rune3.gno diff --git a/gnovm/pkg/gnolang/nodes.go b/gnovm/pkg/gnolang/nodes.go index 8d3d6d8a2cc..0496d37ed72 100644 --- a/gnovm/pkg/gnolang/nodes.go +++ b/gnovm/pkg/gnolang/nodes.go @@ -2153,6 +2153,7 @@ type ValuePather interface { // Utility func (x *BasicLitExpr) GetString() string { + // Matches string literal parsing in go/constant.MakeFromLiteral. str, err := strconv.Unquote(x.Value) if err != nil { panic("error in parsing string literal: " + err.Error()) diff --git a/gnovm/pkg/gnolang/op_eval.go b/gnovm/pkg/gnolang/op_eval.go index 1beba1d6e3f..2aa13b21753 100644 --- a/gnovm/pkg/gnolang/op_eval.go +++ b/gnovm/pkg/gnolang/op_eval.go @@ -204,16 +204,14 @@ func (m *Machine) doOpEval() { // and github.com/golang/go/issues/19921 panic("imaginaries are not supported") case CHAR: - cstr, err := strconv.Unquote(x.Value) + // Matching character literal parsing in go/constant.MakeFromLiteral. + val := x.Value + rne, _, _, err := strconv.UnquoteChar(val[1:len(val)-1], '\'') if err != nil { panic("error in parsing character literal: " + err.Error()) } - runes := []rune(cstr) - if len(runes) != 1 { - panic(fmt.Sprintf("error in parsing character literal: 1 rune expected, but got %v (%s)", len(runes), cstr)) - } tv := TypedValue{T: UntypedRuneType} - tv.SetInt32(runes[0]) + tv.SetInt32(rne) m.PushValue(tv) case STRING: m.PushValue(TypedValue{ diff --git a/gnovm/tests/files/rune3.gno b/gnovm/tests/files/rune3.gno new file mode 100644 index 00000000000..e848565e3a4 --- /dev/null +++ b/gnovm/tests/files/rune3.gno @@ -0,0 +1,10 @@ +package main + +const overflow = '\xff' + +func main() { + println(overflow) +} + +// Output: +// 255