mirror of
https://github.com/nspcc-dev/neo-go.git
synced 2025-02-19 15:23:35 +00:00
compiler: support nil checks
This commit is contained in:
parent
6f5a42facf
commit
954c8ff8d6
2 changed files with 75 additions and 2 deletions
|
@ -659,8 +659,26 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ast.Walk(c, n.X)
|
var checkForNull bool
|
||||||
ast.Walk(c, n.Y)
|
|
||||||
|
if isExprNil(n.X) {
|
||||||
|
checkForNull = true
|
||||||
|
} else {
|
||||||
|
ast.Walk(c, n.X)
|
||||||
|
}
|
||||||
|
if isExprNil(n.Y) {
|
||||||
|
checkForNull = true
|
||||||
|
} else {
|
||||||
|
ast.Walk(c, n.Y)
|
||||||
|
}
|
||||||
|
if checkForNull {
|
||||||
|
emit.Opcode(c.prog.BinWriter, opcode.ISNULL)
|
||||||
|
if n.Op == token.NEQ {
|
||||||
|
emit.Opcode(c.prog.BinWriter, opcode.NOT)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case n.Op == token.ADD:
|
case n.Op == token.ADD:
|
||||||
|
|
55
pkg/compiler/nilcheck_test.go
Normal file
55
pkg/compiler/nilcheck_test.go
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
package compiler_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/big"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var nilTestCases = []testCase{
|
||||||
|
{
|
||||||
|
"nil check positive right",
|
||||||
|
`
|
||||||
|
package foo
|
||||||
|
func Main() int {
|
||||||
|
var t interface{}
|
||||||
|
if t == nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
big.NewInt(1),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nil check negative right",
|
||||||
|
`
|
||||||
|
package foo
|
||||||
|
func Main() int {
|
||||||
|
t := []byte{}
|
||||||
|
if t == nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
big.NewInt(2),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nil check positive left",
|
||||||
|
`
|
||||||
|
package foo
|
||||||
|
func Main() int {
|
||||||
|
var t interface{}
|
||||||
|
if nil == t {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
big.NewInt(1),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNil(t *testing.T) {
|
||||||
|
runTestCases(t, nilTestCases)
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue