...

Source file src/go/types/api_test.go

Documentation: go/types

		 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.
		 4  
		 5  package types_test
		 6  
		 7  import (
		 8  	"bytes"
		 9  	"fmt"
		10  	"go/ast"
		11  	"go/importer"
		12  	"go/internal/typeparams"
		13  	"go/parser"
		14  	"go/token"
		15  	"internal/testenv"
		16  	"reflect"
		17  	"regexp"
		18  	"strings"
		19  	"testing"
		20  
		21  	. "go/types"
		22  )
		23  
		24  // pkgFor parses and type checks the package specified by path and source,
		25  // populating info if provided.
		26  //
		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)
		33  	if err != nil {
		34  		return nil, err
		35  	}
		36  	conf := Config{Importer: importer.Default()}
		37  	return conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
		38  }
		39  
		40  func mustTypecheck(t *testing.T, path, source string, info *Info) string {
		41  	pkg, err := pkgFor(path, source, info)
		42  	if err != nil {
		43  		name := path
		44  		if pkg != nil {
		45  			name = "package " + pkg.Name()
		46  		}
		47  		t.Fatalf("%s: didn't type-check (%s)", name, err)
		48  	}
		49  	return pkg.Name()
		50  }
		51  
		52  // genericPkg is a prefix for packages that should be type checked with
		53  // generics.
		54  const genericPkg = "package generic_"
		55  
		56  func modeForSource(src string) parser.Mode {
		57  	if !strings.HasPrefix(src, genericPkg) {
		58  		return typeparams.DisallowParsing
		59  	}
		60  	return 0
		61  }
		62  
		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)
		69  	}
		70  	conf := Config{
		71  		Error:		func(err error) {},
		72  		Importer: importer.Default(),
		73  	}
		74  	pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, info)
		75  	return pkg.Name(), err
		76  }
		77  
		78  func TestValuesInfo(t *testing.T) {
		79  	var tests = []struct {
		80  		src	string
		81  		expr string // constant expression
		82  		typ	string // constant type
		83  		val	string // constant value
		84  	}{
		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"`},
		91  
		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"`},
		98  
		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`},
	 102  
	 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`},
	 106  
	 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`},
	 110  
	 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`},
	 114  
	 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)`},
	 118  
	 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`, ``},
	 126  
	 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"`},
	 131  
	 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)`},
	 140  
	 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)`},
	 153  
	 154  		{`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // issue #22341
	 155  	}
	 156  
	 157  	for _, test := range tests {
	 158  		info := Info{
	 159  			Types: make(map[ast.Expr]TypeAndValue),
	 160  		}
	 161  		name := mustTypecheck(t, "ValuesInfo", test.src, &info)
	 162  
	 163  		// look for expression
	 164  		var expr ast.Expr
	 165  		for e := range info.Types {
	 166  			if ExprString(e) == test.expr {
	 167  				expr = e
	 168  				break
	 169  			}
	 170  		}
	 171  		if expr == nil {
	 172  			t.Errorf("package %s: no expression found for %s", name, test.expr)
	 173  			continue
	 174  		}
	 175  		tv := info.Types[expr]
	 176  
	 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)
	 180  			continue
	 181  		}
	 182  
	 183  		// if we have a constant, check that value is correct
	 184  		if tv.Value != nil {
	 185  			if got := tv.Value.ExactString(); got != test.val {
	 186  				t.Errorf("package %s: got value %s; want %s", name, got, test.val)
	 187  			}
	 188  		} else {
	 189  			if test.val != "" {
	 190  				t.Errorf("package %s: no constant found; want %s", name, test.val)
	 191  			}
	 192  		}
	 193  	}
	 194  }
	 195  
	 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_"
	 199  
	 200  	var tests = []struct {
	 201  		src	string
	 202  		expr string // expression
	 203  		typ	string // value type
	 204  	}{
	 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`},
	 211  
	 212  		// uses of nil
	 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`},
	 220  
	 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`},
	 228  
	 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`},
	 236  
	 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`},
	 244  
	 245  		// comma-ok expressions
	 246  		{`package p0; var x interface{}; var _, _ = x.(int)`,
	 247  			`x.(int)`,
	 248  			`(int, bool)`,
	 249  		},
	 250  		{`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
	 251  			`x.(int)`,
	 252  			`(int, bool)`,
	 253  		},
	 254  		{`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
	 255  			`m["foo"]`,
	 256  			`(complex128, p2a.mybool)`,
	 257  		},
	 258  		{`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
	 259  			`m["foo"]`,
	 260  			`(complex128, bool)`,
	 261  		},
	 262  		{`package p3; var c chan string; var _, _ = <-c`,
	 263  			`<-c`,
	 264  			`(string, bool)`,
	 265  		},
	 266  
	 267  		// issue 6796
	 268  		{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
	 269  			`x.(int)`,
	 270  			`(int, bool)`,
	 271  		},
	 272  		{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
	 273  			`(<-c)`,
	 274  			`(string, bool)`,
	 275  		},
	 276  		{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
	 277  			`<-c`,
	 278  			`(string, bool)`,
	 279  		},
	 280  		{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
	 281  			`(<-c)`,
	 282  			`(string, bool)`,
	 283  		},
	 284  		{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
	 285  			`(<-c)`,
	 286  			`(string, bool)`,
	 287  		},
	 288  
	 289  		// issue 7060
	 290  		{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
	 291  			`m[0]`,
	 292  			`(string, bool)`,
	 293  		},
	 294  		{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
	 295  			`m[0]`,
	 296  			`(string, bool)`,
	 297  		},
	 298  		{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
	 299  			`m[0]`,
	 300  			`(string, bool)`,
	 301  		},
	 302  		{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
	 303  			`<-ch`,
	 304  			`(string, bool)`,
	 305  		},
	 306  		{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
	 307  			`<-ch`,
	 308  			`(string, bool)`,
	 309  		},
	 310  		{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
	 311  			`<-ch`,
	 312  			`(string, bool)`,
	 313  		},
	 314  
	 315  		// issue 28277
	 316  		{`package issue28277_a; func f(...int)`,
	 317  			`...int`,
	 318  			`[]int`,
	 319  		},
	 320  		{`package issue28277_b; func f(a, b int, c ...[]struct{})`,
	 321  			`...[]struct{}`,
	 322  			`[][]struct{}`,
	 323  		},
	 324  
	 325  		// issue 47243
	 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`},
	 336  
	 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`},
	 344  
	 345  		// parameterized functions
	 346  		{genericPkg + `p0; func f[T any](T); var _ = f[int]`, `f`, `func[T₁ interface{}](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[T₁ interface{}](T₁)`},
	 349  		{genericPkg + `p3; func f[T any](T); func _() { f(42) }`, `f(42)`, `()`},
	 350  
	 351  		// type parameters
	 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[P₁ interface{}]`},
	 354  		{genericPkg + `t2; type t[P interface{}] int; var _ t[int]`, `t`, `generic_t2.t[P₁ interface{}]`},
	 355  		{genericPkg + `t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `generic_t3.t[P₁, Q₂ interface{}]`},
	 356  
	 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`},
	 359  
	 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]`},
	 362  
	 363  		// issue 45096
	 364  		{genericPkg + `issue45096; func _[T interface{ type int8, int16, int32	}](x T) { _ = x < 0 }`, `0`, `T₁`},
	 365  	}
	 366  
	 367  	for _, test := range tests {
	 368  		ResetId() // avoid renumbering of type parameter ids when adding tests
	 369  		if strings.HasPrefix(test.src, genericPkg) && !typeparams.Enabled {
	 370  			continue
	 371  		}
	 372  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
	 373  		var name string
	 374  		if strings.HasPrefix(test.src, broken) {
	 375  			var err error
	 376  			name, err = mayTypecheck(t, "TypesInfo", test.src, &info)
	 377  			if err == nil {
	 378  				t.Errorf("package %s: expected to fail but passed", name)
	 379  				continue
	 380  			}
	 381  		} else {
	 382  			name = mustTypecheck(t, "TypesInfo", test.src, &info)
	 383  		}
	 384  
	 385  		// look for expression type
	 386  		var typ Type
	 387  		for e, tv := range info.Types {
	 388  			if ExprString(e) == test.expr {
	 389  				typ = tv.Type
	 390  				break
	 391  			}
	 392  		}
	 393  		if typ == nil {
	 394  			t.Errorf("package %s: no type found for %s", name, test.expr)
	 395  			continue
	 396  		}
	 397  
	 398  		// check that type is correct
	 399  		if got := typ.String(); got != test.typ {
	 400  			t.Errorf("package %s: got %s; want %s", name, got, test.typ)
	 401  		}
	 402  	}
	 403  }
	 404  
	 405  func TestDefsInfo(t *testing.T) {
	 406  	var tests = []struct {
	 407  		src	string
	 408  		obj	string
	 409  		want string
	 410  	}{
	 411  		{`package p0; const x = 42`, `x`, `const p0.x untyped int`},
	 412  		{`package p1; const x int = 42`, `x`, `const p1.x int`},
	 413  		{`package p2; var x int`, `x`, `var p2.x int`},
	 414  		{`package p3; type x int`, `x`, `type p3.x int`},
	 415  		{`package p4; func f()`, `f`, `func p4.f()`},
	 416  		{`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
	 417  
	 418  		// generic types must be sanitized
	 419  		// (need to use sufficiently nested types to provoke unexpanded types)
	 420  		{genericPkg + `g0; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
	 421  		{genericPkg + `g1; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
	 422  		{genericPkg + `g2; type t[P any] P; type x struct{ f t[int] }`, `x`, `type generic_g2.x struct{f generic_g2.t[int]}`},
	 423  		{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]})`},
	 424  	}
	 425  
	 426  	for _, test := range tests {
	 427  		if strings.HasPrefix(test.src, genericPkg) && !typeparams.Enabled {
	 428  			continue
	 429  		}
	 430  		info := Info{
	 431  			Defs: make(map[*ast.Ident]Object),
	 432  		}
	 433  		name := mustTypecheck(t, "DefsInfo", test.src, &info)
	 434  
	 435  		// find object
	 436  		var def Object
	 437  		for id, obj := range info.Defs {
	 438  			if id.Name == test.obj {
	 439  				def = obj
	 440  				break
	 441  			}
	 442  		}
	 443  		if def == nil {
	 444  			t.Errorf("package %s: %s not found", name, test.obj)
	 445  			continue
	 446  		}
	 447  
	 448  		if got := def.String(); got != test.want {
	 449  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
	 450  		}
	 451  	}
	 452  }
	 453  
	 454  func TestUsesInfo(t *testing.T) {
	 455  	var tests = []struct {
	 456  		src	string
	 457  		obj	string
	 458  		want string
	 459  	}{
	 460  		{`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
	 461  		{`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
	 462  		{`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
	 463  		{`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
	 464  		{`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
	 465  
	 466  		// generic types must be sanitized
	 467  		// (need to use sufficiently nested types to provoke unexpanded types)
	 468  		{genericPkg + `g0; func _() { _ = x }; type t[P any] P; const x = t[int](42)`, `x`, `const generic_g0.x generic_g0.t[int]`},
	 469  		{genericPkg + `g1; func _() { _ = x }; type t[P any] P; var x = t[int](42)`, `x`, `var generic_g1.x generic_g1.t[int]`},
	 470  		{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]}`},
	 471  		{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]})`},
	 472  	}
	 473  
	 474  	for _, test := range tests {
	 475  		if strings.HasPrefix(test.src, genericPkg) && !typeparams.Enabled {
	 476  			continue
	 477  		}
	 478  		info := Info{
	 479  			Uses: make(map[*ast.Ident]Object),
	 480  		}
	 481  		name := mustTypecheck(t, "UsesInfo", test.src, &info)
	 482  
	 483  		// find object
	 484  		var use Object
	 485  		for id, obj := range info.Uses {
	 486  			if id.Name == test.obj {
	 487  				use = obj
	 488  				break
	 489  			}
	 490  		}
	 491  		if use == nil {
	 492  			t.Errorf("package %s: %s not found", name, test.obj)
	 493  			continue
	 494  		}
	 495  
	 496  		if got := use.String(); got != test.want {
	 497  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
	 498  		}
	 499  	}
	 500  }
	 501  
	 502  func TestImplicitsInfo(t *testing.T) {
	 503  	testenv.MustHaveGoBuild(t)
	 504  
	 505  	var tests = []struct {
	 506  		src	string
	 507  		want string
	 508  	}{
	 509  		{`package p2; import . "fmt"; var _ = Println`, ""},					 // no Implicits entry
	 510  		{`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
	 511  		{`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
	 512  
	 513  		{`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
	 514  		{`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
	 515  		{`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
	 516  		{`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
	 517  
	 518  		{`package p7; func f(x int) {}`, ""}, // no Implicits entry
	 519  		{`package p8; func f(int) {}`, "field: var	int"},
	 520  		{`package p9; func f() (complex64) { return 0 }`, "field: var	complex64"},
	 521  		{`package p10; type T struct{}; func (*T) f() {}`, "field: var	*p10.T"},
	 522  	}
	 523  
	 524  	for _, test := range tests {
	 525  		info := Info{
	 526  			Implicits: make(map[ast.Node]Object),
	 527  		}
	 528  		name := mustTypecheck(t, "ImplicitsInfo", test.src, &info)
	 529  
	 530  		// the test cases expect at most one Implicits entry
	 531  		if len(info.Implicits) > 1 {
	 532  			t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
	 533  			continue
	 534  		}
	 535  
	 536  		// extract Implicits entry, if any
	 537  		var got string
	 538  		for n, obj := range info.Implicits {
	 539  			switch x := n.(type) {
	 540  			case *ast.ImportSpec:
	 541  				got = "importSpec"
	 542  			case *ast.CaseClause:
	 543  				got = "caseClause"
	 544  			case *ast.Field:
	 545  				got = "field"
	 546  			default:
	 547  				t.Fatalf("package %s: unexpected %T", name, x)
	 548  			}
	 549  			got += ": " + obj.String()
	 550  		}
	 551  
	 552  		// verify entry
	 553  		if got != test.want {
	 554  			t.Errorf("package %s: got %q; want %q", name, got, test.want)
	 555  		}
	 556  	}
	 557  }
	 558  
	 559  func predString(tv TypeAndValue) string {
	 560  	var buf bytes.Buffer
	 561  	pred := func(b bool, s string) {
	 562  		if b {
	 563  			if buf.Len() > 0 {
	 564  				buf.WriteString(", ")
	 565  			}
	 566  			buf.WriteString(s)
	 567  		}
	 568  	}
	 569  
	 570  	pred(tv.IsVoid(), "void")
	 571  	pred(tv.IsType(), "type")
	 572  	pred(tv.IsBuiltin(), "builtin")
	 573  	pred(tv.IsValue() && tv.Value != nil, "const")
	 574  	pred(tv.IsValue() && tv.Value == nil, "value")
	 575  	pred(tv.IsNil(), "nil")
	 576  	pred(tv.Addressable(), "addressable")
	 577  	pred(tv.Assignable(), "assignable")
	 578  	pred(tv.HasOk(), "hasOk")
	 579  
	 580  	if buf.Len() == 0 {
	 581  		return "invalid"
	 582  	}
	 583  	return buf.String()
	 584  }
	 585  
	 586  func TestPredicatesInfo(t *testing.T) {
	 587  	testenv.MustHaveGoBuild(t)
	 588  
	 589  	var tests = []struct {
	 590  		src	string
	 591  		expr string
	 592  		pred string
	 593  	}{
	 594  		// void
	 595  		{`package n0; func f() { f() }`, `f()`, `void`},
	 596  
	 597  		// types
	 598  		{`package t0; type _ int`, `int`, `type`},
	 599  		{`package t1; type _ []int`, `[]int`, `type`},
	 600  		{`package t2; type _ func()`, `func()`, `type`},
	 601  		{`package t3; type _ func(int)`, `int`, `type`},
	 602  		{`package t3; type _ func(...int)`, `...int`, `type`},
	 603  
	 604  		// built-ins
	 605  		{`package b0; var _ = len("")`, `len`, `builtin`},
	 606  		{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
	 607  
	 608  		// constants
	 609  		{`package c0; var _ = 42`, `42`, `const`},
	 610  		{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
	 611  		{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
	 612  
	 613  		// values
	 614  		{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
	 615  		{`package v1; var _ = &[]int{1}`, `([]int literal)`, `value`},
	 616  		{`package v2; var _ = func(){}`, `(func() literal)`, `value`},
	 617  		{`package v4; func f() { _ = f }`, `f`, `value`},
	 618  		{`package v3; var _ *int = nil`, `nil`, `value, nil`},
	 619  		{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
	 620  
	 621  		// addressable (and thus assignable) operands
	 622  		{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
	 623  		{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
	 624  		{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
	 625  		{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
	 626  		{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
	 627  		{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
	 628  		{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
	 629  		{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
	 630  		// composite literals are not addressable
	 631  
	 632  		// assignable but not addressable values
	 633  		{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
	 634  		{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
	 635  
	 636  		// hasOk expressions
	 637  		{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
	 638  		{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
	 639  
	 640  		// missing entries
	 641  		// - package names are collected in the Uses map
	 642  		// - identifiers being declared are collected in the Defs map
	 643  		{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
	 644  		{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
	 645  		{`package m2; const c = 0`, `c`, `<missing>`},
	 646  		{`package m3; type T int`, `T`, `<missing>`},
	 647  		{`package m4; var v int`, `v`, `<missing>`},
	 648  		{`package m5; func f() {}`, `f`, `<missing>`},
	 649  		{`package m6; func _(x int) {}`, `x`, `<missing>`},
	 650  		{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
	 651  		{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
	 652  	}
	 653  
	 654  	for _, test := range tests {
	 655  		info := Info{Types: make(map[ast.Expr]TypeAndValue)}
	 656  		name := mustTypecheck(t, "PredicatesInfo", test.src, &info)
	 657  
	 658  		// look for expression predicates
	 659  		got := "<missing>"
	 660  		for e, tv := range info.Types {
	 661  			//println(name, ExprString(e))
	 662  			if ExprString(e) == test.expr {
	 663  				got = predString(tv)
	 664  				break
	 665  			}
	 666  		}
	 667  
	 668  		if got != test.pred {
	 669  			t.Errorf("package %s: got %s; want %s", name, got, test.pred)
	 670  		}
	 671  	}
	 672  }
	 673  
	 674  func TestScopesInfo(t *testing.T) {
	 675  	testenv.MustHaveGoBuild(t)
	 676  
	 677  	var tests = []struct {
	 678  		src		string
	 679  		scopes []string // list of scope descriptors of the form kind:varlist
	 680  	}{
	 681  		{`package p0`, []string{
	 682  			"file:",
	 683  		}},
	 684  		{`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
	 685  			"file:fmt m",
	 686  		}},
	 687  		{`package p2; func _() {}`, []string{
	 688  			"file:", "func:",
	 689  		}},
	 690  		{`package p3; func _(x, y int) {}`, []string{
	 691  			"file:", "func:x y",
	 692  		}},
	 693  		{`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
	 694  			"file:", "func:x y z", // redeclaration of x
	 695  		}},
	 696  		{`package p5; func _(x, y int) (u, _ int) { return }`, []string{
	 697  			"file:", "func:u x y",
	 698  		}},
	 699  		{`package p6; func _() { { var x int; _ = x } }`, []string{
	 700  			"file:", "func:", "block:x",
	 701  		}},
	 702  		{`package p7; func _() { if true {} }`, []string{
	 703  			"file:", "func:", "if:", "block:",
	 704  		}},
	 705  		{`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
	 706  			"file:", "func:", "if:x", "block:y",
	 707  		}},
	 708  		{`package p9; func _() { switch x := 0; x {} }`, []string{
	 709  			"file:", "func:", "switch:x",
	 710  		}},
	 711  		{`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
	 712  			"file:", "func:", "switch:x", "case:y", "case:",
	 713  		}},
	 714  		{`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
	 715  			"file:", "func:t", "type switch:",
	 716  		}},
	 717  		{`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
	 718  			"file:", "func:t", "type switch:t",
	 719  		}},
	 720  		{`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
	 721  			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
	 722  		}},
	 723  		{`package p14; func _() { select{} }`, []string{
	 724  			"file:", "func:",
	 725  		}},
	 726  		{`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
	 727  			"file:", "func:c", "comm:",
	 728  		}},
	 729  		{`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
	 730  			"file:", "func:c", "comm:i x",
	 731  		}},
	 732  		{`package p17; func _() { for{} }`, []string{
	 733  			"file:", "func:", "for:", "block:",
	 734  		}},
	 735  		{`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
	 736  			"file:", "func:n", "for:i", "block:",
	 737  		}},
	 738  		{`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
	 739  			"file:", "func:a", "range:i", "block:",
	 740  		}},
	 741  		{`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
	 742  			"file:", "func:a", "range:i x", "block:",
	 743  		}},
	 744  	}
	 745  
	 746  	for _, test := range tests {
	 747  		info := Info{Scopes: make(map[ast.Node]*Scope)}
	 748  		name := mustTypecheck(t, "ScopesInfo", test.src, &info)
	 749  
	 750  		// number of scopes must match
	 751  		if len(info.Scopes) != len(test.scopes) {
	 752  			t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
	 753  		}
	 754  
	 755  		// scope descriptions must match
	 756  		for node, scope := range info.Scopes {
	 757  			kind := "<unknown node kind>"
	 758  			switch node.(type) {
	 759  			case *ast.File:
	 760  				kind = "file"
	 761  			case *ast.FuncType:
	 762  				kind = "func"
	 763  			case *ast.BlockStmt:
	 764  				kind = "block"
	 765  			case *ast.IfStmt:
	 766  				kind = "if"
	 767  			case *ast.SwitchStmt:
	 768  				kind = "switch"
	 769  			case *ast.TypeSwitchStmt:
	 770  				kind = "type switch"
	 771  			case *ast.CaseClause:
	 772  				kind = "case"
	 773  			case *ast.CommClause:
	 774  				kind = "comm"
	 775  			case *ast.ForStmt:
	 776  				kind = "for"
	 777  			case *ast.RangeStmt:
	 778  				kind = "range"
	 779  			}
	 780  
	 781  			// look for matching scope description
	 782  			desc := kind + ":" + strings.Join(scope.Names(), " ")
	 783  			found := false
	 784  			for _, d := range test.scopes {
	 785  				if desc == d {
	 786  					found = true
	 787  					break
	 788  				}
	 789  			}
	 790  			if !found {
	 791  				t.Errorf("package %s: no matching scope found for %s", name, desc)
	 792  			}
	 793  		}
	 794  	}
	 795  }
	 796  
	 797  func TestInitOrderInfo(t *testing.T) {
	 798  	var tests = []struct {
	 799  		src	 string
	 800  		inits []string
	 801  	}{
	 802  		{`package p0; var (x = 1; y = x)`, []string{
	 803  			"x = 1", "y = x",
	 804  		}},
	 805  		{`package p1; var (a = 1; b = 2; c = 3)`, []string{
	 806  			"a = 1", "b = 2", "c = 3",
	 807  		}},
	 808  		{`package p2; var (a, b, c = 1, 2, 3)`, []string{
	 809  			"a = 1", "b = 2", "c = 3",
	 810  		}},
	 811  		{`package p3; var _ = f(); func f() int { return 1 }`, []string{
	 812  			"_ = f()", // blank var
	 813  		}},
	 814  		{`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
	 815  			"a = 0", "z = 0", "y = z", "x = y",
	 816  		}},
	 817  		{`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
	 818  			"a, _ = m[0]", // blank var
	 819  		}},
	 820  		{`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
	 821  			"z = 0", "a, b = f()",
	 822  		}},
	 823  		{`package p7; var (a = func() int { return b }(); b = 1)`, []string{
	 824  			"b = 1", "a = (func() int literal)()",
	 825  		}},
	 826  		{`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
	 827  			"c = 1", "a, b = (func() (_, _ int) literal)()",
	 828  		}},
	 829  		{`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
	 830  			"y = 1", "x = T.m",
	 831  		}},
	 832  		{`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
	 833  			"a = 0", "b = 0", "c = 0", "d = c + b",
	 834  		}},
	 835  		{`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
	 836  			"c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
	 837  		}},
	 838  		// emit an initializer for n:1 initializations only once (not for each node
	 839  		// on the lhs which may appear in different order in the dependency graph)
	 840  		{`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
	 841  			"b = 0", "x, y = m[0]", "a = x",
	 842  		}},
	 843  		// test case from spec section on package initialization
	 844  		{`package p12
	 845  
	 846  		var (
	 847  			a = c + b
	 848  			b = f()
	 849  			c = f()
	 850  			d = 3
	 851  		)
	 852  
	 853  		func f() int {
	 854  			d++
	 855  			return d
	 856  		}`, []string{
	 857  			"d = 3", "b = f()", "c = f()", "a = c + b",
	 858  		}},
	 859  		// test case for issue 7131
	 860  		{`package main
	 861  
	 862  		var counter int
	 863  		func next() int { counter++; return counter }
	 864  
	 865  		var _ = makeOrder()
	 866  		func makeOrder() []int { return []int{f, b, d, e, c, a} }
	 867  
	 868  		var a			 = next()
	 869  		var b, c		= next(), next()
	 870  		var d, e, f = next(), next(), next()
	 871  		`, []string{
	 872  			"a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
	 873  		}},
	 874  		// test case for issue 10709
	 875  		{`package p13
	 876  
	 877  		var (
	 878  				v = t.m()
	 879  				t = makeT(0)
	 880  		)
	 881  
	 882  		type T struct{}
	 883  
	 884  		func (T) m() int { return 0 }
	 885  
	 886  		func makeT(n int) T {
	 887  				if n > 0 {
	 888  						return makeT(n-1)
	 889  				}
	 890  				return T{}
	 891  		}`, []string{
	 892  			"t = makeT(0)", "v = t.m()",
	 893  		}},
	 894  		// test case for issue 10709: same as test before, but variable decls swapped
	 895  		{`package p14
	 896  
	 897  		var (
	 898  				t = makeT(0)
	 899  				v = t.m()
	 900  		)
	 901  
	 902  		type T struct{}
	 903  
	 904  		func (T) m() int { return 0 }
	 905  
	 906  		func makeT(n int) T {
	 907  				if n > 0 {
	 908  						return makeT(n-1)
	 909  				}
	 910  				return T{}
	 911  		}`, []string{
	 912  			"t = makeT(0)", "v = t.m()",
	 913  		}},
	 914  		// another candidate possibly causing problems with issue 10709
	 915  		{`package p15
	 916  
	 917  		var y1 = f1()
	 918  
	 919  		func f1() int { return g1() }
	 920  		func g1() int { f1(); return x1 }
	 921  
	 922  		var x1 = 0
	 923  
	 924  		var y2 = f2()
	 925  
	 926  		func f2() int { return g2() }
	 927  		func g2() int { return x2 }
	 928  
	 929  		var x2 = 0`, []string{
	 930  			"x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
	 931  		}},
	 932  	}
	 933  
	 934  	for _, test := range tests {
	 935  		info := Info{}
	 936  		name := mustTypecheck(t, "InitOrderInfo", test.src, &info)
	 937  
	 938  		// number of initializers must match
	 939  		if len(info.InitOrder) != len(test.inits) {
	 940  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
	 941  			continue
	 942  		}
	 943  
	 944  		// initializers must match
	 945  		for i, want := range test.inits {
	 946  			got := info.InitOrder[i].String()
	 947  			if got != want {
	 948  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
	 949  				continue
	 950  			}
	 951  		}
	 952  	}
	 953  }
	 954  
	 955  func TestMultiFileInitOrder(t *testing.T) {
	 956  	fset := token.NewFileSet()
	 957  	mustParse := func(src string) *ast.File {
	 958  		f, err := parser.ParseFile(fset, "main", src, 0)
	 959  		if err != nil {
	 960  			t.Fatal(err)
	 961  		}
	 962  		return f
	 963  	}
	 964  
	 965  	fileA := mustParse(`package main; var a = 1`)
	 966  	fileB := mustParse(`package main; var b = 2`)
	 967  
	 968  	// The initialization order must not depend on the parse
	 969  	// order of the files, only on the presentation order to
	 970  	// the type-checker.
	 971  	for _, test := range []struct {
	 972  		files []*ast.File
	 973  		want	string
	 974  	}{
	 975  		{[]*ast.File{fileA, fileB}, "[a = 1 b = 2]"},
	 976  		{[]*ast.File{fileB, fileA}, "[b = 2 a = 1]"},
	 977  	} {
	 978  		var info Info
	 979  		if _, err := new(Config).Check("main", fset, test.files, &info); err != nil {
	 980  			t.Fatal(err)
	 981  		}
	 982  		if got := fmt.Sprint(info.InitOrder); got != test.want {
	 983  			t.Fatalf("got %s; want %s", got, test.want)
	 984  		}
	 985  	}
	 986  }
	 987  
	 988  func TestFiles(t *testing.T) {
	 989  	var sources = []string{
	 990  		"package p; type T struct{}; func (T) m1() {}",
	 991  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
	 992  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
	 993  		"package p",
	 994  	}
	 995  
	 996  	var conf Config
	 997  	fset := token.NewFileSet()
	 998  	pkg := NewPackage("p", "p")
	 999  	var info Info
	1000  	check := NewChecker(&conf, fset, pkg, &info)
	1001  
	1002  	for i, src := range sources {
	1003  		filename := fmt.Sprintf("sources%d", i)
	1004  		f, err := parser.ParseFile(fset, filename, src, 0)
	1005  		if err != nil {
	1006  			t.Fatal(err)
	1007  		}
	1008  		if err := check.Files([]*ast.File{f}); err != nil {
	1009  			t.Error(err)
	1010  		}
	1011  	}
	1012  
	1013  	// check InitOrder is [x y]
	1014  	var vars []string
	1015  	for _, init := range info.InitOrder {
	1016  		for _, v := range init.Lhs {
	1017  			vars = append(vars, v.Name())
	1018  		}
	1019  	}
	1020  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
	1021  		t.Errorf("InitOrder == %s, want %s", got, want)
	1022  	}
	1023  }
	1024  
	1025  type testImporter map[string]*Package
	1026  
	1027  func (m testImporter) Import(path string) (*Package, error) {
	1028  	if pkg := m[path]; pkg != nil {
	1029  		return pkg, nil
	1030  	}
	1031  	return nil, fmt.Errorf("package %q not found", path)
	1032  }
	1033  
	1034  func TestSelection(t *testing.T) {
	1035  	selections := make(map[*ast.SelectorExpr]*Selection)
	1036  
	1037  	fset := token.NewFileSet()
	1038  	imports := make(testImporter)
	1039  	conf := Config{Importer: imports}
	1040  	makePkg := func(path, src string) {
	1041  		f, err := parser.ParseFile(fset, path+".go", src, 0)
	1042  		if err != nil {
	1043  			t.Fatal(err)
	1044  		}
	1045  		pkg, err := conf.Check(path, fset, []*ast.File{f}, &Info{Selections: selections})
	1046  		if err != nil {
	1047  			t.Fatal(err)
	1048  		}
	1049  		imports[path] = pkg
	1050  	}
	1051  
	1052  	const libSrc = `
	1053  package lib
	1054  type T float64
	1055  const C T = 3
	1056  var V T
	1057  func F() {}
	1058  func (T) M() {}
	1059  `
	1060  	const mainSrc = `
	1061  package main
	1062  import "lib"
	1063  
	1064  type A struct {
	1065  	*B
	1066  	C
	1067  }
	1068  
	1069  type B struct {
	1070  	b int
	1071  }
	1072  
	1073  func (B) f(int)
	1074  
	1075  type C struct {
	1076  	c int
	1077  }
	1078  
	1079  func (C) g()
	1080  func (*C) h()
	1081  
	1082  func main() {
	1083  	// qualified identifiers
	1084  	var _ lib.T
	1085  				_ = lib.C
	1086  				_ = lib.F
	1087  				_ = lib.V
	1088  	_ = lib.T.M
	1089  
	1090  	// fields
	1091  	_ = A{}.B
	1092  	_ = new(A).B
	1093  
	1094  	_ = A{}.C
	1095  	_ = new(A).C
	1096  
	1097  	_ = A{}.b
	1098  	_ = new(A).b
	1099  
	1100  	_ = A{}.c
	1101  	_ = new(A).c
	1102  
	1103  	// methods
	1104  				_ = A{}.f
	1105  				_ = new(A).f
	1106  				_ = A{}.g
	1107  				_ = new(A).g
	1108  				_ = new(A).h
	1109  
	1110  				_ = B{}.f
	1111  				_ = new(B).f
	1112  
	1113  				_ = C{}.g
	1114  				_ = new(C).g
	1115  				_ = new(C).h
	1116  
	1117  	// method expressions
	1118  				_ = A.f
	1119  				_ = (*A).f
	1120  				_ = B.f
	1121  				_ = (*B).f
	1122  }`
	1123  
	1124  	wantOut := map[string][2]string{
	1125  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
	1126  
	1127  		"A{}.B":		{"field (main.A) B *main.B", ".[0]"},
	1128  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
	1129  		"A{}.C":		{"field (main.A) C main.C", ".[1]"},
	1130  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
	1131  		"A{}.b":		{"field (main.A) b int", "->[0 0]"},
	1132  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
	1133  		"A{}.c":		{"field (main.A) c int", ".[1 0]"},
	1134  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
	1135  
	1136  		"A{}.f":		{"method (main.A) f(int)", "->[0 0]"},
	1137  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
	1138  		"A{}.g":		{"method (main.A) g()", ".[1 0]"},
	1139  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
	1140  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
	1141  		"B{}.f":		{"method (main.B) f(int)", ".[0]"},
	1142  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
	1143  		"C{}.g":		{"method (main.C) g()", ".[0]"},
	1144  		"new(C).g": {"method (*main.C) g()", "->[0]"},
	1145  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
	1146  
	1147  		"A.f":		{"method expr (main.A) f(main.A, int)", "->[0 0]"},
	1148  		"(*A).f": {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
	1149  		"B.f":		{"method expr (main.B) f(main.B, int)", ".[0]"},
	1150  		"(*B).f": {"method expr (*main.B) f(*main.B, int)", "->[0]"},
	1151  	}
	1152  
	1153  	makePkg("lib", libSrc)
	1154  	makePkg("main", mainSrc)
	1155  
	1156  	for e, sel := range selections {
	1157  		_ = sel.String() // assertion: must not panic
	1158  
	1159  		start := fset.Position(e.Pos()).Offset
	1160  		end := fset.Position(e.End()).Offset
	1161  		syntax := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
	1162  
	1163  		direct := "."
	1164  		if sel.Indirect() {
	1165  			direct = "->"
	1166  		}
	1167  		got := [2]string{
	1168  			sel.String(),
	1169  			fmt.Sprintf("%s%v", direct, sel.Index()),
	1170  		}
	1171  		want := wantOut[syntax]
	1172  		if want != got {
	1173  			t.Errorf("%s: got %q; want %q", syntax, got, want)
	1174  		}
	1175  		delete(wantOut, syntax)
	1176  
	1177  		// We must explicitly assert properties of the
	1178  		// Signature's receiver since it doesn't participate
	1179  		// in Identical() or String().
	1180  		sig, _ := sel.Type().(*Signature)
	1181  		if sel.Kind() == MethodVal {
	1182  			got := sig.Recv().Type()
	1183  			want := sel.Recv()
	1184  			if !Identical(got, want) {
	1185  				t.Errorf("%s: Recv() = %s, want %s", syntax, got, want)
	1186  			}
	1187  		} else if sig != nil && sig.Recv() != nil {
	1188  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
	1189  		}
	1190  	}
	1191  	// Assert that all wantOut entries were used exactly once.
	1192  	for syntax := range wantOut {
	1193  		t.Errorf("no ast.Selection found with syntax %q", syntax)
	1194  	}
	1195  }
	1196  
	1197  func TestIssue8518(t *testing.T) {
	1198  	fset := token.NewFileSet()
	1199  	imports := make(testImporter)
	1200  	conf := Config{
	1201  		Error:		func(err error) { t.Log(err) }, // don't exit after first error
	1202  		Importer: imports,
	1203  	}
	1204  	makePkg := func(path, src string) {
	1205  		f, err := parser.ParseFile(fset, path, src, 0)
	1206  		if err != nil {
	1207  			t.Fatal(err)
	1208  		}
	1209  		pkg, _ := conf.Check(path, fset, []*ast.File{f}, nil) // errors logged via conf.Error
	1210  		imports[path] = pkg
	1211  	}
	1212  
	1213  	const libSrc = `
	1214  package a
	1215  import "missing"
	1216  const C1 = foo
	1217  const C2 = missing.C
	1218  `
	1219  
	1220  	const mainSrc = `
	1221  package main
	1222  import "a"
	1223  var _ = a.C1
	1224  var _ = a.C2
	1225  `
	1226  
	1227  	makePkg("a", libSrc)
	1228  	makePkg("main", mainSrc) // don't crash when type-checking this package
	1229  }
	1230  
	1231  func TestLookupFieldOrMethod(t *testing.T) {
	1232  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
	1233  	// addressable value, and x for a non-addressable value (even though a variable
	1234  	// for ease of test case writing).
	1235  	//
	1236  	// Should be kept in sync with TestMethodSet.
	1237  	var tests = []struct {
	1238  		src			string
	1239  		found		bool
	1240  		index		[]int
	1241  		indirect bool
	1242  	}{
	1243  		// field lookups
	1244  		{"var x T; type T struct{}", false, nil, false},
	1245  		{"var x T; type T struct{ f int }", true, []int{0}, false},
	1246  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
	1247  
	1248  		// method lookups
	1249  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
	1250  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
	1251  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
	1252  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
	1253  
	1254  		// collisions
	1255  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
	1256  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
	1257  
	1258  		// outside methodset
	1259  		// (*T).f method exists, but value of type T is not addressable
	1260  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
	1261  	}
	1262  
	1263  	for _, test := range tests {
	1264  		pkg, err := pkgFor("test", "package p;"+test.src, nil)
	1265  		if err != nil {
	1266  			t.Errorf("%s: incorrect test case: %s", test.src, err)
	1267  			continue
	1268  		}
	1269  
	1270  		obj := pkg.Scope().Lookup("a")
	1271  		if obj == nil {
	1272  			if obj = pkg.Scope().Lookup("x"); obj == nil {
	1273  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
	1274  				continue
	1275  			}
	1276  		}
	1277  
	1278  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
	1279  		if (f != nil) != test.found {
	1280  			if f == nil {
	1281  				t.Errorf("%s: got no object; want one", test.src)
	1282  			} else {
	1283  				t.Errorf("%s: got object = %v; want none", test.src, f)
	1284  			}
	1285  		}
	1286  		if !sameSlice(index, test.index) {
	1287  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
	1288  		}
	1289  		if indirect != test.indirect {
	1290  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
	1291  		}
	1292  	}
	1293  }
	1294  
	1295  func sameSlice(a, b []int) bool {
	1296  	if len(a) != len(b) {
	1297  		return false
	1298  	}
	1299  	for i, x := range a {
	1300  		if x != b[i] {
	1301  			return false
	1302  		}
	1303  	}
	1304  	return true
	1305  }
	1306  
	1307  // TestScopeLookupParent ensures that (*Scope).LookupParent returns
	1308  // the correct result at various positions with the source.
	1309  func TestScopeLookupParent(t *testing.T) {
	1310  	fset := token.NewFileSet()
	1311  	imports := make(testImporter)
	1312  	conf := Config{Importer: imports}
	1313  	mustParse := func(src string) *ast.File {
	1314  		f, err := parser.ParseFile(fset, "dummy.go", src, parser.ParseComments)
	1315  		if err != nil {
	1316  			t.Fatal(err)
	1317  		}
	1318  		return f
	1319  	}
	1320  	var info Info
	1321  	makePkg := func(path string, files ...*ast.File) {
	1322  		var err error
	1323  		imports[path], err = conf.Check(path, fset, files, &info)
	1324  		if err != nil {
	1325  			t.Fatal(err)
	1326  		}
	1327  	}
	1328  
	1329  	makePkg("lib", mustParse("package lib; var X int"))
	1330  	// Each /*name=kind:line*/ comment makes the test look up the
	1331  	// name at that point and checks that it resolves to a decl of
	1332  	// the specified kind and line number.	"undef" means undefined.
	1333  	mainSrc := `
	1334  /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
	1335  package main
	1336  
	1337  import "lib"
	1338  import . "lib"
	1339  
	1340  const Pi = 3.1415
	1341  type T struct{}
	1342  var Y, _ = lib.X, X
	1343  
	1344  func F(){
	1345  	const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
	1346  	type /*t=undef*/ t /*t=typename:14*/ *t
	1347  	print(Y) /*Y=var:10*/
	1348  	x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
	1349  	var F = /*F=func:12*/ F /*F=var:17*/ ; _ = F
	1350  
	1351  	var a []int
	1352  	for i, x := range /*i=undef*/ /*x=var:16*/ a /*i=var:20*/ /*x=var:20*/ { _ = i; _ = x }
	1353  
	1354  	var i interface{}
	1355  	switch y := i.(type) { /*y=undef*/
	1356  	case /*y=undef*/ int /*y=var:23*/ :
	1357  	case float32, /*y=undef*/ float64 /*y=var:23*/ :
	1358  	default /*y=var:23*/:
	1359  		println(y)
	1360  	}
	1361  	/*y=undef*/
	1362  
	1363  				switch int := i.(type) {
	1364  				case /*int=typename:0*/ int /*int=var:31*/ :
	1365  					println(int)
	1366  				default /*int=var:31*/ :
	1367  				}
	1368  }
	1369  /*main=undef*/
	1370  `
	1371  
	1372  	info.Uses = make(map[*ast.Ident]Object)
	1373  	f := mustParse(mainSrc)
	1374  	makePkg("main", f)
	1375  	mainScope := imports["main"].Scope()
	1376  	rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
	1377  	for _, group := range f.Comments {
	1378  		for _, comment := range group.List {
	1379  			// Parse the assertion in the comment.
	1380  			m := rx.FindStringSubmatch(comment.Text)
	1381  			if m == nil {
	1382  				t.Errorf("%s: bad comment: %s",
	1383  					fset.Position(comment.Pos()), comment.Text)
	1384  				continue
	1385  			}
	1386  			name, want := m[1], m[2]
	1387  
	1388  			// Look up the name in the innermost enclosing scope.
	1389  			inner := mainScope.Innermost(comment.Pos())
	1390  			if inner == nil {
	1391  				t.Errorf("%s: at %s: can't find innermost scope",
	1392  					fset.Position(comment.Pos()), comment.Text)
	1393  				continue
	1394  			}
	1395  			got := "undef"
	1396  			if _, obj := inner.LookupParent(name, comment.Pos()); obj != nil {
	1397  				kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
	1398  				got = fmt.Sprintf("%s:%d", kind, fset.Position(obj.Pos()).Line)
	1399  			}
	1400  			if got != want {
	1401  				t.Errorf("%s: at %s: %s resolved to %s, want %s",
	1402  					fset.Position(comment.Pos()), comment.Text, name, got, want)
	1403  			}
	1404  		}
	1405  	}
	1406  
	1407  	// Check that for each referring identifier,
	1408  	// a lookup of its name on the innermost
	1409  	// enclosing scope returns the correct object.
	1410  
	1411  	for id, wantObj := range info.Uses {
	1412  		inner := mainScope.Innermost(id.Pos())
	1413  		if inner == nil {
	1414  			t.Errorf("%s: can't find innermost scope enclosing %q",
	1415  				fset.Position(id.Pos()), id.Name)
	1416  			continue
	1417  		}
	1418  
	1419  		// Exclude selectors and qualified identifiers---lexical
	1420  		// refs only.	(Ideally, we'd see if the AST parent is a
	1421  		// SelectorExpr, but that requires PathEnclosingInterval
	1422  		// from golang.org/x/tools/go/ast/astutil.)
	1423  		if id.Name == "X" {
	1424  			continue
	1425  		}
	1426  
	1427  		_, gotObj := inner.LookupParent(id.Name, id.Pos())
	1428  		if gotObj != wantObj {
	1429  			t.Errorf("%s: got %v, want %v",
	1430  				fset.Position(id.Pos()), gotObj, wantObj)
	1431  			continue
	1432  		}
	1433  	}
	1434  }
	1435  
	1436  func TestConvertibleTo(t *testing.T) {
	1437  	for _, test := range []struct {
	1438  		v, t Type
	1439  		want bool
	1440  	}{
	1441  		{Typ[Int], Typ[Int], true},
	1442  		{Typ[Int], Typ[Float32], true},
	1443  		{newDefined(Typ[Int]), Typ[Int], true},
	1444  		{newDefined(new(Struct)), new(Struct), true},
	1445  		{newDefined(Typ[Int]), new(Struct), false},
	1446  		{Typ[UntypedInt], Typ[Int], true},
	1447  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
	1448  		{NewSlice(Typ[Int]), NewArray(Typ[Int], 10), false},
	1449  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
	1450  		// Untyped string values are not permitted by the spec, so the below
	1451  		// behavior is undefined.
	1452  		{Typ[UntypedString], Typ[String], true},
	1453  	} {
	1454  		if got := ConvertibleTo(test.v, test.t); got != test.want {
	1455  			t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
	1456  		}
	1457  	}
	1458  }
	1459  
	1460  func TestAssignableTo(t *testing.T) {
	1461  	for _, test := range []struct {
	1462  		v, t Type
	1463  		want bool
	1464  	}{
	1465  		{Typ[Int], Typ[Int], true},
	1466  		{Typ[Int], Typ[Float32], false},
	1467  		{newDefined(Typ[Int]), Typ[Int], false},
	1468  		{newDefined(new(Struct)), new(Struct), true},
	1469  		{Typ[UntypedBool], Typ[Bool], true},
	1470  		{Typ[UntypedString], Typ[Bool], false},
	1471  		// Neither untyped string nor untyped numeric assignments arise during
	1472  		// normal type checking, so the below behavior is technically undefined by
	1473  		// the spec.
	1474  		{Typ[UntypedString], Typ[String], true},
	1475  		{Typ[UntypedInt], Typ[Int], true},
	1476  	} {
	1477  		if got := AssignableTo(test.v, test.t); got != test.want {
	1478  			t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
	1479  		}
	1480  	}
	1481  }
	1482  
	1483  func TestIdentical_issue15173(t *testing.T) {
	1484  	// Identical should allow nil arguments and be symmetric.
	1485  	for _, test := range []struct {
	1486  		x, y Type
	1487  		want bool
	1488  	}{
	1489  		{Typ[Int], Typ[Int], true},
	1490  		{Typ[Int], nil, false},
	1491  		{nil, Typ[Int], false},
	1492  		{nil, nil, true},
	1493  	} {
	1494  		if got := Identical(test.x, test.y); got != test.want {
	1495  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
	1496  		}
	1497  	}
	1498  }
	1499  
	1500  func TestIssue15305(t *testing.T) {
	1501  	const src = "package p; func f() int16; var _ = f(undef)"
	1502  	fset := token.NewFileSet()
	1503  	f, err := parser.ParseFile(fset, "issue15305.go", src, 0)
	1504  	if err != nil {
	1505  		t.Fatal(err)
	1506  	}
	1507  	conf := Config{
	1508  		Error: func(err error) {}, // allow errors
	1509  	}
	1510  	info := &Info{
	1511  		Types: make(map[ast.Expr]TypeAndValue),
	1512  	}
	1513  	conf.Check("p", fset, []*ast.File{f}, info) // ignore result
	1514  	for e, tv := range info.Types {
	1515  		if _, ok := e.(*ast.CallExpr); ok {
	1516  			if tv.Type != Typ[Int16] {
	1517  				t.Errorf("CallExpr has type %v, want int16", tv.Type)
	1518  			}
	1519  			return
	1520  		}
	1521  	}
	1522  	t.Errorf("CallExpr has no type")
	1523  }
	1524  
	1525  // TestCompositeLitTypes verifies that Info.Types registers the correct
	1526  // types for composite literal expressions and composite literal type
	1527  // expressions.
	1528  func TestCompositeLitTypes(t *testing.T) {
	1529  	for _, test := range []struct {
	1530  		lit, typ string
	1531  	}{
	1532  		{`[16]byte{}`, `[16]byte`},
	1533  		{`[...]byte{}`, `[0]byte`},								// test for issue #14092
	1534  		{`[...]int{1, 2, 3}`, `[3]int`},					 // test for issue #14092
	1535  		{`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for issue #14092
	1536  		{`[]int{}`, `[]int`},
	1537  		{`map[string]bool{"foo": true}`, `map[string]bool`},
	1538  		{`struct{}{}`, `struct{}`},
	1539  		{`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
	1540  	} {
	1541  		fset := token.NewFileSet()
	1542  		f, err := parser.ParseFile(fset, test.lit, "package p; var _ = "+test.lit, 0)
	1543  		if err != nil {
	1544  			t.Fatalf("%s: %v", test.lit, err)
	1545  		}
	1546  
	1547  		info := &Info{
	1548  			Types: make(map[ast.Expr]TypeAndValue),
	1549  		}
	1550  		if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
	1551  			t.Fatalf("%s: %v", test.lit, err)
	1552  		}
	1553  
	1554  		cmptype := func(x ast.Expr, want string) {
	1555  			tv, ok := info.Types[x]
	1556  			if !ok {
	1557  				t.Errorf("%s: no Types entry found", test.lit)
	1558  				return
	1559  			}
	1560  			if tv.Type == nil {
	1561  				t.Errorf("%s: type is nil", test.lit)
	1562  				return
	1563  			}
	1564  			if got := tv.Type.String(); got != want {
	1565  				t.Errorf("%s: got %v, want %s", test.lit, got, want)
	1566  			}
	1567  		}
	1568  
	1569  		// test type of composite literal expression
	1570  		rhs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0]
	1571  		cmptype(rhs, test.typ)
	1572  
	1573  		// test type of composite literal type expression
	1574  		cmptype(rhs.(*ast.CompositeLit).Type, test.typ)
	1575  	}
	1576  }
	1577  
	1578  // TestObjectParents verifies that objects have parent scopes or not
	1579  // as specified by the Object interface.
	1580  func TestObjectParents(t *testing.T) {
	1581  	const src = `
	1582  package p
	1583  
	1584  const C = 0
	1585  
	1586  type T1 struct {
	1587  	a, b int
	1588  	T2
	1589  }
	1590  
	1591  type T2 interface {
	1592  	im1()
	1593  	im2()
	1594  }
	1595  
	1596  func (T1) m1() {}
	1597  func (*T1) m2() {}
	1598  
	1599  func f(x int) { y := x; print(y) }
	1600  `
	1601  
	1602  	fset := token.NewFileSet()
	1603  	f, err := parser.ParseFile(fset, "src", src, 0)
	1604  	if err != nil {
	1605  		t.Fatal(err)
	1606  	}
	1607  
	1608  	info := &Info{
	1609  		Defs: make(map[*ast.Ident]Object),
	1610  	}
	1611  	if _, err = new(Config).Check("p", fset, []*ast.File{f}, info); err != nil {
	1612  		t.Fatal(err)
	1613  	}
	1614  
	1615  	for ident, obj := range info.Defs {
	1616  		if obj == nil {
	1617  			// only package names and implicit vars have a nil object
	1618  			// (in this test we only need to handle the package name)
	1619  			if ident.Name != "p" {
	1620  				t.Errorf("%v has nil object", ident)
	1621  			}
	1622  			continue
	1623  		}
	1624  
	1625  		// struct fields, type-associated and interface methods
	1626  		// have no parent scope
	1627  		wantParent := true
	1628  		switch obj := obj.(type) {
	1629  		case *Var:
	1630  			if obj.IsField() {
	1631  				wantParent = false
	1632  			}
	1633  		case *Func:
	1634  			if obj.Type().(*Signature).Recv() != nil { // method
	1635  				wantParent = false
	1636  			}
	1637  		}
	1638  
	1639  		gotParent := obj.Parent() != nil
	1640  		switch {
	1641  		case gotParent && !wantParent:
	1642  			t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
	1643  		case !gotParent && wantParent:
	1644  			t.Errorf("%v: no parent found", ident)
	1645  		}
	1646  	}
	1647  }
	1648  
	1649  // TestFailedImport tests that we don't get follow-on errors
	1650  // elsewhere in a package due to failing to import a package.
	1651  func TestFailedImport(t *testing.T) {
	1652  	testenv.MustHaveGoBuild(t)
	1653  
	1654  	const src = `
	1655  package p
	1656  
	1657  import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
	1658  
	1659  const c = foo.C
	1660  type T = foo.T
	1661  var v T = c
	1662  func f(x T) T { return foo.F(x) }
	1663  `
	1664  	fset := token.NewFileSet()
	1665  	f, err := parser.ParseFile(fset, "src", src, 0)
	1666  	if err != nil {
	1667  		t.Fatal(err)
	1668  	}
	1669  	files := []*ast.File{f}
	1670  
	1671  	// type-check using all possible importers
	1672  	for _, compiler := range []string{"gc", "gccgo", "source"} {
	1673  		errcount := 0
	1674  		conf := Config{
	1675  			Error: func(err error) {
	1676  				// we should only see the import error
	1677  				if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
	1678  					t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
	1679  				}
	1680  				errcount++
	1681  			},
	1682  			Importer: importer.For(compiler, nil),
	1683  		}
	1684  
	1685  		info := &Info{
	1686  			Uses: make(map[*ast.Ident]Object),
	1687  		}
	1688  		pkg, _ := conf.Check("p", fset, files, info)
	1689  		if pkg == nil {
	1690  			t.Errorf("for %s importer, type-checking failed to return a package", compiler)
	1691  			continue
	1692  		}
	1693  
	1694  		imports := pkg.Imports()
	1695  		if len(imports) != 1 {
	1696  			t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
	1697  			continue
	1698  		}
	1699  		imp := imports[0]
	1700  		if imp.Name() != "foo" {
	1701  			t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
	1702  			continue
	1703  		}
	1704  
	1705  		// verify that all uses of foo refer to the imported package foo (imp)
	1706  		for ident, obj := range info.Uses {
	1707  			if ident.Name == "foo" {
	1708  				if obj, ok := obj.(*PkgName); ok {
	1709  					if obj.Imported() != imp {
	1710  						t.Errorf("%s resolved to %v; want %v", ident, obj.Imported(), imp)
	1711  					}
	1712  				} else {
	1713  					t.Errorf("%s resolved to %v; want package name", ident, obj)
	1714  				}
	1715  			}
	1716  		}
	1717  	}
	1718  }
	1719  

View as plain text