Debian Codegraph @

internal/typesinternal/element_test.go

raw symbols SCIP
1 // Copyright 2024 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 package typesinternal_test
6
7 import (
8 "go/ast"
9 "go/parser"
10 "go/token"
11 "go/types"
12 "maps"
13 "slices"
14 "strings"
15 "testing"
16
17 "golang.org/x/tools/go/types/typeutil"
18 "golang.org/x/tools/internal/testenv"
19 "golang.org/x/tools/internal/typesinternal"
20 )
21
22 const elementSrc = `
23 package p
24
25 type A = int
26
27 type B = *map[chan int][]func() [2]bool
28
29 type C = T
30
31 type T struct{ x int }
32 func (T) method() uint
33 func (*T) ptrmethod() complex128
34
35 type D = A
36
37 type E = struct{ x int }
38
39 type F = func(int8, int16) (int32, int64)
40
41 type G = struct { U }
42
43 type U struct{}
44 func (U) method() uint32
45
46 `
47
48 func TestForEachElement(t *testing.T) {
49 // Add generic method, if go1.27.
50 // It doesn't change the outcome:
51 // complex64 is not expected in the result.
52 elementSrc := elementSrc
53 if testenv.Go1Point() >= 27 {
54 elementSrc += `
55 // generic method: T.generic[U] is not explored.
56 func (T) generic[U any](complex64) {}
57
58 // method of generic type
59 type H[T any] uintptr
60 func (H[T]) m(T) uint16
61 type Hf64 = H[float64]
62 `
63 // (still available: uint8 uint64 float32)
64 }
65
66 fset := token.NewFileSet()
67 f, err := parser.ParseFile(fset, "a.go", elementSrc, 0)
68 if err != nil {
69 t.Fatal(err) // parse error
70 }
71 var config types.Config
72 pkg, err := config.Check(f.Name.Name, fset, []*ast.File{f}, nil)
73 if err != nil {
74 t.Fatal(err) // type error
75 }
76
77 type testcase struct {
78 name string // name of a type alias whose RHS type's elements to compute
79 want []string // strings of types that are/are not elements (! => not)
80 }
81 tests := []testcase{
82 // simple type
83 {"A", []string{"int"}},
84
85 // compound type
86 {"B", []string{
87 "*map[chan int][]func() [2]bool",
88 "map[chan int][]func() [2]bool",
89 "chan int",
90 "int",
91 "[]func() [2]bool",
92 "func() [2]bool",
93 "[2]bool",
94 "bool",
95 }},
96
97 // defined struct type with methods, incl. pointer methods.
98 // Observe that it descends into the field type, but
99 // the result does not include the struct type itself.
100 // (This follows the Go toolchain behavior, and finesses the need
101 // to create wrapper methods for that struct type.)
102 {"C", []string{"T", "*T", "int", "uint", "complex128", "!complex64", "!struct{x int}"}},
103
104 // alias type
105 {"D", []string{"int"}},
106
107 // struct type not beneath a defined type
108 {"E", []string{"struct{x int}", "int"}},
109
110 // signature types: the params/results tuples
111 // are traversed but not included.
112 {"F", []string{"func(int8, int16) (int32, int64)",
113 "int8", "int16", "int32", "int64"}},
114
115 // struct with embedded field that has methods
116 {"G", []string{"*U", "struct{U}", "uint32", "U"}},
117 }
118 if testenv.Go1Point() >= 27 {
119 tests = append(tests, []testcase{
120 // H[float64].m is a ground type, so it is visited, giving us uint16.
121 {"Hf64", []string{"*H[float64]", "H[float64]", "float64", "uint16"}},
122 }...)
123 }
124 var msets typeutil.MethodSetCache
125 for _, test := range tests {
126 tname, ok := pkg.Scope().Lookup(test.name).(*types.TypeName)
127 if !ok {
128 t.Errorf("no such type %q", test.name)
129 continue
130 }
131 T := types.Unalias(tname.Type())
132
133 toStr := func(T types.Type) string {
134 return types.TypeString(T, func(*types.Package) string { return "" })
135 }
136
137 got := make(map[string]bool)
138 set := new(typeutil.Map) // for de-duping
139 set2 := new(typeutil.Map) // for consistency check
140 typesinternal.ForEachElement(set, &msets, T, func(elem types.Type) {
141 got[toStr(elem)] = true
142 set2.Set(elem, true)
143 })
144
145 // Assert that set==set2, meaning f(x) was
146 // called for each x in the de-duping map.
147 if set.Len() != set2.Len() {
148 t.Errorf("ForEachElement called f %d times yet de-dup set has %d elements",
149 set2.Len(), set.Len())
150 } else {
151 set.Iterate(func(key types.Type, _ any) {
152 if set2.At(key) == nil {
153 t.Errorf("ForEachElement did not call f(%v)", key)
154 }
155 })
156 }
157
158 // Assert than all expected (and no unexpected) elements were found.
159 fail := false
160 for _, typstr := range test.want {
161 found := got[typstr]
162 typstr, unwanted := strings.CutPrefix(typstr, "!")
163 if found && unwanted {
164 fail = true
165 t.Errorf("ForEachElement(%s): unwanted element %q", T, typstr)
166 } else if !found && !unwanted {
167 fail = true
168 t.Errorf("ForEachElement(%s): element %q not found", T, typstr)
169 }
170 }
171 if fail {
172 t.Logf("got elements:\n%s", strings.Join(slices.Sorted(maps.Keys(got)), "\n"))
173 }
174 }
175 }