/
api_test.go
2443 lines (2161 loc) · 72.1 KB
/
api_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types2_test
import (
"bytes"
"cmd/compile/internal/syntax"
"errors"
"fmt"
"internal/testenv"
"reflect"
"regexp"
"strings"
"testing"
. "cmd/compile/internal/types2"
)
// brokenPkg is a source prefix for packages that are not expected to parse
// or type-check cleanly. They are always parsed assuming that they contain
// generic code.
const brokenPkg = "package broken_"
func parseSrc(path, src string) (*syntax.File, error) {
errh := func(error) {} // dummy error handler so that parsing continues in presence of errors
return syntax.Parse(syntax.NewFileBase(path), strings.NewReader(src), errh, nil, syntax.AllowGenerics|syntax.AllowMethodTypeParams)
}
func pkgFor(path, source string, info *Info) (*Package, error) {
f, err := parseSrc(path, source)
if err != nil {
return nil, err
}
conf := Config{Importer: defaultImporter()}
return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
}
func mustTypecheck(t *testing.T, path, source string, info *Info) string {
pkg, err := pkgFor(path, source, info)
if err != nil {
name := path
if pkg != nil {
name = "package " + pkg.Name()
}
t.Fatalf("%s: didn't type-check (%s)", name, err)
}
return pkg.Name()
}
func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
f, err := parseSrc(path, source)
if f == nil { // ignore errors unless f is nil
t.Fatalf("%s: unable to parse: %s", path, err)
}
conf := Config{
Error: func(err error) {},
Importer: defaultImporter(),
}
pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
return pkg.Name(), err
}
func TestValuesInfo(t *testing.T) {
var tests = []struct {
src string
expr string // constant expression
typ string // constant type
val string // constant value
}{
{`package a0; const _ = false`, `false`, `untyped bool`, `false`},
{`package a1; const _ = 0`, `0`, `untyped int`, `0`},
{`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
{`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
{`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
{`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
{`package b0; var _ = false`, `false`, `bool`, `false`},
{`package b1; var _ = 0`, `0`, `int`, `0`},
{`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
{`package b3; var _ = 0.`, `0.`, `float64`, `0`},
{`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
{`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
{`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
{`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
{`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
{`package c1a; var _ = int(0)`, `0`, `int`, `0`},
{`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
{`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
{`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
{`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
{`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
{`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
{`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
{`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
{`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
{`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
{`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
{`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
{`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
{`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
{`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
{`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
{`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
{`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
{`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
{`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
{`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
{`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
{`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
{`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
{`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
{`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
{`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
{`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
{`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
{`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
{`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
{`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
{`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
{`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
{`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
{`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
{`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
{`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
{`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
{`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
{`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
{`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
{`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // issue #48422
}
for _, test := range tests {
info := Info{
Types: make(map[syntax.Expr]TypeAndValue),
}
name := mustTypecheck(t, "ValuesInfo", test.src, &info)
// look for expression
var expr syntax.Expr
for e := range info.Types {
if syntax.String(e) == test.expr {
expr = e
break
}
}
if expr == nil {
t.Errorf("package %s: no expression found for %s", name, test.expr)
continue
}
tv := info.Types[expr]
// check that type is correct
if got := tv.Type.String(); got != test.typ {
t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
continue
}
// if we have a constant, check that value is correct
if tv.Value != nil {
if got := tv.Value.ExactString(); got != test.val {
t.Errorf("package %s: got value %s; want %s", name, got, test.val)
}
} else {
if test.val != "" {
t.Errorf("package %s: no constant found; want %s", name, test.val)
}
}
}
}
func TestTypesInfo(t *testing.T) {
var tests = []struct {
src string
expr string // expression
typ string // value type
}{
// single-valued expressions of untyped constants
{`package b0; var x interface{} = false`, `false`, `bool`},
{`package b1; var x interface{} = 0`, `0`, `int`},
{`package b2; var x interface{} = 0.`, `0.`, `float64`},
{`package b3; var x interface{} = 0i`, `0i`, `complex128`},
{`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
// uses of nil
{`package n0; var _ *int = nil`, `nil`, `*int`},
{`package n1; var _ func() = nil`, `nil`, `func()`},
{`package n2; var _ []byte = nil`, `nil`, `[]byte`},
{`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
{`package n4; var _ chan int = nil`, `nil`, `chan int`},
{`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
{`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
{`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
{`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
{`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
{`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
{`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
{`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
{`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
{`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
{`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
{`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
{`package n21; var _ = (func())(nil)`, `nil`, `func()`},
{`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
{`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
{`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
{`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
{`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
{`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
{`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
{`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
{`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
{`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
{`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
{`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
{`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
{`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
// comma-ok expressions
{`package p0; var x interface{}; var _, _ = x.(int)`,
`x.(int)`,
`(int, bool)`,
},
{`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
`x.(int)`,
`(int, bool)`,
},
{`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
`m["foo"]`,
`(complex128, p2a.mybool)`,
},
{`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
`m["foo"]`,
`(complex128, bool)`,
},
{`package p3; var c chan string; var _, _ = <-c`,
`<-c`,
`(string, bool)`,
},
// issue 6796
{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
`x.(int)`,
`(int, bool)`,
},
{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
`(<-c)`,
`(string, bool)`,
},
{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
`<-c`,
`(string, bool)`,
},
{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
`(<-c)`,
`(string, bool)`,
},
{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
`(<-c)`,
`(string, bool)`,
},
// issue 7060
{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
`m[0]`,
`(string, bool)`,
},
{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
`m[0]`,
`(string, bool)`,
},
{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
`m[0]`,
`(string, bool)`,
},
{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
`<-ch`,
`(string, bool)`,
},
{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
`<-ch`,
`(string, bool)`,
},
{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
`<-ch`,
`(string, bool)`,
},
// issue 28277
{`package issue28277_a; func f(...int)`,
`...int`,
`[]int`,
},
{`package issue28277_b; func f(a, b int, c ...[]struct{})`,
`...[]struct{}`,
`[][]struct{}`,
},
// tests for broken code that doesn't parse or type-check
{brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
{brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
{brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
{brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
{`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
{brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
// parameterized functions
{`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
{`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
{`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
{`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
{`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
{`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
// type parameters
{`package t0; type t[] int; var _ t`, `t`, `t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
{`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
{`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
{`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
{brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
// instantiated types must be sanitized
{`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
// issue 45096
{`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
// issue 47895
{`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
// issue 50093
{`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
{`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
{`package u2a; func _[_ interface{int|string}]() {}`, `int | string`, `int|string`},
{`package u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string | ~bool`, `int|string|~bool`},
{`package u3a; func _[_ interface{int|string|~bool}]() {}`, `int | string`, `int|string`},
{`package u3a; func _[_ interface{int|string|~bool}]() {}`, `~bool`, `~bool`},
{`package u3a; func _[_ interface{int|string|~float64|~bool}]() {}`, `int | string | ~float64`, `int|string|~float64`},
{`package u0b; func _[_ int]() {}`, `int`, `int`},
{`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
{`package u2b; func _[_ int|string]() {}`, `int | string`, `int|string`},
{`package u3b; func _[_ int|string|~bool]() {}`, `int | string | ~bool`, `int|string|~bool`},
{`package u3b; func _[_ int|string|~bool]() {}`, `int | string`, `int|string`},
{`package u3b; func _[_ int|string|~bool]() {}`, `~bool`, `~bool`},
{`package u3b; func _[_ int|string|~float64|~bool]() {}`, `int | string | ~float64`, `int|string|~float64`},
{`package u0c; type _ interface{int}`, `int`, `int`},
{`package u1c; type _ interface{~int}`, `~int`, `~int`},
{`package u2c; type _ interface{int|string}`, `int | string`, `int|string`},
{`package u3c; type _ interface{int|string|~bool}`, `int | string | ~bool`, `int|string|~bool`},
{`package u3c; type _ interface{int|string|~bool}`, `int | string`, `int|string`},
{`package u3c; type _ interface{int|string|~bool}`, `~bool`, `~bool`},
{`package u3c; type _ interface{int|string|~float64|~bool}`, `int | string | ~float64`, `int|string|~float64`},
}
for _, test := range tests {
info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
var name string
if strings.HasPrefix(test.src, brokenPkg) {
var err error
name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
if err == nil {
t.Errorf("package %s: expected to fail but passed", name)
continue
}
} else {
name = mustTypecheck(t, "TypesInfo", test.src, &info)
}
// look for expression type
var typ Type
for e, tv := range info.Types {
if syntax.String(e) == test.expr {
typ = tv.Type
break
}
}
if typ == nil {
t.Errorf("package %s: no type found for %s", name, test.expr)
continue
}
// check that type is correct
if got := typ.String(); got != test.typ {
t.Errorf("package %s: got %s; want %s", name, got, test.typ)
}
}
}
func TestInstanceInfo(t *testing.T) {
var tests = []struct {
src string
name string
targs []string
typ string
}{
{`package p0; func f[T any](T) {}; func _() { f(42) }`,
`f`,
[]string{`int`},
`func(int)`,
},
{`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
`f`,
[]string{`rune`},
`func(rune) rune`,
},
{`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
`f`,
[]string{`complex128`},
`func(...complex128) complex128`,
},
{`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
`f`,
[]string{`float64`, `string`, `byte`},
`func(float64, *string, []byte)`,
},
{`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
`f`,
[]string{`float64`, `byte`},
`func(float64, *byte, ...[]byte)`,
},
// we don't know how to translate these but we can type-check them
{`package q0; type T struct{}; func (T) m[P any](P) {}; func _(x T) { x.m(42) }`,
`m`,
[]string{`int`},
`func(int)`,
},
{`package q1; type T struct{}; func (T) m[P any](P) P { panic(0) }; func _(x T) { x.m(42) }`,
`m`,
[]string{`int`},
`func(int) int`,
},
{`package q2; type T struct{}; func (T) m[P any](...P) P { panic(0) }; func _(x T) { x.m(42) }`,
`m`,
[]string{`int`},
`func(...int) int`,
},
{`package q3; type T struct{}; func (T) m[A, B, C any](A, *B, []C) {}; func _(x T) { x.m(1.2, new(string), []byte{}) }`,
`m`,
[]string{`float64`, `string`, `byte`},
`func(float64, *string, []byte)`,
},
{`package q4; type T struct{}; func (T) m[A, B any](A, *B, ...[]B) {}; func _(x T) { x.m(1.2, new(byte)) }`,
`m`,
[]string{`float64`, `byte`},
`func(float64, *byte, ...[]byte)`,
},
{`package r0; type T[P any] struct{}; func (_ T[P]) m[Q any](Q) {}; func _[P any](x T[P]) { x.m(42) }`,
`m`,
[]string{`int`},
`func(int)`,
},
// TODO(gri) record method type parameters in syntax.FuncType so we can check this
// {`package r1; type T interface{ m[P any](P) }; func _(x T) { x.m(4.2) }`,
// `x.m`,
// []string{`float64`},
// `func(float64)`,
// },
{`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
`f`,
[]string{`string`, `*string`},
`func(x string)`,
},
{`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
`f`,
[]string{`int`, `*int`},
`func(x []int)`,
},
{`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
`f`,
[]string{`int`, `chan<- int`},
`func(x []int)`,
},
{`package s4; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]](x []T) {}; func _(x []int) { f(x) }`,
`f`,
[]string{`int`, `chan<- int`, `chan<- []*chan<- int`},
`func(x []int)`,
},
{`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
`f`,
[]string{`string`, `*string`},
`func() string`,
},
{`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
`f`,
[]string{`string`, `*string`},
`func() string`,
},
{`package t3; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
`f`,
[]string{`int`, `chan<- int`, `chan<- []*chan<- int`},
`func() []int`,
},
{`package t4; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = (f[int]) }`,
`f`,
[]string{`int`, `chan<- int`, `chan<- []*chan<- int`},
`func() []int`,
},
{`package i0; import "lib"; func _() { lib.F(42) }`,
`F`,
[]string{`int`},
`func(int)`,
},
{`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
`T`,
[]string{`int`},
`struct{x int}`,
},
{`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
`T`,
[]string{`int`},
`struct{x int}`,
},
{`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
`T`,
[]string{`int`},
`struct{x int}`,
},
{`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
`T`,
[]string{`[]int`, `int`},
`struct{x []int; y int}`,
},
{`package type4; import "lib"; var _ lib.T[int]`,
`T`,
[]string{`int`},
`[]int`,
},
}
for _, test := range tests {
const lib = `package lib
func F[P any](P) {}
type T[P any] []P
`
imports := make(testImporter)
conf := Config{Importer: imports}
instances := make(map[*syntax.Name]Instance)
uses := make(map[*syntax.Name]Object)
makePkg := func(src string) *Package {
f, err := parseSrc("p.go", src)
if err != nil {
t.Fatal(err)
}
pkg, err := conf.Check("", []*syntax.File{f}, &Info{Instances: instances, Uses: uses})
if err != nil {
t.Fatal(err)
}
imports[pkg.Name()] = pkg
return pkg
}
makePkg(lib)
pkg := makePkg(test.src)
// look for instance information
var targs []Type
var typ Type
for ident, inst := range instances {
if syntax.String(ident) == test.name {
for i := 0; i < inst.TypeArgs.Len(); i++ {
targs = append(targs, inst.TypeArgs.At(i))
}
typ = inst.Type
// Check that we can find the corresponding parameterized type.
ptype := uses[ident].Type()
lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
if lister == nil || lister.TypeParams().Len() == 0 {
t.Errorf("package %s: info.Types[%v] = %v, want parameterized type", pkg.Name(), ident, ptype)
continue
}
// Verify the invariant that re-instantiating the generic type with
// TypeArgs results in an equivalent type.
inst2, err := Instantiate(nil, ptype, targs, true)
if err != nil {
t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
}
if !Identical(inst.Type, inst2) {
t.Errorf("%v and %v are not identical", inst.Type, inst2)
}
break
}
}
if targs == nil {
t.Errorf("package %s: no instance information found for %s", pkg.Name(), test.name)
continue
}
// check that type arguments are correct
if len(targs) != len(test.targs) {
t.Errorf("package %s: got %d type arguments; want %d", pkg.Name(), len(targs), len(test.targs))
continue
}
for i, targ := range targs {
if got := targ.String(); got != test.targs[i] {
t.Errorf("package %s, %d. type argument: got %s; want %s", pkg.Name(), i, got, test.targs[i])
continue
}
}
// check that the types match
if got := typ.Underlying().String(); got != test.typ {
t.Errorf("package %s: got %s; want %s", pkg.Name(), got, test.typ)
}
}
}
func TestDefsInfo(t *testing.T) {
var tests = []struct {
src string
obj string
want string
}{
{`package p0; const x = 42`, `x`, `const p0.x untyped int`},
{`package p1; const x int = 42`, `x`, `const p1.x int`},
{`package p2; var x int`, `x`, `var p2.x int`},
{`package p3; type x int`, `x`, `type p3.x int`},
{`package p4; func f()`, `f`, `func p4.f()`},
{`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
// Tests using generics.
{`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
{`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
{`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
}
for _, test := range tests {
info := Info{
Defs: make(map[*syntax.Name]Object),
}
name := mustTypecheck(t, "DefsInfo", test.src, &info)
// find object
var def Object
for id, obj := range info.Defs {
if id.Value == test.obj {
def = obj
break
}
}
if def == nil {
t.Errorf("package %s: %s not found", name, test.obj)
continue
}
if got := def.String(); got != test.want {
t.Errorf("package %s: got %s; want %s", name, got, test.want)
}
}
}
func TestUsesInfo(t *testing.T) {
var tests = []struct {
src string
obj string
want string
}{
{`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
{`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
{`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
{`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
{`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
// Tests using generics.
{`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
{`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
{`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
{`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
// Uses of fields are instantiated.
{`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
{`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
// Uses of methods are uses of the instantiated method.
{`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
{`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
{`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
{`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
{`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
{`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
{`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
{`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
{`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
{`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
{
`package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
`m`,
`func (m10.E[int]).m()`,
},
}
for _, test := range tests {
info := Info{
Uses: make(map[*syntax.Name]Object),
}
name := mustTypecheck(t, "UsesInfo", test.src, &info)
// find object
var use Object
for id, obj := range info.Uses {
if id.Value == test.obj {
if use != nil {
panic(fmt.Sprintf("multiple uses of %q", id.Value))
}
use = obj
}
}
if use == nil {
t.Errorf("package %s: %s not found", name, test.obj)
continue
}
if got := use.String(); got != test.want {
t.Errorf("package %s: got %s; want %s", name, got, test.want)
}
}
}
func TestGenericMethodInfo(t *testing.T) {
src := `package p
type N[A any] int
func (r N[B]) m() { r.m(); r.n() }
func (r *N[C]) n() { }
`
f, err := parseSrc("p.go", src)
if err != nil {
t.Fatal(err)
}
info := Info{
Defs: make(map[*syntax.Name]Object),
Uses: make(map[*syntax.Name]Object),
Selections: make(map[*syntax.SelectorExpr]*Selection),
}
var conf Config
pkg, err := conf.Check("p", []*syntax.File{f}, &info)
if err != nil {
t.Fatal(err)
}
N := pkg.Scope().Lookup("N").Type().(*Named)
// Find the generic methods stored on N.
gm, gn := N.Method(0), N.Method(1)
if gm.Name() == "n" {
gm, gn = gn, gm
}
// Collect objects from info.
var dm, dn *Func // the declared methods
var dmm, dmn *Func // the methods used in the body of m
for _, decl := range f.DeclList {
fdecl, ok := decl.(*syntax.FuncDecl)
if !ok {
continue
}
def := info.Defs[fdecl.Name].(*Func)
switch fdecl.Name.Value {
case "m":
dm = def
syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
if call, ok := n.(*syntax.CallExpr); ok {
sel := call.Fun.(*syntax.SelectorExpr)
use := info.Uses[sel.Sel].(*Func)
selection := info.Selections[sel]
if selection.Kind() != MethodVal {
t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
}
if selection.Obj() != use {
t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
}
switch sel.Sel.Value {
case "m":
dmm = use
case "n":
dmn = use
}
}
return true
})
case "n":
dn = def
}
}
if gm != dm {
t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
}
if gn != dn {
t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
}
if dmm != dm {
t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
}
if dmn == dn {
t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
}
}
func TestImplicitsInfo(t *testing.T) {
testenv.MustHaveGoBuild(t)
var tests = []struct {
src string
want string
}{
{`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
{`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
{`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
{`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
{`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
{`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
{`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
{`package p7; func f(x int) {}`, ""}, // no Implicits entry
{`package p8; func f(int) {}`, "field: var int"},
{`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
{`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
// Tests using generics.
{`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
{`package f1; func f[T any](int) {}`, "field: var int"},
{`package f2; func f[T any](T) {}`, "field: var T"},
{`package f3; func f[T any]() (complex64) { return 0 }`, "field: var complex64"},
{`package f4; func f[T any](t T) (T) { return t }`, "field: var T"},
{`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var *t0.T[_]"},
{`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
{`package t2; type T[A any] struct{}; func _[P any](x interface{}) { switch t := x.(type) { case T[P]: _ = t } }`, "caseClause: var t t2.T[P]"},
{`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
}
for _, test := range tests {
info := Info{
Implicits: make(map[syntax.Node]Object),
}
name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
// the test cases expect at most one Implicits entry
if len(info.Implicits) > 1 {
t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
continue
}
// extract Implicits entry, if any
var got string
for n, obj := range info.Implicits {
switch x := n.(type) {
case *syntax.ImportDecl:
got = "importSpec"
case *syntax.CaseClause:
got = "caseClause"
case *syntax.Field:
got = "field"
default:
t.Fatalf("package %s: unexpected %T", name, x)
}
got += ": " + obj.String()
}
// verify entry
if got != test.want {
t.Errorf("package %s: got %q; want %q", name, got, test.want)
}
}
}
func predString(tv TypeAndValue) string {
var buf bytes.Buffer
pred := func(b bool, s string) {
if b {
if buf.Len() > 0 {
buf.WriteString(", ")
}
buf.WriteString(s)
}
}
pred(tv.IsVoid(), "void")
pred(tv.IsType(), "type")
pred(tv.IsBuiltin(), "builtin")
pred(tv.IsValue() && tv.Value != nil, "const")
pred(tv.IsValue() && tv.Value == nil, "value")
pred(tv.IsNil(), "nil")
pred(tv.Addressable(), "addressable")
pred(tv.Assignable(), "assignable")
pred(tv.HasOk(), "hasOk")
if buf.Len() == 0 {
return "invalid"
}
return buf.String()
}
func TestPredicatesInfo(t *testing.T) {
testenv.MustHaveGoBuild(t)
var tests = []struct {
src string
expr string
pred string
}{
// void
{`package n0; func f() { f() }`, `f()`, `void`},
// types
{`package t0; type _ int`, `int`, `type`},
{`package t1; type _ []int`, `[]int`, `type`},
{`package t2; type _ func()`, `func()`, `type`},
{`package t3; type _ func(int)`, `int`, `type`},
{`package t3; type _ func(...int)`, `...int`, `type`},
// built-ins
{`package b0; var _ = len("")`, `len`, `builtin`},
{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
// constants
{`package c0; var _ = 42`, `42`, `const`},
{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
// values
{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
{`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
{`package v2; var _ = func(){}`, `func() {}`, `value`},
{`package v4; func f() { _ = f }`, `f`, `value`},
{`package v3; var _ *int = nil`, `nil`, `value, nil`},
{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
// addressable (and thus assignable) operands
{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
// composite literals are not addressable
// assignable but not addressable values
{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
// hasOk expressions
{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
// missing entries
// - package names are collected in the Uses map
// - identifiers being declared are collected in the Defs map
{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
{`package m2; const c = 0`, `c`, `<missing>`},
{`package m3; type T int`, `T`, `<missing>`},
{`package m4; var v int`, `v`, `<missing>`},
{`package m5; func f() {}`, `f`, `<missing>`},
{`package m6; func _(x int) {}`, `x`, `<missing>`},
{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
}
for _, test := range tests {
info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
// look for expression predicates
got := "<missing>"
for e, tv := range info.Types {
//println(name, syntax.String(e))
if syntax.String(e) == test.expr {
got = predString(tv)
break