]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/cover: skip function declarations with blank names
authorzikaeroh <zikaeroh@gmail.com>
Thu, 12 Mar 2020 00:02:50 +0000 (17:02 -0700)
committerBryan C. Mills <bcmills@google.com>
Fri, 13 Mar 2020 14:29:27 +0000 (14:29 +0000)
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>

src/cmd/cover/cover.go
src/cmd/go/testdata/script/cover_blank_func_decl.txt [new file with mode: 0644]

index e04c8834bd8cf3f977ef2d60982f47a853f48c9e..360f9aeb06c4bd57e4deb64531013cf1545fc53c 100644 (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
 }
diff --git a/src/cmd/go/testdata/script/cover_blank_func_decl.txt b/src/cmd/go/testdata/script/cover_blank_func_decl.txt
new file mode 100644 (file)
index 0000000..6fac4f8
--- /dev/null
@@ -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()
+}