Skip to content

Commit

Permalink
fix: handle conversion of nil to an interface type
Browse files Browse the repository at this point in the history
  • Loading branch information
mvertes authored Feb 9, 2020
1 parent 6c339ce commit 812e55b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
9 changes: 9 additions & 0 deletions _test/type15.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package main

func main() {
err := error(nil)
println(err == nil)
}

// Output:
// true
5 changes: 4 additions & 1 deletion interp/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ func (interp *Interpreter) cfg(root *node, pkgID string) ([]*node, error) {
if isInt(n.child[0].typ.TypeOf()) && n.child[1].kind == basicLit && isFloat(n.child[1].typ.TypeOf()) {
err = n.cfgErrorf("truncated to integer")
}
if isInterface(n.child[0].typ) {
if isInterface(n.child[0].typ) && !n.child[1].isNil() {
// Convert to interface: just check that all required methods are defined by concrete type.
c0, c1 := n.child[0], n.child[1]
if !c1.typ.implements(c0.typ) {
Expand Down Expand Up @@ -1695,6 +1695,9 @@ func (n *node) isNatural() bool {
return false
}

// isNil returns true if node is a literal nil value, false otherwise
func (n *node) isNil() bool { return n.kind == basicLit && !n.rval.IsValid() }

// fieldType returns the nth parameter field node (type) of a fieldList node
func (n *node) fieldType(m int) *node {
k := 0
Expand Down
2 changes: 1 addition & 1 deletion interp/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func convert(n *node) {
typ := n.child[0].typ.TypeOf()
next := getExec(n.tnext)

if c.kind == basicLit && !c.rval.IsValid() { // convert nil to type
if c.isNil() { // convert nil to type
n.exec = func(f *frame) bltn {
dest(f).Set(reflect.New(typ).Elem())
return next
Expand Down

0 comments on commit 812e55b

Please sign in to comment.