Skip to content

Commit

Permalink
A function is not deferred until after it and its args have been eval…
Browse files Browse the repository at this point in the history
…uated.

Fixes #82
  • Loading branch information
gordonklaus committed Jun 10, 2023
1 parent 13ace05 commit 0e73809
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion pkg/ineffassign/ineffassign.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,11 @@ func (bld *builder) Visit(n ast.Node) ast.Visitor {
brek.setDestination(bld.newBlock(exits...))
bld.breaks.pop()
case *ast.DeferStmt:
bld.walk(n.Call.Fun)
for _, a := range n.Call.Args {
bld.walk(a)
}
bld.defers[len(bld.defers)-1] = true
return bld
case *ast.LabeledStmt:
bld.gotos.get(n.Label).setDestination(bld.newBlock(bld.block))
bld.labelStmt = n
Expand Down
25 changes: 25 additions & 0 deletions pkg/ineffassign/testdata/testdata.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package p

import (
"fmt"
"sync"
)

var b bool

func _() {
Expand Down Expand Up @@ -448,6 +453,12 @@ func _(mayPanic, mayRecover func()) (x int) {
return 2
}

func _(mayRecover func()) (x int) {
x = 1 // want "ineffectual assignment to x"
defer mayRecover()
return 2
}

func _() {
defer func() {
x := 1 // want "ineffectual assignment to x"
Expand Down Expand Up @@ -733,3 +744,17 @@ func _() {
}
_ = x
}

func f(mu *sync.Mutex) (n int, err error) {
n, err = g()
if err != nil {
err = fmt.Errorf("g: %w", err) // want "ineffectual assignment to err"
}

mu.Lock()
defer mu.Unlock()

return n, nil
}

func g() (int, error) { return 0, nil }

0 comments on commit 0e73809

Please sign in to comment.