Skip to content

Commit c83725b

Browse files
go/analysis/passes/loopclosure: add typeparams test
testdata/src/typeparams is similar to testdata/src/a but uses type parameters. Change-Id: Ia92f146089da4b1a3743c265181127ca886a71ad Reviewed-on: https://go-review.googlesource.com/c/tools/+/354701 Trust: Guodong Li <[email protected]> Reviewed-by: Robert Findley <[email protected]>
1 parent 18fa840 commit c83725b

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

go/analysis/passes/loopclosure/loopclosure_test.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package loopclosure_test
66

77
import (
8+
"golang.org/x/tools/internal/typeparams"
89
"testing"
910

1011
"golang.org/x/tools/go/analysis/analysistest"
@@ -13,5 +14,9 @@ import (
1314

1415
func Test(t *testing.T) {
1516
testdata := analysistest.TestData()
16-
analysistest.Run(t, testdata, loopclosure.Analyzer, "a")
17+
tests := []string{"a", "golang.org/..."}
18+
if typeparams.Enabled {
19+
tests = append(tests, "typeparams")
20+
}
21+
analysistest.Run(t, testdata, loopclosure.Analyzer, tests...)
1722
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright 2021 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// This file contains tests for the loopclosure checker.
6+
7+
//go:build go1.18
8+
9+
package typeparams
10+
11+
import "golang.org/x/sync/errgroup"
12+
13+
func f[T any](data T) {
14+
print(data)
15+
}
16+
17+
func _[T any]() {
18+
var s []T
19+
for i, v := range s {
20+
go func() {
21+
f(i) // want "loop variable i captured by func literal"
22+
f(v) // want "loop variable v captured by func literal"
23+
}()
24+
}
25+
}
26+
27+
func loop[P interface{ Go(func() error) }](grp P) {
28+
var s []int
29+
for i, v := range s {
30+
// The checker only matches on methods "(*...errgroup.Group).Go".
31+
grp.Go(func() error {
32+
print(i)
33+
print(v)
34+
return nil
35+
})
36+
}
37+
}
38+
39+
func _() {
40+
g := new(errgroup.Group)
41+
loop(g) // the analyzer is not "type inter-procedural" so no findings are reported
42+
}
43+
44+
type T[P any] struct {
45+
a P
46+
}
47+
48+
func (t T[P]) Go(func() error) { }
49+
50+
func _(g T[errgroup.Group]) {
51+
var s []int
52+
for i, v := range s {
53+
// "T.a" is method "(*...errgroup.Group).Go".
54+
g.a.Go(func() error {
55+
print(i) // want "loop variable i captured by func literal"
56+
print(v) // want "loop variable v captured by func literal"
57+
return nil
58+
})
59+
}
60+
}

0 commit comments

Comments
 (0)