1
0
mirror of https://github.com/golang/go synced 2024-11-17 19:04:47 -07:00

cmd/cover: skip function declarations with blank names

Function declarations with blank ("_") names do not introduce a binding,
and therefore cannot be referenced or executed (in fact, they do not
make it into the final compiled binary at all). As such, counters
defined while annotating their bodies will always be zero.

These types of functions are commonly used to create compile-time
checks (e.g., stringer) which are not expected to be executed.

Skip over these functions when annotating a file, preventing the unused
counters from being generated and appearing as uncovered lines in
coverage reports.

Fixes #36264

Change-Id: I6b516cf43c430a6248d68d5f483a3902253fbdab
Reviewed-on: https://go-review.googlesource.com/c/go/+/223117
Reviewed-by: Bryan C. Mills <bcmills@google.com>
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
zikaeroh 2020-03-11 17:02:50 -07:00 committed by Bryan C. Mills
parent c6bcdeafd2
commit c3b9042132
2 changed files with 36 additions and 0 deletions

View File

@ -293,6 +293,11 @@ func (f *File) Visit(node ast.Node) ast.Visitor {
ast.Walk(f, n.Assign)
return nil
}
case *ast.FuncDecl:
// Don't annotate functions with blank names - they cannot be executed.
if n.Name.Name == "_" {
return nil
}
}
return f
}

View File

@ -0,0 +1,31 @@
[short] skip
go test -cover ./coverblank
stdout 'coverage: 100.0% of statements'
-- coverblank/a.go --
package coverblank
func _() {
println("unreachable")
}
type X int
func (x X) Print() {
println(x)
}
func (x X) _() {
println("unreachable")
}
-- coverblank/a_test.go --
package coverblank
import "testing"
func TestX(t *testing.T) {
var x X
x.Print()
}