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.
13 "go/internal/typeparams"
25 // pkgFor parses and type checks the package specified by path and source,
26 // populating info if provided.
28 // If source begins with "package generic_" and type parameters are enabled,
29 // generic code is permitted.
30 func pkgFor(path, source string, info *Info) (*Package, error) {
31 fset := token.NewFileSet()
32 mode := modeForSource(source)
33 f, err := parser.ParseFile(fset, path, source, mode)
37 conf := Config{Importer: importer.Default()}
38 return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
41 func mustTypecheck(t *testing.T, path, source string, info *Info) string {
42 pkg, err := pkgFor(path, source, info)
46 name = "package " + pkg.Name()
48 t.Fatalf("%s: didn't type-check (%s)", name, err)
53 // genericPkg is a prefix for packages that should be type checked with
55 const genericPkg = "package generic_"
57 func modeForSource(src string) parser.Mode {
58 if !strings.HasPrefix(src, genericPkg) {
59 return typeparams.DisallowParsing
64 func mayTypecheck(t *testing.T, path, source string, info *Info) (string, error) {
65 fset := token.NewFileSet()
66 mode := modeForSource(source)
67 f, err := parser.ParseFile(fset, path, source, mode)
68 if f == nil { // ignore errors unless f is nil
69 t.Fatalf("%s: unable to parse: %s", path, err)
72 Error: func(err error) {},
73 Importer: importer.Default(),
75 pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
76 return pkg.Name(), err
79 func TestValuesInfo(t *testing.T) {
80 var tests = []struct {
82 expr string // constant expression
83 typ string // constant type
84 val string // constant value
86 {`package a0; const _ = false`, `false`, `untyped bool`, `false`},
87 {`package a1; const _ = 0`, `0`, `untyped int`, `0`},
88 {`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
89 {`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
90 {`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
91 {`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
93 {`package b0; var _ = false`, `false`, `bool`, `false`},
94 {`package b1; var _ = 0`, `0`, `int`, `0`},
95 {`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
96 {`package b3; var _ = 0.`, `0.`, `float64`, `0`},
97 {`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
98 {`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
100 {`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
101 {`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
102 {`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
104 {`package c1a; var _ = int(0)`, `0`, `int`, `0`},
105 {`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
106 {`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
108 {`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
109 {`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
110 {`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
112 {`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
113 {`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
114 {`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
116 {`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
117 {`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
118 {`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
120 {`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
121 {`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
122 {`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
123 {`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
124 {`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
125 {`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
126 {`package c5g; var s uint; var _ = string(1 << s)`, `1 << s`, `untyped int`, ``},
128 {`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
129 {`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
130 {`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
131 {`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
133 {`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
134 {`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
135 {`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
136 {`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
137 {`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
138 {`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
139 {`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
140 {`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
142 {`package f0 ; var _ float32 = 1e-200`, `1e-200`, `float32`, `0`},
143 {`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
144 {`package f2a; var _ float64 = 1e-2000`, `1e-2000`, `float64`, `0`},
145 {`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
146 {`package f2b; var _ = 1e-2000`, `1e-2000`, `float64`, `0`},
147 {`package f3b; var _ = -1e-2000`, `-1e-2000`, `float64`, `0`},
148 {`package f4 ; var _ complex64 = 1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
149 {`package f5 ; var _ complex64 = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
150 {`package f6a; var _ complex128 = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
151 {`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
152 {`package f6b; var _ = 1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
153 {`package f7b; var _ = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
155 {`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
156 {`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`}, // issue #48422
159 for _, test := range tests {
161 Types: make(map[ast.Expr]TypeAndValue),
163 name := mustTypecheck(t, "ValuesInfo", test.src, &info)
165 // look for expression
167 for e := range info.Types {
168 if ExprString(e) == test.expr {
174 t.Errorf("package %s: no expression found for %s", name, test.expr)
177 tv := info.Types[expr]
179 // check that type is correct
180 if got := tv.Type.String(); got != test.typ {
181 t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
185 // if we have a constant, check that value is correct
187 if got := tv.Value.ExactString(); got != test.val {
188 t.Errorf("package %s: got value %s; want %s", name, got, test.val)
192 t.Errorf("package %s: no constant found; want %s", name, test.val)
198 func TestTypesInfo(t *testing.T) {
199 // Test sources that are not expected to typecheck must start with the broken prefix.
200 const broken = "package broken_"
202 var tests = []struct {
204 expr string // expression
205 typ string // value type
207 // single-valued expressions of untyped constants
208 {`package b0; var x interface{} = false`, `false`, `bool`},
209 {`package b1; var x interface{} = 0`, `0`, `int`},
210 {`package b2; var x interface{} = 0.`, `0.`, `float64`},
211 {`package b3; var x interface{} = 0i`, `0i`, `complex128`},
212 {`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
215 {`package n0; var _ *int = nil`, `nil`, `untyped nil`},
216 {`package n1; var _ func() = nil`, `nil`, `untyped nil`},
217 {`package n2; var _ []byte = nil`, `nil`, `untyped nil`},
218 {`package n3; var _ map[int]int = nil`, `nil`, `untyped nil`},
219 {`package n4; var _ chan int = nil`, `nil`, `untyped nil`},
220 {`package n5; var _ interface{} = nil`, `nil`, `untyped nil`},
221 {`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `untyped nil`},
223 {`package n10; var (x *int; _ = x == nil)`, `nil`, `untyped nil`},
224 {`package n11; var (x func(); _ = x == nil)`, `nil`, `untyped nil`},
225 {`package n12; var (x []byte; _ = x == nil)`, `nil`, `untyped nil`},
226 {`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `untyped nil`},
227 {`package n14; var (x chan int; _ = x == nil)`, `nil`, `untyped nil`},
228 {`package n15; var (x interface{}; _ = x == nil)`, `nil`, `untyped nil`},
229 {`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `untyped nil`},
231 {`package n20; var _ = (*int)(nil)`, `nil`, `untyped nil`},
232 {`package n21; var _ = (func())(nil)`, `nil`, `untyped nil`},
233 {`package n22; var _ = ([]byte)(nil)`, `nil`, `untyped nil`},
234 {`package n23; var _ = (map[int]int)(nil)`, `nil`, `untyped nil`},
235 {`package n24; var _ = (chan int)(nil)`, `nil`, `untyped nil`},
236 {`package n25; var _ = (interface{})(nil)`, `nil`, `untyped nil`},
237 {`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `untyped nil`},
239 {`package n30; func f(*int) { f(nil) }`, `nil`, `untyped nil`},
240 {`package n31; func f(func()) { f(nil) }`, `nil`, `untyped nil`},
241 {`package n32; func f([]byte) { f(nil) }`, `nil`, `untyped nil`},
242 {`package n33; func f(map[int]int) { f(nil) }`, `nil`, `untyped nil`},
243 {`package n34; func f(chan int) { f(nil) }`, `nil`, `untyped nil`},
244 {`package n35; func f(interface{}) { f(nil) }`, `nil`, `untyped nil`},
245 {`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `untyped nil`},
247 // comma-ok expressions
248 {`package p0; var x interface{}; var _, _ = x.(int)`,
252 {`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
256 {`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
258 `(complex128, p2a.mybool)`,
260 {`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
262 `(complex128, bool)`,
264 {`package p3; var c chan string; var _, _ = <-c`,
270 {`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
274 {`package issue6796_b; var c chan string; var _, _ = (<-c)`,
278 {`package issue6796_c; var c chan string; var _, _ = (<-c)`,
282 {`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
286 {`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
292 {`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
296 {`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
300 {`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
304 {`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
308 {`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
312 {`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
318 {`package issue28277_a; func f(...int)`,
322 {`package issue28277_b; func f(a, b int, c ...[]struct{})`,
328 {`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
329 {`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `uint`}, // issue 47410: should be untyped float
330 {`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
331 {`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
332 {`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
333 {`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
334 {`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
335 {`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
336 {`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
337 {`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
339 // tests for broken code that doesn't parse or type-check
340 {broken + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
341 {broken + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
342 {broken + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a; f: b;}}`, `b`, `string`},
343 {broken + `x3; var x = panic("");`, `panic`, `func(interface{})`},
344 {`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
345 {broken + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string][-1]int`},
347 // parameterized functions
348 {genericPkg + `p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T interface{}](T)`},
349 {genericPkg + `p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
350 {genericPkg + `p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
351 {genericPkg + `p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
352 {genericPkg + `p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T interface{}](T)`},
353 {genericPkg + `p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
356 {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
357 {genericPkg + `t1; type t[P any] int; var _ t[int]`, `t`, `generic_t1.t[P interface{}]`},
358 {genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[P interface{}]`},
359 {genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[P, Q interface{}]`},
361 // TODO (rFindley): compare with types2, which resolves the type broken_t4.t[P₁, Q₂ interface{m()}] here
362 {broken + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t`},
364 // instantiated types must be sanitized
365 {genericPkg + `g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `generic_g0.t[int]`},
368 {genericPkg + `issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
371 {`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
374 for _, test := range tests {
375 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
377 if strings.HasPrefix(test.src, broken) {
379 name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
381 t.Errorf("package %s: expected to fail but passed", name)
385 name = mustTypecheck(t, "TypesInfo", test.src, &info)
388 // look for expression type
390 for e, tv := range info.Types {
391 if ExprString(e) == test.expr {
397 t.Errorf("package %s: no type found for %s", name, test.expr)
401 // check that type is correct
402 if got := typ.String(); got != test.typ {
403 t.Errorf("package %s: got %s; want %s", name, got, test.typ)
408 func TestInstanceInfo(t *testing.T) {
409 var tests = []struct {
415 {`package p0; func f[T any](T) {}; func _() { f(42) }`,
420 {`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
425 {`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
427 []string{`complex128`},
428 `func(...complex128) complex128`,
430 {`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
432 []string{`float64`, `string`, `byte`},
433 `func(float64, *string, []byte)`,
435 {`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
437 []string{`float64`, `byte`},
438 `func(float64, *byte, ...[]byte)`,
441 {`package s1; func f[T any, P interface{~*T}](x T) {}; func _(x string) { f(x) }`,
443 []string{`string`, `*string`},
446 {`package s2; func f[T any, P interface{~*T}](x []T) {}; func _(x []int) { f(x) }`,
448 []string{`int`, `*int`},
451 {`package s3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
453 []string{`int`, `chan<- int`},
456 {`package s4; type C[T any] interface{~chan<- T}; func f[T any, P C[T], Q C[[]*P]](x []T) {}; func _(x []int) { f(x) }`,
458 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
462 {`package t1; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = f[string] }`,
464 []string{`string`, `*string`},
467 {`package t2; func f[T any, P interface{~*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
469 []string{`string`, `*string`},
472 {`package t3; type C[T any] interface{~chan<- T}; func f[T any, P C[T]]() []T { return nil }; func _() { _ = f[int] }`,
474 []string{`int`, `chan<- int`},
477 {`package t4; type C[T any] interface{~chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
479 []string{`int`, `chan<- int`, `chan<- []*chan<- int`},
482 {`package i0; import "lib"; func _() { lib.F(42) }`,
487 {`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
492 {`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
497 {`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
502 {`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
504 []string{`[]int`, `int`},
505 `struct{x []int; y int}`,
507 {`package type4; import "lib"; var _ lib.T[int]`,
514 for _, test := range tests {
515 const lib = `package lib
522 imports := make(testImporter)
523 conf := Config{Importer: imports}
524 instances := make(map[*ast.Ident]Instance)
525 uses := make(map[*ast.Ident]Object)
526 makePkg := func(src string) *Package {
527 f, err := parser.ParseFile(fset, "p.go", src, 0)
531 pkg, err := conf.Check("", fset, []*ast.File{f}, &Info{Instances: instances, Uses: uses})
535 imports[pkg.Name()] = pkg
539 pkg := makePkg(test.src)
541 // look for instance information
544 for ident, inst := range instances {
545 if ExprString(ident) == test.name {
546 for i := 0; i < inst.TypeArgs.Len(); i++ {
547 targs = append(targs, inst.TypeArgs.At(i))
551 // Check that we can find the corresponding parameterized type.
552 ptype := uses[ident].Type()
553 lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
554 if lister == nil || lister.TypeParams().Len() == 0 {
555 t.Errorf("package %s: info.Types[%v] = %v, want parameterized type", pkg.Name(), ident, ptype)
559 // Verify the invariant that re-instantiating the generic type with
560 // TypeArgs results in an equivalent type.
561 inst2, err := Instantiate(nil, ptype, targs, true)
563 t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
565 if !Identical(inst.Type, inst2) {
566 t.Errorf("%v and %v are not identical", inst.Type, inst2)
572 t.Errorf("package %s: no instance information found for %s", pkg.Name(), test.name)
576 // check that type arguments are correct
577 if len(targs) != len(test.targs) {
578 t.Errorf("package %s: got %d type arguments; want %d", pkg.Name(), len(targs), len(test.targs))
581 for i, targ := range targs {
582 if got := targ.String(); got != test.targs[i] {
583 t.Errorf("package %s, %d. type argument: got %s; want %s", pkg.Name(), i, got, test.targs[i])
588 // check that the types match
589 if got := typ.Underlying().String(); got != test.typ {
590 t.Errorf("package %s: got %s; want %s", pkg.Name(), got, test.typ)
595 func TestDefsInfo(t *testing.T) {
596 var tests = []struct {
601 {`package p0; const x = 42`, `x`, `const p0.x untyped int`},
602 {`package p1; const x int = 42`, `x`, `const p1.x int`},
603 {`package p2; var x int`, `x`, `var p2.x int`},
604 {`package p3; type x int`, `x`, `type p3.x int`},
605 {`package p4; func f()`, `f`, `func p4.f()`},
606 {`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
609 for _, test := range tests {
611 Defs: make(map[*ast.Ident]Object),
613 name := mustTypecheck(t, "DefsInfo", test.src, &info)
617 for id, obj := range info.Defs {
618 if id.Name == test.obj {
624 t.Errorf("package %s: %s not found", name, test.obj)
628 if got := def.String(); got != test.want {
629 t.Errorf("package %s: got %s; want %s", name, got, test.want)
634 func TestUsesInfo(t *testing.T) {
635 var tests = []struct {
640 {`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
641 {`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
642 {`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
643 {`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
644 {`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
647 for _, test := range tests {
649 Uses: make(map[*ast.Ident]Object),
651 name := mustTypecheck(t, "UsesInfo", test.src, &info)
655 for id, obj := range info.Uses {
656 if id.Name == test.obj {
662 t.Errorf("package %s: %s not found", name, test.obj)
666 if got := use.String(); got != test.want {
667 t.Errorf("package %s: got %s; want %s", name, got, test.want)
672 func TestImplicitsInfo(t *testing.T) {
673 testenv.MustHaveGoBuild(t)
675 var tests = []struct {
679 {`package p2; import . "fmt"; var _ = Println`, ""}, // no Implicits entry
680 {`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
681 {`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
683 {`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
684 {`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
685 {`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
686 {`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
688 {`package p7; func f(x int) {}`, ""}, // no Implicits entry
689 {`package p8; func f(int) {}`, "field: var int"},
690 {`package p9; func f() (complex64) { return 0 }`, "field: var complex64"},
691 {`package p10; type T struct{}; func (*T) f() {}`, "field: var *p10.T"},
694 for _, test := range tests {
696 Implicits: make(map[ast.Node]Object),
698 name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
700 // the test cases expect at most one Implicits entry
701 if len(info.Implicits) > 1 {
702 t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
706 // extract Implicits entry, if any
708 for n, obj := range info.Implicits {
709 switch x := n.(type) {
710 case *ast.ImportSpec:
712 case *ast.CaseClause:
717 t.Fatalf("package %s: unexpected %T", name, x)
719 got += ": " + obj.String()
723 if got != test.want {
724 t.Errorf("package %s: got %q; want %q", name, got, test.want)
729 func predString(tv TypeAndValue) string {
731 pred := func(b bool, s string) {
734 buf.WriteString(", ")
740 pred(tv.IsVoid(), "void")
741 pred(tv.IsType(), "type")
742 pred(tv.IsBuiltin(), "builtin")
743 pred(tv.IsValue() && tv.Value != nil, "const")
744 pred(tv.IsValue() && tv.Value == nil, "value")
745 pred(tv.IsNil(), "nil")
746 pred(tv.Addressable(), "addressable")
747 pred(tv.Assignable(), "assignable")
748 pred(tv.HasOk(), "hasOk")
756 func TestPredicatesInfo(t *testing.T) {
757 testenv.MustHaveGoBuild(t)
759 var tests = []struct {
765 {`package n0; func f() { f() }`, `f()`, `void`},
768 {`package t0; type _ int`, `int`, `type`},
769 {`package t1; type _ []int`, `[]int`, `type`},
770 {`package t2; type _ func()`, `func()`, `type`},
771 {`package t3; type _ func(int)`, `int`, `type`},
772 {`package t3; type _ func(...int)`, `...int`, `type`},
775 {`package b0; var _ = len("")`, `len`, `builtin`},
776 {`package b1; var _ = (len)("")`, `(len)`, `builtin`},
779 {`package c0; var _ = 42`, `42`, `const`},
780 {`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
781 {`package c2; const (i = 1i; _ = i)`, `i`, `const`},
784 {`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
785 {`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
786 {`package v2; var _ = func(){}`, `(func() literal)`, `value`},
787 {`package v4; func f() { _ = f }`, `f`, `value`},
788 {`package v3; var _ *int = nil`, `nil`, `value, nil`},
789 {`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
791 // addressable (and thus assignable) operands
792 {`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
793 {`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
794 {`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
795 {`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
796 {`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
797 {`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
798 {`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
799 {`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
800 // composite literals are not addressable
802 // assignable but not addressable values
803 {`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
804 {`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
807 {`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
808 {`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
811 // - package names are collected in the Uses map
812 // - identifiers being declared are collected in the Defs map
813 {`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
814 {`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
815 {`package m2; const c = 0`, `c`, `<missing>`},
816 {`package m3; type T int`, `T`, `<missing>`},
817 {`package m4; var v int`, `v`, `<missing>`},
818 {`package m5; func f() {}`, `f`, `<missing>`},
819 {`package m6; func _(x int) {}`, `x`, `<missing>`},
820 {`package m6; func _()(x int) { return }`, `x`, `<missing>`},
821 {`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
824 for _, test := range tests {
825 info := Info{Types: make(map[ast.Expr]TypeAndValue)}
826 name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
828 // look for expression predicates
830 for e, tv := range info.Types {
831 //println(name, ExprString(e))
832 if ExprString(e) == test.expr {
838 if got != test.pred {
839 t.Errorf("package %s: got %s; want %s", name, got, test.pred)
844 func TestScopesInfo(t *testing.T) {
845 testenv.MustHaveGoBuild(t)
847 var tests = []struct {
849 scopes []string // list of scope descriptors of the form kind:varlist
851 {`package p0`, []string{
854 {`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
857 {`package p2; func _() {}`, []string{
860 {`package p3; func _(x, y int) {}`, []string{
863 {`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
864 "file:", "func:x y z", // redeclaration of x
866 {`package p5; func _(x, y int) (u, _ int) { return }`, []string{
867 "file:", "func:u x y",
869 {`package p6; func _() { { var x int; _ = x } }`, []string{
870 "file:", "func:", "block:x",
872 {`package p7; func _() { if true {} }`, []string{
873 "file:", "func:", "if:", "block:",
875 {`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
876 "file:", "func:", "if:x", "block:y",
878 {`package p9; func _() { switch x := 0; x {} }`, []string{
879 "file:", "func:", "switch:x",
881 {`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
882 "file:", "func:", "switch:x", "case:y", "case:",
884 {`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
885 "file:", "func:t", "type switch:",
887 {`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
888 "file:", "func:t", "type switch:t",
890 {`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
891 "file:", "func:t", "type switch:", "case:x", // x implicitly declared
893 {`package p14; func _() { select{} }`, []string{
896 {`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
897 "file:", "func:c", "comm:",
899 {`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
900 "file:", "func:c", "comm:i x",
902 {`package p17; func _() { for{} }`, []string{
903 "file:", "func:", "for:", "block:",
905 {`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
906 "file:", "func:n", "for:i", "block:",
908 {`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
909 "file:", "func:a", "range:i", "block:",
911 {`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
912 "file:", "func:a", "range:i x", "block:",
916 for _, test := range tests {
917 info := Info{Scopes: make(map[ast.Node]*Scope)}
918 name := mustTypecheck(t, "ScopesInfo", test.src, &info)
920 // number of scopes must match
921 if len(info.Scopes) != len(test.scopes) {
922 t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
925 // scope descriptions must match
926 for node, scope := range info.Scopes {
927 kind := "<unknown node kind>"
937 case *ast.SwitchStmt:
939 case *ast.TypeSwitchStmt:
941 case *ast.CaseClause:
943 case *ast.CommClause:
951 // look for matching scope description
952 desc := kind + ":" + strings.Join(scope.Names(), " ")
954 for _, d := range test.scopes {
961 t.Errorf("package %s: no matching scope found for %s", name, desc)
967 func TestInitOrderInfo(t *testing.T) {
968 var tests = []struct {
972 {`package p0; var (x = 1; y = x)`, []string{
975 {`package p1; var (a = 1; b = 2; c = 3)`, []string{
976 "a = 1", "b = 2", "c = 3",
978 {`package p2; var (a, b, c = 1, 2, 3)`, []string{
979 "a = 1", "b = 2", "c = 3",
981 {`package p3; var _ = f(); func f() int { return 1 }`, []string{
982 "_ = f()", // blank var
984 {`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
985 "a = 0", "z = 0", "y = z", "x = y",
987 {`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
988 "a, _ = m[0]", // blank var
990 {`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
991 "z = 0", "a, b = f()",
993 {`package p7; var (a = func() int { return b }(); b = 1)`, []string{
994 "b = 1", "a = (func() int literal)()",
996 {`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
997 "c = 1", "a, b = (func() (_, _ int) literal)()",
999 {`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
1002 {`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
1003 "a = 0", "b = 0", "c = 0", "d = c + b",
1005 {`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
1006 "c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
1008 // emit an initializer for n:1 initializations only once (not for each node
1009 // on the lhs which may appear in different order in the dependency graph)
1010 {`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
1011 "b = 0", "x, y = m[0]", "a = x",
1013 // test case from spec section on package initialization
1027 "d = 3", "b = f()", "c = f()", "a = c + b",
1029 // test case for issue 7131
1033 func next() int { counter++; return counter }
1036 func makeOrder() []int { return []int{f, b, d, e, c, a} }
1039 var b, c = next(), next()
1040 var d, e, f = next(), next(), next()
1042 "a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
1044 // test case for issue 10709
1054 func (T) m() int { return 0 }
1056 func makeT(n int) T {
1062 "t = makeT(0)", "v = t.m()",
1064 // test case for issue 10709: same as test before, but variable decls swapped
1074 func (T) m() int { return 0 }
1076 func makeT(n int) T {
1082 "t = makeT(0)", "v = t.m()",
1084 // another candidate possibly causing problems with issue 10709
1089 func f1() int { return g1() }
1090 func g1() int { f1(); return x1 }
1096 func f2() int { return g2() }
1097 func g2() int { return x2 }
1099 var x2 = 0`, []string{
1100 "x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
1104 for _, test := range tests {
1106 name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
1108 // number of initializers must match
1109 if len(info.InitOrder) != len(test.inits) {
1110 t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
1114 // initializers must match
1115 for i, want := range test.inits {
1116 got := info.InitOrder[i].String()
1118 t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
1125 func TestMultiFileInitOrder(t *testing.T) {
1126 fset := token.NewFileSet()
1127 mustParse := func(src string) *ast.File {
1128 f, err := parser.ParseFile(fset, "main", src, 0)
1135 fileA := mustParse(`package main; var a = 1`)
1136 fileB := mustParse(`package main; var b = 2`)
1138 // The initialization order must not depend on the parse
1139 // order of the files, only on the presentation order to
1140 // the type-checker.
1141 for _, test := range []struct {
1145 {[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
1146 {[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
1149 if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
1152 if got := fmt.Sprint(info.InitOrder); got != test.want {
1153 t.Fatalf("got %s; want %s", got, test.want)
1158 func TestFiles(t *testing.T) {
1159 var sources = []string{
1160 "package p; type T struct{}; func (T) m1() {}",
1161 "package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
1162 "package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
1167 fset := token.NewFileSet()
1168 pkg := NewPackage("p", "p")
1170 check := NewChecker(&conf, fset, pkg, &info)
1172 for i, src := range sources {
1173 filename := fmt.Sprintf("sources%d", i)
1174 f, err := parser.ParseFile(fset, filename, src, 0)
1178 if err := check.Files([]*ast.File{f}); err != nil {
1183 // check InitOrder is [x y]
1185 for _, init := range info.InitOrder {
1186 for _, v := range init.Lhs {
1187 vars = append(vars, v.Name())
1190 if got, want := fmt.Sprint(vars), "[x y]"; got != want {
1191 t.Errorf("InitOrder == %s, want %s", got, want)
1195 type testImporter map[string]*Package
1197 func (m testImporter) Import(path string) (*Package, error) {
1198 if pkg := m[path]; pkg != nil {
1201 return nil, fmt.Errorf("package %q not found", path)
1204 func TestSelection(t *testing.T) {
1205 selections := make(map[*ast.SelectorExpr]*Selection)
1207 fset := token.NewFileSet()
1208 imports := make(testImporter)
1209 conf := Config{Importer: imports}
1210 makePkg := func(path, src string) {
1211 f, err := parser.ParseFile(fset, path+".go", src, 0)
1215 pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
1253 // qualified identifiers
1287 // method expressions
1294 wantOut := map[string][2]string{
1295 "lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
1297 "A{}.B": {"field (main.A) B *main.B", ".[0]"},
1298 "new(A).B": {"field (*main.A) B *main.B", "->[0]"},
1299 "A{}.C": {"field (main.A) C main.C", ".[1]"},
1300 "new(A).C": {"field (*main.A) C main.C", "->[1]"},
1301 "A{}.b": {"field (main.A) b int", "->[0 0]"},
1302 "new(A).b": {"field (*main.A) b int", "->[0 0]"},
1303 "A{}.c": {"field (main.A) c int", ".[1 0]"},
1304 "new(A).c": {"field (*main.A) c int", "->[1 0]"},
1306 "A{}.f": {"method (main.A) f(int)", "->[0 0]"},
1307 "new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
1308 "A{}.g": {"method (main.A) g()", ".[1 0]"},
1309 "new(A).g": {"method (*main.A) g()", "->[1 0]"},
1310 "new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
1311 "B{}.f": {"method (main.B) f(int)", ".[0]"},
1312 "new(B).f": {"method (*main.B) f(int)", "->[0]"},
1313 "C{}.g": {"method (main.C) g()", ".[0]"},
1314 "new(C).g": {"method (*main.C) g()", "->[0]"},
1315 "new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
1317 "A.f": {"method expr (main.A) f(main.A, int)", "->[0 0]"},
1318 "(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
1319 "B.f": {"method expr (main.B) f(main.B, int)", ".[0]"},
1320 "(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
1323 makePkg("lib", libSrc)
1324 makePkg("main", mainSrc)
1326 for e, sel := range selections {
1327 _ = sel.String() // assertion: must not panic
1329 start := fset.Position(e.Pos()).Offset
1330 end := fset.Position(e.End()).Offset
1331 syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
1339 fmt.Sprintf("%s%v", direct, sel.Index()),
1341 want := wantOut[syntax]
1343 t.Errorf("%s: got %q; want %q", syntax, got, want)
1345 delete(wantOut, syntax)
1347 // We must explicitly assert properties of the
1348 // Signature's receiver since it doesn't participate
1349 // in Identical() or String().
1350 sig, _ := sel.Type().(*Signature)
1351 if sel.Kind() == MethodVal {
1352 got := sig.Recv().Type()
1354 if !Identical(got, want) {
1355 t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
1357 } else if sig != nil && sig.Recv() != nil {
1358 t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
1361 // Assert that all wantOut entries were used exactly once.
1362 for syntax := range wantOut {
1363 t.Errorf("no ast.Selection found with syntax %q", syntax)
1367 func TestIssue8518(t *testing.T) {
1368 fset := token.NewFileSet()
1369 imports := make(testImporter)
1371 Error: func(err error) { t.Log(err) }, // don't exit after first error
1374 makePkg := func(path, src string) {
1375 f, err := parser.ParseFile(fset, path, src, 0)
1379 pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
1387 const C2 = missing.C
1397 makePkg("a", libSrc)
1398 makePkg("main", mainSrc) // don't crash when type-checking this package
1401 func TestLookupFieldOrMethod(t *testing.T) {
1402 // Test cases assume a lookup of the form a.f or x.f, where a stands for an
1403 // addressable value, and x for a non-addressable value (even though a variable
1404 // for ease of test case writing).
1406 // Should be kept in sync with TestMethodSet.
1407 var tests = []struct {
1414 {"var x T; type T struct{}", false, nil, false},
1415 {"var x T; type T struct{ f int }", true, []int{0}, false},
1416 {"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
1419 {"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
1420 {"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
1421 {"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
1422 {"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
1425 {"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
1426 {"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
1428 // outside methodset
1429 // (*T).f method exists, but value of type T is not addressable
1430 {"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
1433 for _, test := range tests {
1434 pkg, err := pkgFor("test", "package p;"+test.src, nil)
1436 t.Errorf("%s: incorrect test case: %s", test.src, err)
1440 obj := pkg.Scope().Lookup("a")
1442 if obj = pkg.Scope().Lookup("x"); obj == nil {
1443 t.Errorf("%s: incorrect test case - no object a or x", test.src)
1448 f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
1449 if (f != nil) != test.found {
1451 t.Errorf("%s: got no object; want one", test.src)
1453 t.Errorf("%s: got object = %v; want none", test.src, f)
1456 if !sameSlice(index, test.index) {
1457 t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
1459 if indirect != test.indirect {
1460 t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
1465 func sameSlice(a, b []int) bool {
1466 if len(a) != len(b) {
1469 for i, x := range a {
1477 // TestScopeLookupParent ensures that (*Scope).LookupParent returns
1478 // the correct result at various positions with the source.
1479 func TestScopeLookupParent(t *testing.T) {
1480 fset := token.NewFileSet()
1481 imports := make(testImporter)
1482 conf := Config{Importer: imports}
1483 mustParse := func(src string) *ast.File {
1484 f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
1491 makePkg := func(path string, files ...*ast.File) {
1493 imports[path], err = conf.Check(path, fset, files, &info)
1499 makePkg("lib", mustParse("package lib; var X int"))
1500 // Each /*name=kind:line*/ comment makes the test look up the
1501 // name at that point and checks that it resolves to a decl of
1502 // the specified kind and line number. "undef" means undefined.
1504 /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
1515 const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
1516 type /*t=undef*/ t /*t=typename:14*/ *t
1517 print(Y) /*Y=var:10*/
1518 x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
1519 var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
1522 for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
1525 switch y := i.(type) { /*y=undef*/
1526 case /*y=undef*/ int /*y=var:23*/ :
1527 case float32, /*y=undef*/ float64 /*y=var:23*/ :
1528 default /*y=var:23*/:
1533 switch int := i.(type) {
1534 case /*int=typename:0*/ int /*int=var:31*/ :
1536 default /*int=var:31*/ :
1542 info.Uses = make(map[*ast.Ident]Object)
1543 f := mustParse(mainSrc)
1545 mainScope := imports["main"].Scope()
1546 rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
1547 for _, group := range f.Comments {
1548 for _, comment := range group.List {
1549 // Parse the assertion in the comment.
1550 m := rx.FindStringSubmatch(comment.Text)
1552 t.Errorf("%s: bad comment: %s",
1553 fset.Position(comment.Pos()), comment.Text)
1556 name, want := m[1], m[2]
1558 // Look up the name in the innermost enclosing scope.
1559 inner := mainScope.Innermost(comment.Pos())
1561 t.Errorf("%s: at %s: can't find innermost scope",
1562 fset.Position(comment.Pos()), comment.Text)
1566 if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
1567 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
1568 got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
1571 t.Errorf("%s: at %s: %s resolved to %s, want %s",
1572 fset.Position(comment.Pos()), comment.Text, name, got, want)
1577 // Check that for each referring identifier,
1578 // a lookup of its name on the innermost
1579 // enclosing scope returns the correct object.
1581 for id, wantObj := range info.Uses {
1582 inner := mainScope.Innermost(id.Pos())
1584 t.Errorf("%s: can't find innermost scope enclosing %q",
1585 fset.Position(id.Pos()), id.Name)
1589 // Exclude selectors and qualified identifiers---lexical
1590 // refs only. (Ideally, we'd see if the AST parent is a
1591 // SelectorExpr, but that requires PathEnclosingInterval
1592 // from golang.org/x/tools/go/ast/astutil.)
1597 _, gotObj := inner.LookupParent(id.Name, id.Pos())
1598 if gotObj != wantObj {
1599 t.Errorf("%s: got %v, want %v",
1600 fset.Position(id.Pos()), gotObj, wantObj)
1606 // newDefined creates a new defined type named T with the given underlying type.
1607 // Helper function for use with TestIncompleteInterfaces only.
1608 func newDefined(underlying Type) *Named {
1609 tname := NewTypeName(token.NoPos, nil, "T", nil)
1610 return NewNamed(tname, underlying, nil)
1613 func TestConvertibleTo(t *testing.T) {
1614 for _, test := range []struct {
1618 {Typ[Int], Typ[Int], true},
1619 {Typ[Int], Typ[Float32], true},
1620 {Typ[Int], Typ[String], true},
1621 {newDefined(Typ[Int]), Typ[Int], true},
1622 {newDefined(new(Struct)), new(Struct), true},
1623 {newDefined(Typ[Int]), new(Struct), false},
1624 {Typ[UntypedInt], Typ[Int], true},
1625 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
1626 {NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
1627 {NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
1628 // Untyped string values are not permitted by the spec, so the behavior below is undefined.
1629 {Typ[UntypedString], Typ[String], true},
1631 if got := ConvertibleTo(test.v, test.t); got != test.want {
1632 t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1637 func TestAssignableTo(t *testing.T) {
1638 for _, test := range []struct {
1642 {Typ[Int], Typ[Int], true},
1643 {Typ[Int], Typ[Float32], false},
1644 {newDefined(Typ[Int]), Typ[Int], false},
1645 {newDefined(new(Struct)), new(Struct), true},
1646 {Typ[UntypedBool], Typ[Bool], true},
1647 {Typ[UntypedString], Typ[Bool], false},
1648 // Neither untyped string nor untyped numeric assignments arise during
1649 // normal type checking, so the below behavior is technically undefined by
1651 {Typ[UntypedString], Typ[String], true},
1652 {Typ[UntypedInt], Typ[Int], true},
1654 if got := AssignableTo(test.v, test.t); got != test.want {
1655 t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
1660 func TestIdentical_issue15173(t *testing.T) {
1661 // Identical should allow nil arguments and be symmetric.
1662 for _, test := range []struct {
1666 {Typ[Int], Typ[Int], true},
1667 {Typ[Int], nil, false},
1668 {nil, Typ[Int], false},
1671 if got := Identical(test.x, test.y); got != test.want {
1672 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1677 func TestIdenticalUnions(t *testing.T) {
1678 tname := NewTypeName(token.NoPos, nil, "myInt", nil)
1679 myInt := NewNamed(tname, Typ[Int], nil)
1680 tmap := map[string]*Term{
1681 "int": NewTerm(false, Typ[Int]),
1682 "~int": NewTerm(true, Typ[Int]),
1683 "string": NewTerm(false, Typ[String]),
1684 "~string": NewTerm(true, Typ[String]),
1685 "myInt": NewTerm(false, myInt),
1687 makeUnion := func(s string) *Union {
1688 parts := strings.Split(s, "|")
1690 for _, p := range parts {
1693 t.Fatalf("missing term %q", p)
1695 terms = append(terms, term)
1697 return NewUnion(terms)
1699 for _, test := range []struct {
1703 // These tests are just sanity checks. The tests for type sets and
1704 // interfaces provide much more test coverage.
1705 {"int|~int", "~int", true},
1706 {"myInt|~int", "~int", true},
1707 {"int|string", "string|int", true},
1708 {"int|int|string", "string|int", true},
1709 {"myInt|string", "int|string", false},
1711 x := makeUnion(test.x)
1712 y := makeUnion(test.y)
1713 if got := Identical(x, y); got != test.want {
1714 t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
1719 func TestIssue15305(t *testing.T) {
1720 const src = "package p; func f() int16; var _ = f(undef)"
1721 fset := token.NewFileSet()
1722 f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
1727 Error: func(err error) {}, // allow errors
1730 Types: make(map[ast.Expr]TypeAndValue),
1732 conf.Check("p", fset, []*ast.File{f}, info) // ignore result
1733 for e, tv := range info.Types {
1734 if _, ok := e.(*ast.CallExpr); ok {
1735 if tv.Type != Typ[Int16] {
1736 t.Errorf("CallExpr has type %v, want int16", tv.Type)
1741 t.Errorf("CallExpr has no type")
1744 // TestCompositeLitTypes verifies that Info.Types registers the correct
1745 // types for composite literal expressions and composite literal type
1747 func TestCompositeLitTypes(t *testing.T) {
1748 for _, test := range []struct {
1751 {`[16]byte{}`, `[16]byte`},
1752 {`[...]byte{}`, `[0]byte`}, // test for issue #14092
1753 {`[...]int{1, 2, 3}`, `[3]int`}, // test for issue #14092
1754 {`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
1755 {`[]int{}`, `[]int`},
1756 {`map[string]bool{"foo": true}`, `map[string]bool`},
1757 {`struct{}{}`, `struct{}`},
1758 {`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
1760 fset := token.NewFileSet()
1761 f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
1763 t.Fatalf("%s: %v", test.lit, err)
1767 Types: make(map[ast.Expr]TypeAndValue),
1769 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1770 t.Fatalf("%s: %v", test.lit, err)
1773 cmptype := func(x ast.Expr, want string) {
1774 tv, ok := info.Types[x]
1776 t.Errorf("%s: no Types entry found", test.lit)
1780 t.Errorf("%s: type is nil", test.lit)
1783 if got := tv.Type.String(); got != want {
1784 t.Errorf("%s: got %v, want %s", test.lit, got, want)
1788 // test type of composite literal expression
1789 rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
1790 cmptype(rhs, test.typ)
1792 // test type of composite literal type expression
1793 cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
1797 // TestObjectParents verifies that objects have parent scopes or not
1798 // as specified by the Object interface.
1799 func TestObjectParents(t *testing.T) {
1818 func f(x int) { y := x; print(y) }
1821 fset := token.NewFileSet()
1822 f, err := parser.ParseFile(fset, "src", src, 0)
1828 Defs: make(map[*ast.Ident]Object),
1830 if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
1834 for ident, obj := range info.Defs {
1836 // only package names and implicit vars have a nil object
1837 // (in this test we only need to handle the package name)
1838 if ident.Name != "p" {
1839 t.Errorf("%v has nil object", ident)
1844 // struct fields, type-associated and interface methods
1845 // have no parent scope
1847 switch obj := obj.(type) {
1853 if obj.Type().(*Signature).Recv() != nil { // method
1858 gotParent := obj.Parent() != nil
1860 case gotParent && !wantParent:
1861 t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
1862 case !gotParent && wantParent:
1863 t.Errorf("%v: no parent found", ident)
1868 // TestFailedImport tests that we don't get follow-on errors
1869 // elsewhere in a package due to failing to import a package.
1870 func TestFailedImport(t *testing.T) {
1871 testenv.MustHaveGoBuild(t)
1876 import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
1881 func f(x T) T { return foo.F(x) }
1883 fset := token.NewFileSet()
1884 f, err := parser.ParseFile(fset, "src", src, 0)
1888 files := []*ast.File{f}
1890 // type-check using all possible importers
1891 for _, compiler := range []string{"gc", "gccgo", "source"} {
1894 Error: func(err error) {
1895 // we should only see the import error
1896 if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
1897 t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
1901 Importer: importer.For(compiler, nil),
1905 Uses: make(map[*ast.Ident]Object),
1907 pkg, _ := conf.Check("p", fset, files, info)
1909 t.Errorf("for %s importer, type-checking failed to return a package", compiler)
1913 imports := pkg.Imports()
1914 if len(imports) != 1 {
1915 t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
1919 if imp.Name() != "foo" {
1920 t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
1924 // verify that all uses of foo refer to the imported package foo (imp)
1925 for ident, obj := range info.Uses {
1926 if ident.Name == "foo" {
1927 if obj, ok := obj.(*PkgName); ok {
1928 if obj.Imported() != imp {
1929 t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
1932 t.Errorf("%s resolved to %v; want package name", ident, obj)
1939 func TestInstantiate(t *testing.T) {
1940 // eventually we like more tests but this is a start
1941 const src = genericPkg + "p; type T[P any] *T[P]"
1942 pkg, err := pkgFor(".", src, nil)
1947 // type T should have one type parameter
1948 T := pkg.Scope().Lookup("T").Type().(*Named)
1949 if n := T.TypeParams().Len(); n != 1 {
1950 t.Fatalf("expected 1 type parameter; found %d", n)
1953 // instantiation should succeed (no endless recursion)
1954 // even with a nil *Checker
1955 res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
1960 // instantiated type should point to itself
1961 if p := res.Underlying().(*Pointer).Elem(); p != res {
1962 t.Fatalf("unexpected result type: %s points to %s", res, p)
1966 func TestInstantiateErrors(t *testing.T) {
1968 src string // by convention, T must be the type being instantiated
1970 wantAt int // -1 indicates no error
1972 {"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
1973 {"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
1974 {"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
1975 {"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
1978 for _, test := range tests {
1979 src := genericPkg + "p; " + test.src
1980 pkg, err := pkgFor(".", src, nil)
1985 T := pkg.Scope().Lookup("T").Type().(*Named)
1987 _, err = Instantiate(nil, T, test.targs, true)
1989 t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
1992 var argErr *ArgumentError
1993 if !errors.As(err, &argErr) {
1994 t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
1997 if argErr.Index != test.wantAt {
1998 t.Errorf("Instantate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
2003 func TestArgumentErrorUnwrapping(t *testing.T) {
2004 var err error = &ArgumentError{
2006 Err: Error{Msg: "test"},
2009 if !errors.As(err, &e) {
2010 t.Fatalf("error %v does not wrap types.Error", err)
2012 if e.Msg != "test" {
2013 t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
2017 func TestInstanceIdentity(t *testing.T) {
2018 imports := make(testImporter)
2019 conf := Config{Importer: imports}
2020 makePkg := func(src string) {
2021 fset := token.NewFileSet()
2022 f, err := parser.ParseFile(fset, "", src, 0)
2027 pkg, err := conf.Check(name, fset, []*ast.File{f}, nil)
2033 makePkg(genericPkg + `lib; type T[P any] struct{}`)
2034 makePkg(genericPkg + `a; import "generic_lib"; var A generic_lib.T[int]`)
2035 makePkg(genericPkg + `b; import "generic_lib"; var B generic_lib.T[int]`)
2036 a := imports["generic_a"].Scope().Lookup("A")
2037 b := imports["generic_b"].Scope().Lookup("B")
2038 if !Identical(a.Type(), b.Type()) {
2039 t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())