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.
12 "go/internal/typeparams"
24 // pkgFor parses and type checks the package specified by path and source,
25 // populating info if provided.
27 // If source begins with "package generic_" and type parameters are enabled,
28 // generic code is permitted.
29 func pkgFor(path, source string, info *Info) (*Package, error) {
30 fset := token.NewFileSet()
31 mode := modeForSource(source)
32 f, err := parser.ParseFile(fset, path, source, mode)
36 conf := Config{Importer: importer.Default()}
37 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
40 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
41 pkg, err := pkgFor(path, source, info)
45 name = "package " + pkg.Name()
47 t.Fatalf("%s: didn't type-check (%s)", name, err)
52 // genericPkg is a prefix for packages that should be type checked with
54 const genericPkg = "package generic_"
56 func modeForSource(src string) parser.Mode {
57 if !strings.HasPrefix(src, genericPkg) {
58 return typeparams.DisallowParsing
63 func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
64 fset := token.NewFileSet()
65 mode := modeForSource(source)
66 f, err := parser.ParseFile(fset, path, source, mode)
67 if f == nil { // ignore errors unless f is nil
68 t.Fatalf("%s: unable to parse: %s", path, err)
71 Error: func(err error) {},
72 Importer: importer.Default(),
74 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
75 return pkg.Name(), err
78 func TestValuesInfo(t *testing.T) {
79 var tests = []struct {
81 expr string // constant expression
82 typ string // constant type
83 val string // constant value
85 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
86 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
87 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
88 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
89 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
90 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
92 {`package b0; var _ = false`, `false`, `bool`, `false`},
93 {`package b1; var _ = 0`, `0`, `int`, `0`},
94 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
95 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
96 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
97 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
99 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
100 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
101 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
103 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
104 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
105 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
107 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
108 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
109 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
111 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
112 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
113 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
115 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
116 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
117 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
119 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
120 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
121 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
122 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
123 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
124 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
125 {`package c5g; var s uint; var _ = string(1 << s)`, `1 << s`, `untyped int`, ``},
127 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
128 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
129 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
130 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
132 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
133 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
134 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
135 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
136 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
137 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
138 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
139 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
141 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
142 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
143 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
144 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
145 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
146 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
147 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
148 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
149 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
150 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
151 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
152 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
154 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
157 for _, test := range tests {
159 Types: make(map[ast.Expr]TypeAndValue),
161 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
163 // look for expression
165 for e := range info.Types {
166 if ExprString(e) == test.expr {
172 t.Errorf("package %s: no expression found for %s", name, test.expr)
175 tv := info.Types[expr]
177 // check that type is correct
178 if got := tv.Type.String(); got != test.typ {
179 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
183 // if we have a constant, check that value is correct
185 if got := tv.Value.ExactString(); got != test.val {
186 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
190 t.Errorf("package %s: no constant found; want %s", name, test.val)
196 func TestTypesInfo(t *testing.T) {
197 // Test sources that are not expected to typecheck must start with the broken prefix.
198 const broken = "package broken_"
200 var tests = []struct {
202 expr string // expression
203 typ string // value type
205 // single-valued expressions of untyped constants
206 {`package b0; var x interface{} = false`, `false`, `bool`},
207 {`package b1; var x interface{} = 0`, `0`, `int`},
208 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
209 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
210 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
213 {`package n0; var _ *int = nil`, `nil`, `untyped nil`},
214 {`package n1; var _ func() = nil`, `nil`, `untyped nil`},
215 {`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
216 {`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
217 {`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
218 {`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
219 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
221 {`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
222 {`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
223 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
224 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
225 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
226 {`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
227 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
229 {`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
230 {`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
231 {`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
232 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
233 {`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
234 {`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
235 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
237 {`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
238 {`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
239 {`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
240 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
241 {`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
242 {`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
243 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
245 // comma-ok expressions
246 {`package p0; var x interface{}; var _, _ = x.(int)`,
250 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
254 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
256 `(complex128, p2a.mybool)`,
258 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
260 `(complex128, bool)`,
262 {`package p3; var c chan string; var _, _ = <-c`,
268 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
272 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
276 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
280 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
284 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
290 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
294 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
298 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
302 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
306 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
310 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
316 {`package issue28277_a; func f(...int)`,
320 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
326 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
327 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `uint`}, // issue 47410: should be untyped float
328 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
329 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
330 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
331 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
332 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
333 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
334 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
335 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
337 // tests for broken code that doesn't parse or type-check
338 {broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
339 {broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
340 {broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a; f: b;}}`, `b`, `string`},
341 {broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
342 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
343 {broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string][-1]int`},
345 // parameterized functions
346 {genericPkg + `p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[generic_p0.T₁ interface{}](generic_p0.T₁)`},
347 {genericPkg + `p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
348 {genericPkg + `p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func[generic_p2.T₁ interface{}](generic_p2.T₁)`},
349 {genericPkg + `p3; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
352 {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
353 {genericPkg + `t1; type t[P any] int; var _ t[int]`, `t`, `generic_t1.t[generic_t1.P₁ interface{}]`},
354 {genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[generic_t2.P₁ interface{}]`},
355 {genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[generic_t3.P₁, generic_t3.Q₂ interface{}]`},
357 // TODO (rFindley): compare with types2, which resolves the type broken_t4.t[P₁, Q₂ interface{m()}] here
358 {broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t`},
360 // instantiated types must be sanitized
361 {genericPkg + `g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `generic_g0.t[int]`},
364 {genericPkg + `issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `generic_issue45096.T₁`},
367 for _, test := range tests {
368 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
370 if strings.HasPrefix(test.src, broken) {
372 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
374 t.Errorf("package %s: expected to fail but passed", name)
378 name = mustTypecheck(t, "TypesInfo", test.src, &info)
381 // look for expression type
383 for e, tv := range info.Types {
384 if ExprString(e) == test.expr {
390 t.Errorf("package %s: no type found for %s", name, test.expr)
394 // check that type is correct
395 if got := typ.String(); got != test.typ {
396 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
401 func TestInferredInfo(t *testing.T) {
402 var tests = []struct {
408 {genericPkg + `p0; func f[T any](T) {}; func _() { f(42) }`,
413 {genericPkg + `p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
418 {genericPkg + `p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
420 []string{`complex128`},
421 `func(...complex128) complex128`,
423 {genericPkg + `p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
425 []string{`float64`, `string`, `byte`},
426 `func(float64, *string, []byte)`,
428 {genericPkg + `p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
430 []string{`float64`, `byte`},
431 `func(float64, *byte, ...[]byte)`,
434 {genericPkg + `s1; func f[T any, P interface{~*T}](x T) {}; func _(x string) { f(x) }`,
436 []string{`string`, `*string`},
439 {genericPkg + `s2; func f[T any, P interface{~*T}](x []T) {}; func _(x []int) { f(x) }`,
441 []string{`int`, `*int`},
444 {genericPkg + `s3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
446 []string{`int`, `chan<- int`},
449 {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) }`,
451 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
455 {genericPkg + `t1; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = f[string] }`,
457 []string{`string`, `*string`},
460 {genericPkg + `t2; type C[T any] interface{~chan<- T}; func f[T any, P C[T]]() []T { return nil }; func _() { _ = f[int] }`,
462 []string{`int`, `chan<- int`},
465 {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] }`,
467 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
472 for _, test := range tests {
474 info.Inferred = make(map[ast.Expr]Inferred)
475 name, err := mayTypecheck(t, "InferredInfo", test.src, &info)
477 t.Errorf("package %s: %v", name, err)
481 // look for inferred type arguments and signature
484 for call, inf := range info.Inferred {
486 switch x := call.(type) {
492 panic(fmt.Sprintf("unexpected call expression type %T", call))
494 if ExprString(fun) == test.fun {
501 t.Errorf("package %s: no inferred information found for %s", name, test.fun)
505 // check that type arguments are correct
506 if len(targs) != len(test.targs) {
507 t.Errorf("package %s: got %d type arguments; want %d", name, len(targs), len(test.targs))
510 for i, targ := range targs {
511 if got := targ.String(); got != test.targs[i] {
512 t.Errorf("package %s, %d. type argument: got %s; want %s", name, i, got, test.targs[i])
517 // check that signature is correct
518 if got := sig.String(); got != test.sig {
519 t.Errorf("package %s: got %s; want %s", name, got, test.sig)
524 func TestDefsInfo(t *testing.T) {
525 var tests = []struct {
530 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
531 {`package p1; const x int = 42`, `x`, `const p1.x int`},
532 {`package p2; var x int`, `x`, `var p2.x int`},
533 {`package p3; type x int`, `x`, `type p3.x int`},
534 {`package p4; func f()`, `f`, `func p4.f()`},
535 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
537 // generic types must be sanitized
538 // (need to use sufficiently nested types to provoke unexpanded types)
539 {genericPkg + `g0; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
540 {genericPkg + `g1; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
541 {genericPkg + `g2; type t[P any] P; type x struct{ f t[int] }`, `x`, `type generic_g2.x struct{f generic_g2.t[int]}`},
542 {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]})`},
545 for _, test := range tests {
547 Defs: make(map[*ast.Ident]Object),
549 name := mustTypecheck(t, "DefsInfo", test.src, &info)
553 for id, obj := range info.Defs {
554 if id.Name == test.obj {
560 t.Errorf("package %s: %s not found", name, test.obj)
564 if got := def.String(); got != test.want {
565 t.Errorf("package %s: got %s; want %s", name, got, test.want)
570 func TestUsesInfo(t *testing.T) {
571 var tests = []struct {
576 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
577 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
578 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
579 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
580 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
582 // generic types must be sanitized
583 // (need to use sufficiently nested types to provoke unexpanded types)
584 {genericPkg + `g0; func _() { _ = x }; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
585 {genericPkg + `g1; func _() { _ = x }; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
586 {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]}`},
587 {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]})`},
590 for _, test := range tests {
592 Uses: make(map[*ast.Ident]Object),
594 name := mustTypecheck(t, "UsesInfo", test.src, &info)
598 for id, obj := range info.Uses {
599 if id.Name == test.obj {
605 t.Errorf("package %s: %s not found", name, test.obj)
609 if got := use.String(); got != test.want {
610 t.Errorf("package %s: got %s; want %s", name, got, test.want)
615 func TestImplicitsInfo(t *testing.T) {
616 testenv.MustHaveGoBuild(t)
618 var tests = []struct {
622 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
623 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
624 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
626 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
627 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
628 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
629 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
631 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
632 {`package p8; func f(int) {}`, "field: var int"},
633 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
634 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
637 for _, test := range tests {
639 Implicits: make(map[ast.Node]Object),
641 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
643 // the test cases expect at most one Implicits entry
644 if len(info.Implicits) > 1 {
645 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
649 // extract Implicits entry, if any
651 for n, obj := range info.Implicits {
652 switch x := n.(type) {
653 case *ast.ImportSpec:
655 case *ast.CaseClause:
660 t.Fatalf("package %s: unexpected %T", name, x)
662 got += ": " + obj.String()
666 if got != test.want {
667 t.Errorf("package %s: got %q; want %q", name, got, test.want)
672 func predString(tv TypeAndValue) string {
674 pred := func(b bool, s string) {
677 buf.WriteString(", ")
683 pred(tv.IsVoid(), "void")
684 pred(tv.IsType(), "type")
685 pred(tv.IsBuiltin(), "builtin")
686 pred(tv.IsValue() && tv.Value != nil, "const")
687 pred(tv.IsValue() && tv.Value == nil, "value")
688 pred(tv.IsNil(), "nil")
689 pred(tv.Addressable(), "addressable")
690 pred(tv.Assignable(), "assignable")
691 pred(tv.HasOk(), "hasOk")
699 func TestPredicatesInfo(t *testing.T) {
700 testenv.MustHaveGoBuild(t)
702 var tests = []struct {
708 {`package n0; func f() { f() }`, `f()`, `void`},
711 {`package t0; type _ int`, `int`, `type`},
712 {`package t1; type _ []int`, `[]int`, `type`},
713 {`package t2; type _ func()`, `func()`, `type`},
714 {`package t3; type _ func(int)`, `int`, `type`},
715 {`package t3; type _ func(...int)`, `...int`, `type`},
718 {`package b0; var _ = len("")`, `len`, `builtin`},
719 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
722 {`package c0; var _ = 42`, `42`, `const`},
723 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
724 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
727 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
728 {`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
729 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
730 {`package v4; func f() { _ = f }`, `f`, `value`},
731 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
732 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
734 // addressable (and thus assignable) operands
735 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
736 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
737 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
738 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
739 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
740 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
741 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
742 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
743 // composite literals are not addressable
745 // assignable but not addressable values
746 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
747 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
750 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
751 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
754 // - package names are collected in the Uses map
755 // - identifiers being declared are collected in the Defs map
756 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
757 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
758 {`package m2; const c = 0`, `c`, `<missing>`},
759 {`package m3; type T int`, `T`, `<missing>`},
760 {`package m4; var v int`, `v`, `<missing>`},
761 {`package m5; func f() {}`, `f`, `<missing>`},
762 {`package m6; func _(x int) {}`, `x`, `<missing>`},
763 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
764 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
767 for _, test := range tests {
768 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
769 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
771 // look for expression predicates
773 for e, tv := range info.Types {
774 //println(name, ExprString(e))
775 if ExprString(e) == test.expr {
781 if got != test.pred {
782 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
787 func TestScopesInfo(t *testing.T) {
788 testenv.MustHaveGoBuild(t)
790 var tests = []struct {
792 scopes []string // list of scope descriptors of the form kind:varlist
794 {`package p0`, []string{
797 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
800 {`package p2; func _() {}`, []string{
803 {`package p3; func _(x, y int) {}`, []string{
806 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
807 "file:", "func:x y z", // redeclaration of x
809 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
810 "file:", "func:u x y",
812 {`package p6; func _() { { var x int; _ = x } }`, []string{
813 "file:", "func:", "block:x",
815 {`package p7; func _() { if true {} }`, []string{
816 "file:", "func:", "if:", "block:",
818 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
819 "file:", "func:", "if:x", "block:y",
821 {`package p9; func _() { switch x := 0; x {} }`, []string{
822 "file:", "func:", "switch:x",
824 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
825 "file:", "func:", "switch:x", "case:y", "case:",
827 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
828 "file:", "func:t", "type switch:",
830 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
831 "file:", "func:t", "type switch:t",
833 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
834 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
836 {`package p14; func _() { select{} }`, []string{
839 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
840 "file:", "func:c", "comm:",
842 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
843 "file:", "func:c", "comm:i x",
845 {`package p17; func _() { for{} }`, []string{
846 "file:", "func:", "for:", "block:",
848 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
849 "file:", "func:n", "for:i", "block:",
851 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
852 "file:", "func:a", "range:i", "block:",
854 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
855 "file:", "func:a", "range:i x", "block:",
859 for _, test := range tests {
860 info := Info{Scopes: make(map[ast.Node]*Scope)}
861 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
863 // number of scopes must match
864 if len(info.Scopes) != len(test.scopes) {
865 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
868 // scope descriptions must match
869 for node, scope := range info.Scopes {
870 kind := "<unknown node kind>"
880 case *ast.SwitchStmt:
882 case *ast.TypeSwitchStmt:
884 case *ast.CaseClause:
886 case *ast.CommClause:
894 // look for matching scope description
895 desc := kind + ":" + strings.Join(scope.Names(), " ")
897 for _, d := range test.scopes {
904 t.Errorf("package %s: no matching scope found for %s", name, desc)
910 func TestInitOrderInfo(t *testing.T) {
911 var tests = []struct {
915 {`package p0; var (x = 1; y = x)`, []string{
918 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
919 "a = 1", "b = 2", "c = 3",
921 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
922 "a = 1", "b = 2", "c = 3",
924 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
925 "_ = f()", // blank var
927 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
928 "a = 0", "z = 0", "y = z", "x = y",
930 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
931 "a, _ = m[0]", // blank var
933 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
934 "z = 0", "a, b = f()",
936 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
937 "b = 1", "a = (func() int literal)()",
939 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
940 "c = 1", "a, b = (func() (_, _ int) literal)()",
942 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
945 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
946 "a = 0", "b = 0", "c = 0", "d = c + b",
948 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
949 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
951 // emit an initializer for n:1 initializations only once (not for each node
952 // on the lhs which may appear in different order in the dependency graph)
953 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
954 "b = 0", "x, y = m[0]", "a = x",
956 // test case from spec section on package initialization
970 "d = 3", "b = f()", "c = f()", "a = c + b",
972 // test case for issue 7131
976 func next() int { counter++; return counter }
979 func makeOrder() []int { return []int{f, b, d, e, c, a} }
982 var b, c = next(), next()
983 var d, e, f = next(), next(), next()
985 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
987 // test case for issue 10709
997 func (T) m() int { return 0 }
999 func makeT(n int) T {
1005 "t = makeT(0)", "v = t.m()",
1007 // test case for issue 10709: same as test before, but variable decls swapped
1017 func (T) m() int { return 0 }
1019 func makeT(n int) T {
1025 "t = makeT(0)", "v = t.m()",
1027 // another candidate possibly causing problems with issue 10709
1032 func f1() int { return g1() }
1033 func g1() int { f1(); return x1 }
1039 func f2() int { return g2() }
1040 func g2() int { return x2 }
1042 var x2 = 0`, []string{
1043 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1047 for _, test := range tests {
1049 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1051 // number of initializers must match
1052 if len(info.InitOrder) != len(test.inits) {
1053 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1057 // initializers must match
1058 for i, want := range test.inits {
1059 got := info.InitOrder[i].String()
1061 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1068 func TestMultiFileInitOrder(t *testing.T) {
1069 fset := token.NewFileSet()
1070 mustParse := func(src string) *ast.File {
1071 f, err := parser.ParseFile(fset, "main", src, 0)
1078 fileA := mustParse(`package main; var a = 1`)
1079 fileB := mustParse(`package main; var b = 2`)
1081 // The initialization order must not depend on the parse
1082 // order of the files, only on the presentation order to
1083 // the type-checker.
1084 for _, test := range []struct {
1088 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1089 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1092 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1095 if got := fmt.Sprint(info.InitOrder); got != test.want {
1096 t.Fatalf("got %s; want %s", got, test.want)
1101 func TestFiles(t *testing.T) {
1102 var sources = []string{
1103 "package p; type T struct{}; func (T) m1() {}",
1104 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1105 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1110 fset := token.NewFileSet()
1111 pkg := NewPackage("p", "p")
1113 check := NewChecker(&conf, fset, pkg, &info)
1115 for i, src := range sources {
1116 filename := fmt.Sprintf("sources%d", i)
1117 f, err := parser.ParseFile(fset, filename, src, 0)
1121 if err := check.Files([]*ast.File{f}); err != nil {
1126 // check InitOrder is [x y]
1128 for _, init := range info.InitOrder {
1129 for _, v := range init.Lhs {
1130 vars = append(vars, v.Name())
1133 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1134 t.Errorf("InitOrder == %s, want %s", got, want)
1138 type testImporter map[string]*Package
1140 func (m testImporter) Import(path string) (*Package, error) {
1141 if pkg := m[path]; pkg != nil {
1144 return nil, fmt.Errorf("package %q not found", path)
1147 func TestSelection(t *testing.T) {
1148 selections := make(map[*ast.SelectorExpr]*Selection)
1150 fset := token.NewFileSet()
1151 imports := make(testImporter)
1152 conf := Config{Importer: imports}
1153 makePkg := func(path, src string) {
1154 f, err := parser.ParseFile(fset, path+".go", src, 0)
1158 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
1196 // qualified identifiers
1230 // method expressions
1237 wantOut := map[string][2]string{
1238 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1240 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1241 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1242 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1243 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1244 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1245 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1246 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1247 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1249 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1250 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1251 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1252 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1253 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1254 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1255 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1256 "C{}.g": {"method (main.C) g()", ".[0]"},
1257 "new(C).g": {"method (*main.C) g()", "->[0]"},
1258 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1260 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1261 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1262 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1263 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1266 makePkg("lib", libSrc)
1267 makePkg("main", mainSrc)
1269 for e, sel := range selections {
1270 _ = sel.String() // assertion: must not panic
1272 start := fset.Position(e.Pos()).Offset
1273 end := fset.Position(e.End()).Offset
1274 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1282 fmt.Sprintf("%s%v", direct, sel.Index()),
1284 want := wantOut[syntax]
1286 t.Errorf("%s: got %q; want %q", syntax, got, want)
1288 delete(wantOut, syntax)
1290 // We must explicitly assert properties of the
1291 // Signature's receiver since it doesn't participate
1292 // in Identical() or String().
1293 sig, _ := sel.Type().(*Signature)
1294 if sel.Kind() == MethodVal {
1295 got := sig.Recv().Type()
1297 if !Identical(got, want) {
1298 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1300 } else if sig != nil && sig.Recv() != nil {
1301 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1304 // Assert that all wantOut entries were used exactly once.
1305 for syntax := range wantOut {
1306 t.Errorf("no ast.Selection found with syntax %q", syntax)
1310 func TestIssue8518(t *testing.T) {
1311 fset := token.NewFileSet()
1312 imports := make(testImporter)
1314 Error: func(err error) { t.Log(err) }, // don't exit after first error
1317 makePkg := func(path, src string) {
1318 f, err := parser.ParseFile(fset, path, src, 0)
1322 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1330 const C2 = missing.C
1340 makePkg("a", libSrc)
1341 makePkg("main", mainSrc) // don't crash when type-checking this package
1344 func TestLookupFieldOrMethod(t *testing.T) {
1345 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1346 // addressable value, and x for a non-addressable value (even though a variable
1347 // for ease of test case writing).
1349 // Should be kept in sync with TestMethodSet.
1350 var tests = []struct {
1357 {"var x T; type T struct{}", false, nil, false},
1358 {"var x T; type T struct{ f int }", true, []int{0}, false},
1359 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1362 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1363 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1364 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1365 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1368 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1369 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1371 // outside methodset
1372 // (*T).f method exists, but value of type T is not addressable
1373 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1376 for _, test := range tests {
1377 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1379 t.Errorf("%s: incorrect test case: %s", test.src, err)
1383 obj := pkg.Scope().Lookup("a")
1385 if obj = pkg.Scope().Lookup("x"); obj == nil {
1386 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1391 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1392 if (f != nil) != test.found {
1394 t.Errorf("%s: got no object; want one", test.src)
1396 t.Errorf("%s: got object = %v; want none", test.src, f)
1399 if !sameSlice(index, test.index) {
1400 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1402 if indirect != test.indirect {
1403 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1408 func sameSlice(a, b []int) bool {
1409 if len(a) != len(b) {
1412 for i, x := range a {
1420 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1421 // the correct result at various positions with the source.
1422 func TestScopeLookupParent(t *testing.T) {
1423 fset := token.NewFileSet()
1424 imports := make(testImporter)
1425 conf := Config{Importer: imports}
1426 mustParse := func(src string) *ast.File {
1427 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
1434 makePkg := func(path string, files ...*ast.File) {
1436 imports[path], err = conf.Check(path, fset, files, &info)
1442 makePkg("lib", mustParse("package lib; var X int"))
1443 // Each /*name=kind:line*/ comment makes the test look up the
1444 // name at that point and checks that it resolves to a decl of
1445 // the specified kind and line number. "undef" means undefined.
1447 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1458 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1459 type /*t=undef*/ t /*t=typename:14*/ *t
1460 print(Y) /*Y=var:10*/
1461 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1462 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1465 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
1468 switch y := i.(type) { /*y=undef*/
1469 case /*y=undef*/ int /*y=var:23*/ :
1470 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1471 default /*y=var:23*/:
1476 switch int := i.(type) {
1477 case /*int=typename:0*/ int /*int=var:31*/ :
1479 default /*int=var:31*/ :
1485 info.Uses = make(map[*ast.Ident]Object)
1486 f := mustParse(mainSrc)
1488 mainScope := imports["main"].Scope()
1489 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1490 for _, group := range f.Comments {
1491 for _, comment := range group.List {
1492 // Parse the assertion in the comment.
1493 m := rx.FindStringSubmatch(comment.Text)
1495 t.Errorf("%s: bad comment: %s",
1496 fset.Position(comment.Pos()), comment.Text)
1499 name, want := m[1], m[2]
1501 // Look up the name in the innermost enclosing scope.
1502 inner := mainScope.Innermost(comment.Pos())
1504 t.Errorf("%s: at %s: can't find innermost scope",
1505 fset.Position(comment.Pos()), comment.Text)
1509 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1510 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1511 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1514 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1515 fset.Position(comment.Pos()), comment.Text, name, got, want)
1520 // Check that for each referring identifier,
1521 // a lookup of its name on the innermost
1522 // enclosing scope returns the correct object.
1524 for id, wantObj := range info.Uses {
1525 inner := mainScope.Innermost(id.Pos())
1527 t.Errorf("%s: can't find innermost scope enclosing %q",
1528 fset.Position(id.Pos()), id.Name)
1532 // Exclude selectors and qualified identifiers---lexical
1533 // refs only. (Ideally, we'd see if the AST parent is a
1534 // SelectorExpr, but that requires PathEnclosingInterval
1535 // from golang.org/x/tools/go/ast/astutil.)
1540 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1541 if gotObj != wantObj {
1542 t.Errorf("%s: got %v, want %v",
1543 fset.Position(id.Pos()), gotObj, wantObj)
1549 // newDefined creates a new defined type named T with the given underlying type.
1550 // Helper function for use with TestIncompleteInterfaces only.
1551 func newDefined(underlying Type) *Named {
1552 tname := NewTypeName(token.NoPos, nil, "T", nil)
1553 return NewNamed(tname, underlying, nil)
1556 func TestConvertibleTo(t *testing.T) {
1557 for _, test := range []struct {
1561 {Typ[Int], Typ[Int], true},
1562 {Typ[Int], Typ[Float32], true},
1563 {newDefined(Typ[Int]), Typ[Int], true},
1564 {newDefined(new(Struct)), new(Struct), true},
1565 {newDefined(Typ[Int]), new(Struct), false},
1566 {Typ[UntypedInt], Typ[Int], true},
1567 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1568 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1569 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1570 // Untyped string values are not permitted by the spec, so the below
1571 // behavior is undefined.
1572 {Typ[UntypedString], Typ[String], true},
1574 if got := ConvertibleTo(test.v, test.t); got != test.want {
1575 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1580 func TestAssignableTo(t *testing.T) {
1581 for _, test := range []struct {
1585 {Typ[Int], Typ[Int], true},
1586 {Typ[Int], Typ[Float32], false},
1587 {newDefined(Typ[Int]), Typ[Int], false},
1588 {newDefined(new(Struct)), new(Struct), true},
1589 {Typ[UntypedBool], Typ[Bool], true},
1590 {Typ[UntypedString], Typ[Bool], false},
1591 // Neither untyped string nor untyped numeric assignments arise during
1592 // normal type checking, so the below behavior is technically undefined by
1594 {Typ[UntypedString], Typ[String], true},
1595 {Typ[UntypedInt], Typ[Int], true},
1597 if got := AssignableTo(test.v, test.t); got != test.want {
1598 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1603 func TestIdentical_issue15173(t *testing.T) {
1604 // Identical should allow nil arguments and be symmetric.
1605 for _, test := range []struct {
1609 {Typ[Int], Typ[Int], true},
1610 {Typ[Int], nil, false},
1611 {nil, Typ[Int], false},
1614 if got := Identical(test.x, test.y); got != test.want {
1615 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1620 func TestIssue15305(t *testing.T) {
1621 const src = "package p; func f() int16; var _ = f(undef)"
1622 fset := token.NewFileSet()
1623 f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
1628 Error: func(err error) {}, // allow errors
1631 Types: make(map[ast.Expr]TypeAndValue),
1633 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
1634 for e, tv := range info.Types {
1635 if _, ok := e.(*ast.CallExpr); ok {
1636 if tv.Type != Typ[Int16] {
1637 t.Errorf("CallExpr has type %v, want int16", tv.Type)
1642 t.Errorf("CallExpr has no type")
1645 // TestCompositeLitTypes verifies that Info.Types registers the correct
1646 // types for composite literal expressions and composite literal type
1648 func TestCompositeLitTypes(t *testing.T) {
1649 for _, test := range []struct {
1652 {`[16]byte{}`, `[16]byte`},
1653 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
1654 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
1655 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
1656 {`[]int{}`, `[]int`},
1657 {`map[string]bool{"foo": true}`, `map[string]bool`},
1658 {`struct{}{}`, `struct{}`},
1659 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
1661 fset := token.NewFileSet()
1662 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
1664 t.Fatalf("%s: %v", test.lit, err)
1668 Types: make(map[ast.Expr]TypeAndValue),
1670 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1671 t.Fatalf("%s: %v", test.lit, err)
1674 cmptype := func(x ast.Expr, want string) {
1675 tv, ok := info.Types[x]
1677 t.Errorf("%s: no Types entry found", test.lit)
1681 t.Errorf("%s: type is nil", test.lit)
1684 if got := tv.Type.String(); got != want {
1685 t.Errorf("%s: got %v, want %s", test.lit, got, want)
1689 // test type of composite literal expression
1690 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
1691 cmptype(rhs, test.typ)
1693 // test type of composite literal type expression
1694 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
1698 // TestObjectParents verifies that objects have parent scopes or not
1699 // as specified by the Object interface.
1700 func TestObjectParents(t *testing.T) {
1719 func f(x int) { y := x; print(y) }
1722 fset := token.NewFileSet()
1723 f, err := parser.ParseFile(fset, "src", src, 0)
1729 Defs: make(map[*ast.Ident]Object),
1731 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1735 for ident, obj := range info.Defs {
1737 // only package names and implicit vars have a nil object
1738 // (in this test we only need to handle the package name)
1739 if ident.Name != "p" {
1740 t.Errorf("%v has nil object", ident)
1745 // struct fields, type-associated and interface methods
1746 // have no parent scope
1748 switch obj := obj.(type) {
1754 if obj.Type().(*Signature).Recv() != nil { // method
1759 gotParent := obj.Parent() != nil
1761 case gotParent && !wantParent:
1762 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
1763 case !gotParent && wantParent:
1764 t.Errorf("%v: no parent found", ident)
1769 // TestFailedImport tests that we don't get follow-on errors
1770 // elsewhere in a package due to failing to import a package.
1771 func TestFailedImport(t *testing.T) {
1772 testenv.MustHaveGoBuild(t)
1777 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
1782 func f(x T) T { return foo.F(x) }
1784 fset := token.NewFileSet()
1785 f, err := parser.ParseFile(fset, "src", src, 0)
1789 files := []*ast.File{f}
1791 // type-check using all possible importers
1792 for _, compiler := range []string{"gc", "gccgo", "source"} {
1795 Error: func(err error) {
1796 // we should only see the import error
1797 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
1798 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
1802 Importer: importer.For(compiler, nil),
1806 Uses: make(map[*ast.Ident]Object),
1808 pkg, _ := conf.Check("p", fset, files, info)
1810 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
1814 imports := pkg.Imports()
1815 if len(imports) != 1 {
1816 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
1820 if imp.Name() != "foo" {
1821 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
1825 // verify that all uses of foo refer to the imported package foo (imp)
1826 for ident, obj := range info.Uses {
1827 if ident.Name == "foo" {
1828 if obj, ok := obj.(*PkgName); ok {
1829 if obj.Imported() != imp {
1830 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
1833 t.Errorf("%s resolved to %v; want package name", ident, obj)
1840 func TestInstantiate(t *testing.T) {
1841 // eventually we like more tests but this is a start
1842 const src = genericPkg + "p; type T[P any] *T[P]"
1843 pkg, err := pkgFor(".", src, nil)
1848 // type T should have one type parameter
1849 T := pkg.Scope().Lookup("T").Type().(*Named)
1850 if n := T.TParams().Len(); n != 1 {
1851 t.Fatalf("expected 1 type parameter; found %d", n)
1854 // instantiation should succeed (no endless recursion)
1855 // even with a nil *Checker
1857 res := check.Instantiate(token.NoPos, T, []Type{Typ[Int]}, nil, false)
1859 // instantiated type should point to itself
1860 if p := res.Underlying().(*Pointer).Elem(); p != res {
1861 t.Fatalf("unexpected result type: %s points to %s", res, p)
1865 func TestInstanceIdentity(t *testing.T) {
1866 imports := make(testImporter)
1867 conf := Config{Importer: imports}
1868 makePkg := func(src string) {
1869 fset := token.NewFileSet()
1870 f, err := parser.ParseFile(fset, "", src, 0)
1875 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
1881 makePkg(genericPkg + `lib; type T[P any] struct{}`)
1882 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
1883 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
1884 a := imports["generic_a"].Scope().Lookup("A")
1885 b := imports["generic_b"].Scope().Lookup("B")
1886 if !Identical(a.Type(), b.Type()) {
1887 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())