1 // Copyright 2013 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.
9 "cmd/compile/internal/syntax"
17 . "cmd/compile/internal/types2"
20 func unimplemented() {
21 panic("unimplemented")
24 // genericPkg is a source prefix for packages that contain generic code.
25 const genericPkg = "package generic_"
27 // brokenPkg is a source prefix for packages that are not expected to parse
28 // or type-check cleanly. They are always parsed assuming that they contain
30 const brokenPkg = "package broken_"
32 func parseSrc(path, src string) (*syntax.File, error) {
34 if strings.HasPrefix(src, genericPkg) || strings.HasPrefix(src, brokenPkg) {
35 mode = syntax.AllowGenerics
37 errh := func(error) {} // dummy error handler so that parsing continues in presence of errors
38 return syntax.Parse(syntax.NewFileBase(path), strings.NewReader(src), errh, nil, mode)
41 func pkgFor(path, source string, info *Info) (*Package, error) {
42 f, err := parseSrc(path, source)
46 conf := Config{Importer: defaultImporter()}
47 return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
50 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
51 pkg, err := pkgFor(path, source, info)
55 name = "package " + pkg.Name()
57 t.Fatalf("%s: didn't type-check (%s)", name, err)
62 func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
63 f, err := parseSrc(path, source)
64 if f == nil { // ignore errors unless f is nil
65 t.Fatalf("%s: unable to parse: %s", path, err)
68 Error: func(err error) {},
69 Importer: defaultImporter(),
71 pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
72 return pkg.Name(), err
75 func TestValuesInfo(t *testing.T) {
76 var tests = []struct {
78 expr string // constant expression
79 typ string // constant type
80 val string // constant value
82 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
83 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
84 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
85 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
86 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
87 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
89 {`package b0; var _ = false`, `false`, `bool`, `false`},
90 {`package b1; var _ = 0`, `0`, `int`, `0`},
91 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
92 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
93 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
94 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
96 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
97 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
98 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
100 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
101 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
102 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
104 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
105 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
106 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
108 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
109 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
110 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
112 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
113 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
114 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
116 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
117 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
118 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
119 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
120 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
121 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
122 {`package c5g; var s uint; var _ = string(1 << s)`, `1 << s`, `untyped int`, ``},
124 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
125 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
126 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
127 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
129 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
130 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
131 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
132 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
133 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
134 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
135 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
136 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
138 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
139 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
140 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
141 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
142 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
143 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
144 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
145 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
146 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
147 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
148 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
149 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
151 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
154 for _, test := range tests {
156 Types: make(map[syntax.Expr]TypeAndValue),
158 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
160 // look for expression
162 for e := range info.Types {
163 if syntax.String(e) == test.expr {
169 t.Errorf("package %s: no expression found for %s", name, test.expr)
172 tv := info.Types[expr]
174 // check that type is correct
175 if got := tv.Type.String(); got != test.typ {
176 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
180 // if we have a constant, check that value is correct
182 if got := tv.Value.ExactString(); got != test.val {
183 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
187 t.Errorf("package %s: no constant found; want %s", name, test.val)
193 func TestTypesInfo(t *testing.T) {
194 var tests = []struct {
196 expr string // expression
197 typ string // value type
199 // single-valued expressions of untyped constants
200 {`package b0; var x interface{} = false`, `false`, `bool`},
201 {`package b1; var x interface{} = 0`, `0`, `int`},
202 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
203 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
204 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
207 {`package n0; var _ *int = nil`, `nil`, `*int`},
208 {`package n1; var _ func() = nil`, `nil`, `func()`},
209 {`package n2; var _ []byte = nil`, `nil`, `[]byte`},
210 {`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
211 {`package n4; var _ chan int = nil`, `nil`, `chan int`},
212 {`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
213 {`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
214 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
216 {`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
217 {`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
218 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
219 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
220 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
221 {`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
222 {`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
223 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
225 {`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
226 {`package n21; var _ = (func())(nil)`, `nil`, `func()`},
227 {`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
228 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
229 {`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
230 {`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
231 {`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
232 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
234 {`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
235 {`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
236 {`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
237 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
238 {`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
239 {`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
240 {`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
241 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
243 // comma-ok expressions
244 {`package p0; var x interface{}; var _, _ = x.(int)`,
248 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
252 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
254 `(complex128, p2a.mybool)`,
256 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
258 `(complex128, bool)`,
260 {`package p3; var c chan string; var _, _ = <-c`,
266 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
270 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
274 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
278 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
282 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
288 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
292 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
296 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
300 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
304 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
308 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
314 {`package issue28277_a; func f(...int)`,
318 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
323 // tests for broken code that doesn't parse or type-check
324 {brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
325 {brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
326 {brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
327 {brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
328 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
329 {brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
331 // parameterized functions
332 {genericPkg + `p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[generic_p0.T₁ interface{}](generic_p0.T₁)`},
333 {genericPkg + `p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
334 {genericPkg + `p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func[generic_p2.T₁ interface{}](generic_p2.T₁)`},
335 {genericPkg + `p3; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
338 {genericPkg + `t0; type t[] int; var _ t`, `t`, `generic_t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
339 {genericPkg + `t1; type t[P any] int; var _ t[int]`, `t`, `generic_t1.t[generic_t1.P₁ interface{}]`},
340 {genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[generic_t2.P₁ interface{}]`},
341 {genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[generic_t3.P₁, generic_t3.Q₂ interface{}]`},
342 {brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[broken_t4.P₁, broken_t4.Q₂ interface{m()}]`},
344 // instantiated types must be sanitized
345 {genericPkg + `g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `generic_g0.t[int]`},
348 {genericPkg + `issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `generic_issue45096.T₁`},
351 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
354 for _, test := range tests {
355 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
357 if strings.HasPrefix(test.src, brokenPkg) {
359 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
361 t.Errorf("package %s: expected to fail but passed", name)
365 name = mustTypecheck(t, "TypesInfo", test.src, &info)
368 // look for expression type
370 for e, tv := range info.Types {
371 if syntax.String(e) == test.expr {
377 t.Errorf("package %s: no type found for %s", name, test.expr)
381 // check that type is correct
382 if got := typ.String(); got != test.typ {
383 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
388 func TestInferredInfo(t *testing.T) {
389 var tests = []struct {
395 {genericPkg + `p0; func f[T any](T) {}; func _() { f(42) }`,
400 {genericPkg + `p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
405 {genericPkg + `p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
407 []string{`complex128`},
408 `func(...complex128) complex128`,
410 {genericPkg + `p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
412 []string{`float64`, `string`, `byte`},
413 `func(float64, *string, []byte)`,
415 {genericPkg + `p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
417 []string{`float64`, `byte`},
418 `func(float64, *byte, ...[]byte)`,
421 // we don't know how to translate these but we can type-check them
422 {genericPkg + `q0; type T struct{}; func (T) m[P any](P) {}; func _(x T) { x.m(42) }`,
427 {genericPkg + `q1; type T struct{}; func (T) m[P any](P) P { panic(0) }; func _(x T) { x.m(42) }`,
432 {genericPkg + `q2; type T struct{}; func (T) m[P any](...P) P { panic(0) }; func _(x T) { x.m(42) }`,
437 {genericPkg + `q3; type T struct{}; func (T) m[A, B, C any](A, *B, []C) {}; func _(x T) { x.m(1.2, new(string), []byte{}) }`,
439 []string{`float64`, `string`, `byte`},
440 `func(float64, *string, []byte)`,
442 {genericPkg + `q4; type T struct{}; func (T) m[A, B any](A, *B, ...[]B) {}; func _(x T) { x.m(1.2, new(byte)) }`,
444 []string{`float64`, `byte`},
445 `func(float64, *byte, ...[]byte)`,
448 {genericPkg + `r0; type T[P any] struct{}; func (_ T[P]) m[Q any](Q) {}; func _[P any](x T[P]) { x.m(42) }`,
453 // TODO(gri) record method type parameters in syntax.FuncType so we can check this
454 // {genericPkg + `r1; type T interface{ m[P any](P) }; func _(x T) { x.m(4.2) }`,
456 // []string{`float64`},
460 {genericPkg + `s1; func f[T any, P interface{~*T}](x T) {}; func _(x string) { f(x) }`,
462 []string{`string`, `*string`},
465 {genericPkg + `s2; func f[T any, P interface{~*T}](x []T) {}; func _(x []int) { f(x) }`,
467 []string{`int`, `*int`},
470 {genericPkg + `s3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
472 []string{`int`, `chan<- int`},
475 {genericPkg + `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) }`,
477 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
481 {genericPkg + `t1; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = f[string] }`,
483 []string{`string`, `*string`},
486 {genericPkg + `t2; type C[T any] interface{~chan<- T}; func f[T any, P C[T]]() []T { return nil }; func _() { _ = f[int] }`,
488 []string{`int`, `chan<- int`},
491 {genericPkg + `t3; type C[T any] interface{~chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
493 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
498 for _, test := range tests {
499 info := Info{Inferred: make(map[syntax.Expr]Inferred)}
500 name, err := mayTypecheck(t, "InferredInfo", test.src, &info)
502 t.Errorf("package %s: %v", name, err)
506 // look for inferred type arguments and signature
509 for call, inf := range info.Inferred {
511 switch x := call.(type) {
512 case *syntax.CallExpr:
514 case *syntax.IndexExpr:
517 panic(fmt.Sprintf("unexpected call expression type %T", call))
519 if syntax.String(fun) == test.fun {
526 t.Errorf("package %s: no inferred information found for %s", name, test.fun)
530 // check that type arguments are correct
531 if len(targs) != len(test.targs) {
532 t.Errorf("package %s: got %d type arguments; want %d", name, len(targs), len(test.targs))
535 for i, targ := range targs {
536 if got := targ.String(); got != test.targs[i] {
537 t.Errorf("package %s, %d. type argument: got %s; want %s", name, i, got, test.targs[i])
542 // check that signature is correct
543 if got := sig.String(); got != test.sig {
544 t.Errorf("package %s: got %s; want %s", name, got, test.sig)
549 func TestDefsInfo(t *testing.T) {
550 var tests = []struct {
555 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
556 {`package p1; const x int = 42`, `x`, `const p1.x int`},
557 {`package p2; var x int`, `x`, `var p2.x int`},
558 {`package p3; type x int`, `x`, `type p3.x int`},
559 {`package p4; func f()`, `f`, `func p4.f()`},
560 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
562 // generic types must be sanitized
563 // (need to use sufficiently nested types to provoke unexpanded types)
564 {genericPkg + `g0; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
565 {genericPkg + `g1; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
566 {genericPkg + `g2; type t[P any] P; type x struct{ f t[int] }`, `x`, `type generic_g2.x struct{f generic_g2.t[int]}`},
567 {genericPkg + `g3; type t[P any] P; func f(x struct{ f t[string] }); var g = f`, `g`, `var generic_g3.g func(x struct{f generic_g3.t[string]})`},
570 for _, test := range tests {
572 Defs: make(map[*syntax.Name]Object),
574 name := mustTypecheck(t, "DefsInfo", test.src, &info)
578 for id, obj := range info.Defs {
579 if id.Value == test.obj {
585 t.Errorf("package %s: %s not found", name, test.obj)
589 if got := def.String(); got != test.want {
590 t.Errorf("package %s: got %s; want %s", name, got, test.want)
595 func TestUsesInfo(t *testing.T) {
596 var tests = []struct {
601 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
602 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
603 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
604 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
605 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
607 // generic types must be sanitized
608 // (need to use sufficiently nested types to provoke unexpanded types)
609 {genericPkg + `g0; func _() { _ = x }; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
610 {genericPkg + `g1; func _() { _ = x }; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
611 {genericPkg + `g2; func _() { type _ x }; type t[P any] P; type x struct{ f t[int] }`, `x`, `type generic_g2.x struct{f generic_g2.t[int]}`},
612 {genericPkg + `g3; func _() { _ = f }; type t[P any] P; func f(x struct{ f t[string] })`, `f`, `func generic_g3.f(x struct{f generic_g3.t[string]})`},
615 for _, test := range tests {
617 Uses: make(map[*syntax.Name]Object),
619 name := mustTypecheck(t, "UsesInfo", test.src, &info)
623 for id, obj := range info.Uses {
624 if id.Value == test.obj {
630 t.Errorf("package %s: %s not found", name, test.obj)
634 if got := use.String(); got != test.want {
635 t.Errorf("package %s: got %s; want %s", name, got, test.want)
640 func TestImplicitsInfo(t *testing.T) {
641 testenv.MustHaveGoBuild(t)
643 var tests = []struct {
647 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
648 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
649 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
651 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
652 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
653 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
654 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
656 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
657 {`package p8; func f(int) {}`, "field: var int"},
658 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
659 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
662 for _, test := range tests {
664 Implicits: make(map[syntax.Node]Object),
666 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
668 // the test cases expect at most one Implicits entry
669 if len(info.Implicits) > 1 {
670 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
674 // extract Implicits entry, if any
676 for n, obj := range info.Implicits {
677 switch x := n.(type) {
678 case *syntax.ImportDecl:
680 case *syntax.CaseClause:
685 t.Fatalf("package %s: unexpected %T", name, x)
687 got += ": " + obj.String()
691 if got != test.want {
692 t.Errorf("package %s: got %q; want %q", name, got, test.want)
697 func predString(tv TypeAndValue) string {
699 pred := func(b bool, s string) {
702 buf.WriteString(", ")
708 pred(tv.IsVoid(), "void")
709 pred(tv.IsType(), "type")
710 pred(tv.IsBuiltin(), "builtin")
711 pred(tv.IsValue() && tv.Value != nil, "const")
712 pred(tv.IsValue() && tv.Value == nil, "value")
713 pred(tv.IsNil(), "nil")
714 pred(tv.Addressable(), "addressable")
715 pred(tv.Assignable(), "assignable")
716 pred(tv.HasOk(), "hasOk")
724 func TestPredicatesInfo(t *testing.T) {
725 testenv.MustHaveGoBuild(t)
727 var tests = []struct {
733 {`package n0; func f() { f() }`, `f()`, `void`},
736 {`package t0; type _ int`, `int`, `type`},
737 {`package t1; type _ []int`, `[]int`, `type`},
738 {`package t2; type _ func()`, `func()`, `type`},
739 {`package t3; type _ func(int)`, `int`, `type`},
740 {`package t3; type _ func(...int)`, `...int`, `type`},
743 {`package b0; var _ = len("")`, `len`, `builtin`},
744 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
747 {`package c0; var _ = 42`, `42`, `const`},
748 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
749 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
752 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
753 {`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
754 {`package v2; var _ = func(){}`, `func() {}`, `value`},
755 {`package v4; func f() { _ = f }`, `f`, `value`},
756 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
757 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
759 // addressable (and thus assignable) operands
760 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
761 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
762 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
763 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
764 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
765 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
766 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
767 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
768 // composite literals are not addressable
770 // assignable but not addressable values
771 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
772 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
775 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
776 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
779 // - package names are collected in the Uses map
780 // - identifiers being declared are collected in the Defs map
781 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
782 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
783 {`package m2; const c = 0`, `c`, `<missing>`},
784 {`package m3; type T int`, `T`, `<missing>`},
785 {`package m4; var v int`, `v`, `<missing>`},
786 {`package m5; func f() {}`, `f`, `<missing>`},
787 {`package m6; func _(x int) {}`, `x`, `<missing>`},
788 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
789 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
792 for _, test := range tests {
793 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
794 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
796 // look for expression predicates
798 for e, tv := range info.Types {
799 //println(name, syntax.String(e))
800 if syntax.String(e) == test.expr {
806 if got != test.pred {
807 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
812 func TestScopesInfo(t *testing.T) {
813 testenv.MustHaveGoBuild(t)
815 var tests = []struct {
817 scopes []string // list of scope descriptors of the form kind:varlist
819 {`package p0`, []string{
822 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
825 {`package p2; func _() {}`, []string{
828 {`package p3; func _(x, y int) {}`, []string{
831 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
832 "file:", "func:x y z", // redeclaration of x
834 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
835 "file:", "func:u x y",
837 {`package p6; func _() { { var x int; _ = x } }`, []string{
838 "file:", "func:", "block:x",
840 {`package p7; func _() { if true {} }`, []string{
841 "file:", "func:", "if:", "block:",
843 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
844 "file:", "func:", "if:x", "block:y",
846 {`package p9; func _() { switch x := 0; x {} }`, []string{
847 "file:", "func:", "switch:x",
849 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
850 "file:", "func:", "switch:x", "case:y", "case:",
852 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
853 "file:", "func:t", "switch:",
855 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
856 "file:", "func:t", "switch:t",
858 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
859 "file:", "func:t", "switch:", "case:x", // x implicitly declared
861 {`package p14; func _() { select{} }`, []string{
864 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
865 "file:", "func:c", "comm:",
867 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
868 "file:", "func:c", "comm:i x",
870 {`package p17; func _() { for{} }`, []string{
871 "file:", "func:", "for:", "block:",
873 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
874 "file:", "func:n", "for:i", "block:",
876 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
877 "file:", "func:a", "for:i", "block:",
879 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
880 "file:", "func:a", "for:i x", "block:",
884 for _, test := range tests {
885 info := Info{Scopes: make(map[syntax.Node]*Scope)}
886 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
888 // number of scopes must match
889 if len(info.Scopes) != len(test.scopes) {
890 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
893 // scope descriptions must match
894 for node, scope := range info.Scopes {
899 case *syntax.FuncType:
901 case *syntax.BlockStmt:
905 case *syntax.SwitchStmt:
907 case *syntax.SelectStmt:
909 case *syntax.CaseClause:
911 case *syntax.CommClause:
913 case *syntax.ForStmt:
916 kind = fmt.Sprintf("%T", node)
919 // look for matching scope description
920 desc := kind + ":" + strings.Join(scope.Names(), " ")
922 for _, d := range test.scopes {
929 t.Errorf("package %s: no matching scope found for %s", name, desc)
935 func TestInitOrderInfo(t *testing.T) {
936 var tests = []struct {
940 {`package p0; var (x = 1; y = x)`, []string{
943 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
944 "a = 1", "b = 2", "c = 3",
946 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
947 "a = 1", "b = 2", "c = 3",
949 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
950 "_ = f()", // blank var
952 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
953 "a = 0", "z = 0", "y = z", "x = y",
955 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
956 "a, _ = m[0]", // blank var
958 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
959 "z = 0", "a, b = f()",
961 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
962 "b = 1", "a = func() int {…}()",
964 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
965 "c = 1", "a, b = func() (_, _ int) {…}()",
967 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
970 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
971 "a = 0", "b = 0", "c = 0", "d = c + b",
973 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
974 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
976 // emit an initializer for n:1 initializations only once (not for each node
977 // on the lhs which may appear in different order in the dependency graph)
978 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
979 "b = 0", "x, y = m[0]", "a = x",
981 // test case from spec section on package initialization
995 "d = 3", "b = f()", "c = f()", "a = c + b",
997 // test case for issue 7131
1001 func next() int { counter++; return counter }
1004 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1007 var b, c = next(), next()
1008 var d, e, f = next(), next(), next()
1010 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1012 // test case for issue 10709
1022 func (T) m() int { return 0 }
1024 func makeT(n int) T {
1030 "t = makeT(0)", "v = t.m()",
1032 // test case for issue 10709: same as test before, but variable decls swapped
1042 func (T) m() int { return 0 }
1044 func makeT(n int) T {
1050 "t = makeT(0)", "v = t.m()",
1052 // another candidate possibly causing problems with issue 10709
1057 func f1() int { return g1() }
1058 func g1() int { f1(); return x1 }
1064 func f2() int { return g2() }
1065 func g2() int { return x2 }
1067 var x2 = 0`, []string{
1068 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1072 for _, test := range tests {
1074 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1076 // number of initializers must match
1077 if len(info.InitOrder) != len(test.inits) {
1078 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1082 // initializers must match
1083 for i, want := range test.inits {
1084 got := info.InitOrder[i].String()
1086 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1093 func TestMultiFileInitOrder(t *testing.T) {
1094 mustParse := func(src string) *syntax.File {
1095 f, err := parseSrc("main", src)
1102 fileA := mustParse(`package main; var a = 1`)
1103 fileB := mustParse(`package main; var b = 2`)
1105 // The initialization order must not depend on the parse
1106 // order of the files, only on the presentation order to
1107 // the type-checker.
1108 for _, test := range []struct {
1109 files []*syntax.File
1112 {[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
1113 {[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
1116 if _, err := new(Config).Check("main", test.files, &info); err != nil {
1119 if got := fmt.Sprint(info.InitOrder); got != test.want {
1120 t.Fatalf("got %s; want %s", got, test.want)
1125 func TestFiles(t *testing.T) {
1126 var sources = []string{
1127 "package p; type T struct{}; func (T) m1() {}",
1128 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1129 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1134 pkg := NewPackage("p", "p")
1136 check := NewChecker(&conf, pkg, &info)
1138 for i, src := range sources {
1139 filename := fmt.Sprintf("sources%d", i)
1140 f, err := parseSrc(filename, src)
1144 if err := check.Files([]*syntax.File{f}); err != nil {
1149 // check InitOrder is [x y]
1151 for _, init := range info.InitOrder {
1152 for _, v := range init.Lhs {
1153 vars = append(vars, v.Name())
1156 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1157 t.Errorf("InitOrder == %s, want %s", got, want)
1161 type testImporter map[string]*Package
1163 func (m testImporter) Import(path string) (*Package, error) {
1164 if pkg := m[path]; pkg != nil {
1167 return nil, fmt.Errorf("package %q not found", path)
1170 func TestSelection(t *testing.T) {
1171 t.Skip("requires fixes around source positions")
1173 selections := make(map[*syntax.SelectorExpr]*Selection)
1175 imports := make(testImporter)
1176 conf := Config{Importer: imports}
1177 makePkg := func(path, src string) {
1178 f, err := parseSrc(path+".go", src)
1182 pkg, err := conf.Check(path, []*syntax.File{f}, &Info{Selections: selections})
1220 // qualified identifiers
1254 // method expressions
1261 wantOut := map[string][2]string{
1262 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1264 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1265 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1266 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1267 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1268 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1269 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1270 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1271 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1273 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1274 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1275 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1276 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1277 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1278 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1279 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1280 "C{}.g": {"method (main.C) g()", ".[0]"},
1281 "new(C).g": {"method (*main.C) g()", "->[0]"},
1282 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1284 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1285 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1286 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1287 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1290 makePkg("lib", libSrc)
1291 makePkg("main", mainSrc)
1293 for e, sel := range selections {
1294 _ = sel.String() // assertion: must not panic
1298 // start := fset.Position(e.Pos()).Offset
1299 // end := fset.Position(e.End()).Offset
1300 // syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1308 fmt.Sprintf("%s%v", direct, sel.Index()),
1312 // want := wantOut[syntax]
1314 // t.Errorf("%s: got %q; want %q", syntax, got, want)
1316 // delete(wantOut, syntax)
1318 // We must explicitly assert properties of the
1319 // Signature's receiver since it doesn't participate
1320 // in Identical() or String().
1321 sig, _ := sel.Type().(*Signature)
1322 if sel.Kind() == MethodVal {
1323 got := sig.Recv().Type()
1325 if !Identical(got, want) {
1327 // t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1329 } else if sig != nil && sig.Recv() != nil {
1330 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1333 // Assert that all wantOut entries were used exactly once.
1334 for syntax := range wantOut {
1335 t.Errorf("no syntax.Selection found with syntax %q", syntax)
1339 func TestIssue8518(t *testing.T) {
1340 imports := make(testImporter)
1342 Error: func(err error) { t.Log(err) }, // don't exit after first error
1345 makePkg := func(path, src string) {
1346 f, err := parseSrc(path, src)
1350 pkg, _ := conf.Check(path, []*syntax.File{f}, nil) // errors logged via conf.Error
1358 const C2 = missing.C
1368 makePkg("a", libSrc)
1369 makePkg("main", mainSrc) // don't crash when type-checking this package
1372 func TestLookupFieldOrMethod(t *testing.T) {
1373 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1374 // addressable value, and x for a non-addressable value (even though a variable
1375 // for ease of test case writing).
1376 var tests = []struct {
1383 {"var x T; type T struct{}", false, nil, false},
1384 {"var x T; type T struct{ f int }", true, []int{0}, false},
1385 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1388 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1389 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1390 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1391 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1394 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1395 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1397 // outside methodset
1398 // (*T).f method exists, but value of type T is not addressable
1399 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1402 for _, test := range tests {
1403 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1405 t.Errorf("%s: incorrect test case: %s", test.src, err)
1409 obj := pkg.Scope().Lookup("a")
1411 if obj = pkg.Scope().Lookup("x"); obj == nil {
1412 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1417 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1418 if (f != nil) != test.found {
1420 t.Errorf("%s: got no object; want one", test.src)
1422 t.Errorf("%s: got object = %v; want none", test.src, f)
1425 if !sameSlice(index, test.index) {
1426 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1428 if indirect != test.indirect {
1429 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1434 func sameSlice(a, b []int) bool {
1435 if len(a) != len(b) {
1438 for i, x := range a {
1446 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1447 // the correct result at various positions within the source.
1448 func TestScopeLookupParent(t *testing.T) {
1449 imports := make(testImporter)
1450 conf := Config{Importer: imports}
1452 makePkg := func(path, src string) {
1453 f, err := parseSrc(path, src)
1457 imports[path], err = conf.Check(path, []*syntax.File{f}, &info)
1463 makePkg("lib", "package lib; var X int")
1464 // Each /*name=kind:line*/ comment makes the test look up the
1465 // name at that point and checks that it resolves to a decl of
1466 // the specified kind and line number. "undef" means undefined.
1468 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1479 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1480 type /*t=undef*/ t /*t=typename:14*/ *t
1481 print(Y) /*Y=var:10*/
1482 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1483 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1486 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
1489 switch y := i.(type) { /*y=undef*/
1490 case /*y=undef*/ int /*y=var:23*/ :
1491 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1492 default /*y=var:23*/:
1497 switch int := i.(type) {
1498 case /*int=typename:0*/ int /*int=var:31*/ :
1500 default /*int=var:31*/ :
1506 info.Uses = make(map[*syntax.Name]Object)
1507 makePkg("main", mainSrc)
1508 mainScope := imports["main"].Scope()
1510 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1512 base := syntax.NewFileBase("main")
1513 syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
1514 pos := syntax.MakePos(base, line, col)
1516 // Syntax errors are not comments.
1518 t.Errorf("%s: %s", pos, text)
1522 // Parse the assertion in the comment.
1523 m := rx.FindStringSubmatch(text)
1525 t.Errorf("%s: bad comment: %s", pos, text)
1528 name, want := m[1], m[2]
1530 // Look up the name in the innermost enclosing scope.
1531 inner := mainScope.Innermost(pos)
1533 t.Errorf("%s: at %s: can't find innermost scope", pos, text)
1537 if _, obj := inner.LookupParent(name, pos); obj != nil {
1538 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
1539 got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
1542 t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
1546 // Check that for each referring identifier,
1547 // a lookup of its name on the innermost
1548 // enclosing scope returns the correct object.
1550 for id, wantObj := range info.Uses {
1551 inner := mainScope.Innermost(id.Pos())
1553 t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
1557 // Exclude selectors and qualified identifiers---lexical
1558 // refs only. (Ideally, we'd see if the AST parent is a
1559 // SelectorExpr, but that requires PathEnclosingInterval
1560 // from golang.org/x/tools/go/ast/astutil.)
1561 if id.Value == "X" {
1565 _, gotObj := inner.LookupParent(id.Value, id.Pos())
1566 if gotObj != wantObj {
1567 t.Errorf("%s: got %v, want %v", id.Pos(), gotObj, wantObj)
1573 var nopos syntax.Pos
1575 // newDefined creates a new defined type named T with the given underlying type.
1576 func newDefined(underlying Type) *Named {
1577 tname := NewTypeName(nopos, nil, "T", nil)
1578 return NewNamed(tname, underlying, nil)
1581 func TestConvertibleTo(t *testing.T) {
1582 for _, test := range []struct {
1586 {Typ[Int], Typ[Int], true},
1587 {Typ[Int], Typ[Float32], true},
1588 {newDefined(Typ[Int]), Typ[Int], true},
1589 {newDefined(new(Struct)), new(Struct), true},
1590 {newDefined(Typ[Int]), new(Struct), false},
1591 {Typ[UntypedInt], Typ[Int], true},
1592 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1593 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1594 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1595 // Untyped string values are not permitted by the spec, so the below
1596 // behavior is undefined.
1597 {Typ[UntypedString], Typ[String], true},
1599 if got := ConvertibleTo(test.v, test.t); got != test.want {
1600 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1605 func TestAssignableTo(t *testing.T) {
1606 for _, test := range []struct {
1610 {Typ[Int], Typ[Int], true},
1611 {Typ[Int], Typ[Float32], false},
1612 {newDefined(Typ[Int]), Typ[Int], false},
1613 {newDefined(new(Struct)), new(Struct), true},
1614 {Typ[UntypedBool], Typ[Bool], true},
1615 {Typ[UntypedString], Typ[Bool], false},
1616 // Neither untyped string nor untyped numeric assignments arise during
1617 // normal type checking, so the below behavior is technically undefined by
1619 {Typ[UntypedString], Typ[String], true},
1620 {Typ[UntypedInt], Typ[Int], true},
1622 if got := AssignableTo(test.v, test.t); got != test.want {
1623 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1628 func TestIdentical_issue15173(t *testing.T) {
1629 // Identical should allow nil arguments and be symmetric.
1630 for _, test := range []struct {
1634 {Typ[Int], Typ[Int], true},
1635 {Typ[Int], nil, false},
1636 {nil, Typ[Int], false},
1639 if got := Identical(test.x, test.y); got != test.want {
1640 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1645 func TestIssue15305(t *testing.T) {
1646 const src = "package p; func f() int16; var _ = f(undef)"
1647 f, err := parseSrc("issue15305.go", src)
1652 Error: func(err error) {}, // allow errors
1655 Types: make(map[syntax.Expr]TypeAndValue),
1657 conf.Check("p", []*syntax.File{f}, info) // ignore result
1658 for e, tv := range info.Types {
1659 if _, ok := e.(*syntax.CallExpr); ok {
1660 if tv.Type != Typ[Int16] {
1661 t.Errorf("CallExpr has type %v, want int16", tv.Type)
1666 t.Errorf("CallExpr has no type")
1669 // TestCompositeLitTypes verifies that Info.Types registers the correct
1670 // types for composite literal expressions and composite literal type
1672 func TestCompositeLitTypes(t *testing.T) {
1673 for _, test := range []struct {
1676 {`[16]byte{}`, `[16]byte`},
1677 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
1678 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
1679 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
1680 {`[]int{}`, `[]int`},
1681 {`map[string]bool{"foo": true}`, `map[string]bool`},
1682 {`struct{}{}`, `struct{}`},
1683 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
1685 f, err := parseSrc(test.lit, "package p; var _ = "+test.lit)
1687 t.Fatalf("%s: %v", test.lit, err)
1691 Types: make(map[syntax.Expr]TypeAndValue),
1693 if _, err = new(Config).Check("p", []*syntax.File{f}, info); err != nil {
1694 t.Fatalf("%s: %v", test.lit, err)
1697 cmptype := func(x syntax.Expr, want string) {
1698 tv, ok := info.Types[x]
1700 t.Errorf("%s: no Types entry found", test.lit)
1704 t.Errorf("%s: type is nil", test.lit)
1707 if got := tv.Type.String(); got != want {
1708 t.Errorf("%s: got %v, want %s", test.lit, got, want)
1712 // test type of composite literal expression
1713 rhs := f.DeclList[0].(*syntax.VarDecl).Values
1714 cmptype(rhs, test.typ)
1716 // test type of composite literal type expression
1717 cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
1721 // TestObjectParents verifies that objects have parent scopes or not
1722 // as specified by the Object interface.
1723 func TestObjectParents(t *testing.T) {
1742 func f(x int) { y := x; print(y) }
1745 f, err := parseSrc("src", src)
1751 Defs: make(map[*syntax.Name]Object),
1753 if _, err = new(Config).Check("p", []*syntax.File{f}, info); err != nil {
1757 for ident, obj := range info.Defs {
1759 // only package names and implicit vars have a nil object
1760 // (in this test we only need to handle the package name)
1761 if ident.Value != "p" {
1762 t.Errorf("%v has nil object", ident)
1767 // struct fields, type-associated and interface methods
1768 // have no parent scope
1770 switch obj := obj.(type) {
1776 if obj.Type().(*Signature).Recv() != nil { // method
1781 gotParent := obj.Parent() != nil
1783 case gotParent && !wantParent:
1784 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
1785 case !gotParent && wantParent:
1786 t.Errorf("%v: no parent found", ident)
1791 // TestFailedImport tests that we don't get follow-on errors
1792 // elsewhere in a package due to failing to import a package.
1793 func TestFailedImport(t *testing.T) {
1794 testenv.MustHaveGoBuild(t)
1799 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
1804 func f(x T) T { return foo.F(x) }
1806 f, err := parseSrc("src", src)
1810 files := []*syntax.File{f}
1812 // type-check using all possible importers
1813 for _, compiler := range []string{"gc", "gccgo", "source"} {
1816 Error: func(err error) {
1817 // we should only see the import error
1818 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
1819 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
1823 //Importer: importer.For(compiler, nil),
1827 Uses: make(map[*syntax.Name]Object),
1829 pkg, _ := conf.Check("p", files, info)
1831 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
1835 imports := pkg.Imports()
1836 if len(imports) != 1 {
1837 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
1841 if imp.Name() != "foo" {
1842 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
1846 // verify that all uses of foo refer to the imported package foo (imp)
1847 for ident, obj := range info.Uses {
1848 if ident.Value == "foo" {
1849 if obj, ok := obj.(*PkgName); ok {
1850 if obj.Imported() != imp {
1851 t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
1854 t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
1861 func TestInstantiate(t *testing.T) {
1862 // eventually we like more tests but this is a start
1863 const src = genericPkg + "p; type T[P any] *T[P]"
1864 pkg, err := pkgFor(".", src, nil)
1869 // type T should have one type parameter
1870 T := pkg.Scope().Lookup("T").Type().(*Named)
1871 if n := T.TParams().Len(); n != 1 {
1872 t.Fatalf("expected 1 type parameter; found %d", n)
1875 // instantiation should succeed (no endless recursion)
1876 // even with a nil *Checker
1877 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
1882 // instantiated type should point to itself
1883 if p := res.Underlying().(*Pointer).Elem(); p != res {
1884 t.Fatalf("unexpected result type: %s points to %s", res, p)
1888 func TestInstantiateErrors(t *testing.T) {
1890 src string // by convention, T must be the type being instantiated
1892 wantAt int // -1 indicates no error
1894 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
1895 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
1896 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
1897 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
1900 for _, test := range tests {
1901 src := genericPkg + "p; " + test.src
1902 pkg, err := pkgFor(".", src, nil)
1907 T := pkg.Scope().Lookup("T").Type().(*Named)
1909 _, err = Instantiate(nil, T, test.targs, true)
1911 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
1914 gotAt := err.(ArgumentError).Index()
1915 if gotAt != test.wantAt {
1916 t.Errorf("Instantate(%v, %v): error at index %d, want index %d", T, test.targs, gotAt, test.wantAt)
1921 func TestInstanceIdentity(t *testing.T) {
1922 imports := make(testImporter)
1923 conf := Config{Importer: imports}
1924 makePkg := func(src string) {
1925 f, err := parseSrc("", src)
1929 name := f.PkgName.Value
1930 pkg, err := conf.Check(name, []*syntax.File{f}, nil)
1936 makePkg(genericPkg + `lib; type T[P any] struct{}`)
1937 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
1938 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
1939 a := imports["generic_a"].Scope().Lookup("A")
1940 b := imports["generic_b"].Scope().Lookup("B")
1941 if !Identical(a.Type(), b.Type()) {
1942 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())