Skip to content

Commit 40877a4

Browse files
committed
unused: don't ignore fields and methods of aliased type in imported package
When ignoring an alias, we don't want to ignore the fields and methods of the aliased type if that type is in a different package. Not only is it unnecessary, it also breaks the invariant that we only use objects we've already seen. Closes gh-1073 (cherry picked from commit 6c9d8ed)
1 parent df71e5d commit 40877a4

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

unused/testdata/src/alias/alias.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package main
22

3+
import "net/http"
4+
35
type t1 struct{} // used
46
type t2 struct{} // unused
57
type t3 struct{} // used
@@ -13,3 +15,20 @@ func main() { // used
1315
var _ alias1
1416
var _ t3
1517
}
18+
19+
type t4 struct { // used
20+
x int // used
21+
}
22+
23+
func (t4) foo() {} // used
24+
25+
//lint:ignore U1000 alias5 is ignored, which also ignores t4
26+
type alias5 = t4 // used
27+
28+
//lint:ignore U1000 alias6 is ignored, and we don't incorrectly try to include http.Server's fields and methods in the graph
29+
type alias6 = http.Server // used
30+
31+
//lint:ignore U1000 aliases don't have to be to named types
32+
type alias7 = struct { // used
33+
x int // used
34+
}

unused/unused.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1206,6 +1206,17 @@ func (g *graph) entry(pkg *pkg) {
12061206

12071207
// use methods and fields of ignored types
12081208
if obj, ok := obj.(*types.TypeName); ok {
1209+
if obj.IsAlias() {
1210+
if typ, ok := obj.Type().(*types.Named); ok && typ.Obj().Pkg() != obj.Pkg() {
1211+
// This is an alias of a named type in another package.
1212+
// Don't walk its fields or methods; we don't have to,
1213+
// and it breaks an assertion in graph.use because we're using an object that we haven't seen before.
1214+
//
1215+
// For aliases to types in the same package, we do want to ignore the fields and methods,
1216+
// because ignoring the alias should ignore the aliased type.
1217+
continue
1218+
}
1219+
}
12091220
if typ, ok := obj.Type().(*types.Named); ok {
12101221
for i := 0; i < typ.NumMethods(); i++ {
12111222
g.use(typ.Method(i), nil, edgeIgnored)

0 commit comments

Comments
 (0)