Debian Codegraph @

go/types/typeutil/map_test.go

raw symbols SCIP
1 // Copyright 2014 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 typeutil_test
6
7 // TODO(adonovan):
8 // - test use of explicit hasher across two maps.
9 // - test hashcodes are consistent with equals for a range of types
10 // (e.g. all types generated by type-checking some body of real code).
11
12 import (
13 "go/ast"
14 "go/parser"
15 "go/token"
16 "go/types"
17 "testing"
18
19 "golang.org/x/tools/go/packages"
20 "golang.org/x/tools/go/types/typeutil"
21 "golang.org/x/tools/internal/testenv"
22 )
23
24 var (
25 tStr = types.Typ[types.String] // string
26 tPStr1 = types.NewPointer(tStr) // *string
27 tPStr2 = types.NewPointer(tStr) // *string, again
28 tInt = types.Typ[types.Int] // int
29 tChanInt1 = types.NewChan(types.RecvOnly, tInt) // <-chan int
30 tChanInt2 = types.NewChan(types.RecvOnly, tInt) // <-chan int, again
31 )
32
33 func checkEqualButNotIdentical(t *testing.T, x, y types.Type, comment string) {
34 if !types.Identical(x, y) {
35 t.Errorf("%s: not equal: %s, %s", comment, x, y)
36 }
37 if x == y {
38 t.Errorf("%s: identical: %v, %v", comment, x, y)
39 }
40 }
41
42 func TestAxioms(t *testing.T) {
43 checkEqualButNotIdentical(t, tPStr1, tPStr2, "tPstr{1,2}")
44 checkEqualButNotIdentical(t, tChanInt1, tChanInt2, "tChanInt{1,2}")
45 }
46
47 func TestMap(t *testing.T) {
48 var tmap *typeutil.Map
49
50 // All methods but Set are safe on (*T)(nil).
51 tmap.Len()
52 tmap.At(tPStr1)
53 tmap.Delete(tPStr1)
54 tmap.KeysString()
55 _ = tmap.String()
56
57 tmap = new(typeutil.Map)
58
59 // Length of empty map.
60 if l := tmap.Len(); l != 0 {
61 t.Errorf("Len() on empty Map: got %d, want 0", l)
62 }
63 // At of missing key.
64 if v := tmap.At(tPStr1); v != nil {
65 t.Errorf("At() on empty Map: got %v, want nil", v)
66 }
67 // Deletion of missing key.
68 if tmap.Delete(tPStr1) {
69 t.Errorf("Delete() on empty Map: got true, want false")
70 }
71 // Set of new key.
72 if prev := tmap.Set(tPStr1, "*string"); prev != nil {
73 t.Errorf("Set() on empty Map returned non-nil previous value %s", prev)
74 }
75
76 // Now: {*string: "*string"}
77
78 // Length of non-empty map.
79 if l := tmap.Len(); l != 1 {
80 t.Errorf("Len(): got %d, want 1", l)
81 }
82 // At via insertion key.
83 if v := tmap.At(tPStr1); v != "*string" {
84 t.Errorf("At(): got %q, want \"*string\"", v)
85 }
86 // At via equal key.
87 if v := tmap.At(tPStr2); v != "*string" {
88 t.Errorf("At(): got %q, want \"*string\"", v)
89 }
90 // Iteration over sole entry.
91 tmap.Iterate(func(key types.Type, value any) {
92 if key != tPStr1 {
93 t.Errorf("Iterate: key: got %s, want %s", key, tPStr1)
94 }
95 if want := "*string"; value != want {
96 t.Errorf("Iterate: value: got %s, want %s", value, want)
97 }
98 })
99
100 // Setion with key equal to present one.
101 if prev := tmap.Set(tPStr2, "*string again"); prev != "*string" {
102 t.Errorf("Set() previous value: got %s, want \"*string\"", prev)
103 }
104
105 // Setion of another association.
106 if prev := tmap.Set(tChanInt1, "<-chan int"); prev != nil {
107 t.Errorf("Set() previous value: got %s, want nil", prev)
108 }
109
110 // Now: {*string: "*string again", <-chan int: "<-chan int"}
111
112 want1 := "{*string: \"*string again\", <-chan int: \"<-chan int\"}"
113 want2 := "{<-chan int: \"<-chan int\", *string: \"*string again\"}"
114 if s := tmap.String(); s != want1 && s != want2 {
115 t.Errorf("String(): got %s, want %s", s, want1)
116 }
117
118 want1 = "{*string, <-chan int}"
119 want2 = "{<-chan int, *string}"
120 if s := tmap.KeysString(); s != want1 && s != want2 {
121 t.Errorf("KeysString(): got %s, want %s", s, want1)
122 }
123
124 // Keys().
125 I := types.Identical
126 switch k := tmap.Keys(); {
127 case I(k[0], tChanInt1) && I(k[1], tPStr1): // ok
128 case I(k[1], tChanInt1) && I(k[0], tPStr1): // ok
129 default:
130 t.Errorf("Keys(): got %v, want %s", k, want2)
131 }
132
133 if l := tmap.Len(); l != 2 {
134 t.Errorf("Len(): got %d, want 1", l)
135 }
136 // At via original key.
137 if v := tmap.At(tPStr1); v != "*string again" {
138 t.Errorf("At(): got %q, want \"*string again\"", v)
139 }
140 hamming := 1
141 tmap.Iterate(func(key types.Type, value any) {
142 switch {
143 case I(key, tChanInt1):
144 hamming *= 2 // ok
145 case I(key, tPStr1):
146 hamming *= 3 // ok
147 }
148 })
149 if hamming != 6 {
150 t.Errorf("Iterate: hamming: got %d, want %d", hamming, 6)
151 }
152
153 if v := tmap.At(tChanInt2); v != "<-chan int" {
154 t.Errorf("At(): got %q, want \"<-chan int\"", v)
155 }
156 // Deletion with key equal to present one.
157 if !tmap.Delete(tChanInt2) {
158 t.Errorf("Delete() of existing key: got false, want true")
159 }
160
161 // Now: {*string: "*string again"}
162
163 if l := tmap.Len(); l != 1 {
164 t.Errorf("Len(): got %d, want 1", l)
165 }
166 // Deletion again.
167 if !tmap.Delete(tPStr2) {
168 t.Errorf("Delete() of existing key: got false, want true")
169 }
170
171 // Now: {}
172
173 if l := tmap.Len(); l != 0 {
174 t.Errorf("Len(): got %d, want %d", l, 0)
175 }
176 if s := tmap.String(); s != "{}" {
177 t.Errorf("Len(): got %q, want %q", s, "")
178 }
179 }
180
181 func TestMapGenerics(t *testing.T) {
182 const src = `
183 package p
184
185 // Basic defined types.
186 type T1 int
187 type T2 int
188
189 // Identical methods.
190 func (T1) M(int) {}
191 func (T2) M(int) {}
192
193 // A constraint interface.
194 type C interface {
195 ~int | string
196 }
197
198 type I interface {
199 }
200
201 // A generic type.
202 type G[P C] int
203
204 // Generic functions with identical signature.
205 func Fa1[P C](p P) {}
206 func Fa2[Q C](q Q) {}
207
208 // Fb1 and Fb2 are identical and should be mapped to the same entry, even if we
209 // map their arguments first.
210 func Fb1[P any](x *P) {
211 var y *P // Map this first.
212 _ = y
213 }
214 func Fb2[Q any](x *Q) {
215 }
216
217 // G1 and G2 are mutually recursive, and have identical methods.
218 type G1[P any] struct{
219 Field *G2[P]
220 }
221 func (G1[P]) M(G1[P], G2[P]) {}
222 type G2[Q any] struct{
223 Field *G1[Q]
224 }
225 func (G2[P]) M(G1[P], G2[P]) {}
226
227 // Method type expressions on different generic types are different.
228 var ME1 = G1[int].M
229 var ME2 = G2[int].M
230
231 // ME1Type should have identical type as ME1.
232 var ME1Type func(G1[int], G1[int], G2[int])
233
234 // Examples from issue #51314
235 type Constraint[T any] any
236 func Foo[T Constraint[T]]() {}
237 func Fn[T1 ~*T2, T2 ~*T1](t1 T1, t2 T2) {}
238
239 // Bar and Baz are identical to Foo.
240 func Bar[P Constraint[P]]() {}
241 func Baz[Q any]() {} // The underlying type of Constraint[P] is any.
242 // But Quux is not.
243 func Quux[Q interface{ quux() }]() {}
244
245
246 type Issue56048_I interface{ m() interface { Issue56048_I } }
247 var Issue56048 = Issue56048_I.m
248
249 type Issue56048_Ib interface{ m() chan []*interface { Issue56048_Ib } }
250 var Issue56048b = Issue56048_Ib.m
251
252 // Non-generic alias
253 type NonAlias int
254 type Alias1 = NonAlias
255 type Alias2 = NonAlias
256
257 // Generic alias (requires go1.23)
258 // type SetOfInt = map[int]bool
259 // type Set[T comparable] = map[K]bool
260 // type SetOfInt2 = Set[int]
261 `
262
263 fset := token.NewFileSet()
264 file, err := parser.ParseFile(fset, "p.go", src, 0)
265 if err != nil {
266 t.Fatal(err)
267 }
268
269 var conf types.Config
270 pkg, err := conf.Check("", fset, []*ast.File{file}, nil)
271 if err != nil {
272 t.Fatal(err)
273 }
274
275 // Collect types.
276 scope := pkg.Scope()
277 var (
278 T1 = scope.Lookup("T1").Type().(*types.Named)
279 T2 = scope.Lookup("T2").Type().(*types.Named)
280 T1M = T1.Method(0).Type()
281 T2M = T2.Method(0).Type()
282 G = scope.Lookup("G").Type()
283 GInt1 = instantiate(t, G, types.Typ[types.Int])
284 GInt2 = instantiate(t, G, types.Typ[types.Int])
285 GStr = instantiate(t, G, types.Typ[types.String])
286 C = scope.Lookup("C").Type()
287 CI = C.Underlying().(*types.Interface)
288 I = scope.Lookup("I").Type()
289 II = I.Underlying().(*types.Interface)
290 U = CI.EmbeddedType(0).(*types.Union)
291 Fa1 = scope.Lookup("Fa1").Type().(*types.Signature)
292 Fa2 = scope.Lookup("Fa2").Type().(*types.Signature)
293 Fa1P = Fa1.TypeParams().At(0)
294 Fa2Q = Fa2.TypeParams().At(0)
295 Fb1 = scope.Lookup("Fb1").Type().(*types.Signature)
296 Fb1x = Fb1.Params().At(0).Type()
297 Fb1y = scope.Lookup("Fb1").(*types.Func).Scope().Lookup("y").Type()
298 Fb2 = scope.Lookup("Fb2").Type().(*types.Signature)
299 Fb2x = Fb2.Params().At(0).Type()
300 G1 = scope.Lookup("G1").Type().(*types.Named)
301 G1M = G1.Method(0).Type()
302 G1IntM1 = instantiate(t, G1, types.Typ[types.Int]).(*types.Named).Method(0).Type()
303 G1IntM2 = instantiate(t, G1, types.Typ[types.Int]).(*types.Named).Method(0).Type()
304 G1StrM = instantiate(t, G1, types.Typ[types.String]).(*types.Named).Method(0).Type()
305 G2 = scope.Lookup("G2").Type()
306 // See below.
307 // G2M = G2.Method(0).Type()
308 G2IntM = instantiate(t, G2, types.Typ[types.Int]).(*types.Named).Method(0).Type()
309 ME1 = scope.Lookup("ME1").Type()
310 ME1Type = scope.Lookup("ME1Type").Type()
311 ME2 = scope.Lookup("ME2").Type()
312
313 Constraint = scope.Lookup("Constraint").Type()
314 Foo = scope.Lookup("Foo").Type()
315 Fn = scope.Lookup("Fn").Type()
316 Bar = scope.Lookup("Foo").Type()
317 Baz = scope.Lookup("Foo").Type()
318 Quux = scope.Lookup("Quux").Type()
319 Issue56048 = scope.Lookup("Issue56048").Type()
320 Issue56048b = scope.Lookup("Issue56048b").Type()
321
322 // In go1.23 these will be *types.Alias; for now they are all int.
323 NonAlias = scope.Lookup("NonAlias").Type()
324 Alias1 = scope.Lookup("Alias1").Type()
325 Alias2 = scope.Lookup("Alias2").Type()
326
327 // Requires go1.23.
328 // SetOfInt = scope.Lookup("SetOfInt").Type()
329 // Set = scope.Lookup("Set").Type().(*types.Alias)
330 // SetOfInt2 = scope.Lookup("SetOfInt2").Type()
331 )
332
333 tmap := new(typeutil.Map)
334
335 steps := []struct {
336 typ types.Type
337 name string
338 newEntry bool
339 }{
340 {T1, "T1", true},
341 {T2, "T2", true},
342 {G, "G", true},
343 {C, "C", true},
344 {CI, "CI", true},
345 {U, "U", true},
346 {I, "I", true},
347 {II, "II", true}, // should not be identical to CI
348
349 // Methods can be identical, even with distinct receivers.
350 {T1M, "T1M", true},
351 {T2M, "T2M", false},
352
353 // Identical instances should map to the same entry.
354 {GInt1, "GInt1", true},
355 {GInt2, "GInt2", false},
356 // ..but instantiating with different arguments should yield a new entry.
357 {GStr, "GStr", true},
358
359 // F1 and F2 should have identical signatures.
360 {Fa1, "F1", true},
361 {Fa2, "F2", false},
362
363 // The identity of P and Q should not have been affected by type parameter
364 // masking during signature hashing.
365 {Fa1P, "F1P", true},
366 {Fa2Q, "F2Q", true},
367
368 {Fb1y, "Fb1y", true},
369 {Fb1x, "Fb1x", false},
370 {Fb2x, "Fb2x", true},
371 {Fb1, "Fb1", true},
372
373 // Mapping elements of the function scope should not affect the identity of
374 // Fb2 or Fb1.
375 {Fb2, "Fb1", false},
376
377 {G1, "G1", true},
378 {G1M, "G1M", true},
379 {G2, "G2", true},
380
381 // See golang/go#49912: receiver type parameter names should be ignored
382 // when comparing method identity.
383 // {G2M, "G2M", false},
384 {G1IntM1, "G1IntM1", true},
385 {G1IntM2, "G1IntM2", false},
386 {G1StrM, "G1StrM", true},
387 {G2IntM, "G2IntM", false}, // identical to G1IntM1
388
389 {ME1, "ME1", true},
390 {ME1Type, "ME1Type", false},
391 {ME2, "ME2", true},
392
393 // See golang/go#51314: avoid infinite recursion on cyclic type constraints.
394 {Constraint, "Constraint", true},
395 {Foo, "Foo", true},
396 {Fn, "Fn", true},
397 {Bar, "Bar", false},
398 {Baz, "Baz", false},
399 {Quux, "Quux", true},
400
401 {Issue56048, "Issue56048", true}, // (not actually about generics)
402 {Issue56048b, "Issue56048b", true}, // (not actually about generics)
403
404 // All three types are identical.
405 {NonAlias, "NonAlias", true},
406 {Alias1, "Alias1", false},
407 {Alias2, "Alias2", false},
408
409 // Generic aliases: requires go1.23.
410 // {SetOfInt, "SetOfInt", true},
411 // {Set, "Set", false},
412 // {SetOfInt2, "SetOfInt2", false},
413 }
414
415 for _, step := range steps {
416 existing := tmap.At(step.typ)
417 if (existing == nil) != step.newEntry {
418 t.Errorf("At(%s) = %v, want new entry: %t", step.name, existing, step.newEntry)
419 }
420 tmap.Set(step.typ, step.name)
421 }
422 }
423
424 func instantiate(t *testing.T, origin types.Type, targs ...types.Type) types.Type {
425 inst, err := types.Instantiate(nil, origin, targs, true)
426 if err != nil {
427 t.Fatal(err)
428 }
429 return inst
430 }
431
432 // BenchmarkMap stores the type of every expression in the net/http
433 // package in a map.
434 func BenchmarkMap(b *testing.B) {
435 testenv.NeedsGoPackages(b)
436
437 // Load all dependencies of net/http.
438 cfg := &packages.Config{Mode: packages.LoadAllSyntax}
439 pkgs, err := packages.Load(cfg, "net/http")
440 if err != nil {
441 b.Fatal(err)
442 }
443
444 // Gather all unique types.Type pointers (>67K) annotating the syntax.
445 allTypes := make(map[types.Type]bool)
446 packages.Visit(pkgs, nil, func(pkg *packages.Package) {
447 for _, tv := range pkg.TypesInfo.Types {
448 allTypes[tv.Type] = true
449 }
450 })
451
452 for b.Loop() {
453 // De-duplicate the logically identical types.
454 var tmap typeutil.Map
455 for t := range allTypes {
456 tmap.Set(t, nil)
457 }
458
459 // For sanity, ensure we find a minimum number
460 // of distinct type equivalence classes.
461 if want := 12000; tmap.Len() < want {
462 b.Errorf("too few types (from %d types.Type values, got %d logically distinct types, want >=%d)",
463 len(allTypes),
464 tmap.Len(),
465 want)
466 }
467 }
468 }