...

Source file src/cmd/compile/internal/types2/api_test.go

Documentation: cmd/compile/internal/types2

     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 types2_test
     6  
     7  import (
     8  	"cmd/compile/internal/syntax"
     9  	"errors"
    10  	"fmt"
    11  	"internal/goversion"
    12  	"internal/testenv"
    13  	"reflect"
    14  	"regexp"
    15  	"sort"
    16  	"strings"
    17  	"sync"
    18  	"testing"
    19  
    20  	. "cmd/compile/internal/types2"
    21  )
    22  
    23  // nopos indicates an unknown position
    24  var nopos syntax.Pos
    25  
    26  func mustParse(src string) *syntax.File {
    27  	f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), nil, nil, 0)
    28  	if err != nil {
    29  		panic(err) // so we don't need to pass *testing.T
    30  	}
    31  	return f
    32  }
    33  
    34  func typecheck(src string, conf *Config, info *Info) (*Package, error) {
    35  	f := mustParse(src)
    36  	if conf == nil {
    37  		conf = &Config{
    38  			Error:    func(err error) {}, // collect all errors
    39  			Importer: defaultImporter(),
    40  		}
    41  	}
    42  	return conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
    43  }
    44  
    45  func mustTypecheck(src string, conf *Config, info *Info) *Package {
    46  	pkg, err := typecheck(src, conf, info)
    47  	if err != nil {
    48  		panic(err) // so we don't need to pass *testing.T
    49  	}
    50  	return pkg
    51  }
    52  
    53  // pkgName extracts the package name from src, which must contain a package header.
    54  func pkgName(src string) string {
    55  	const kw = "package "
    56  	if i := strings.Index(src, kw); i >= 0 {
    57  		after := src[i+len(kw):]
    58  		n := len(after)
    59  		if i := strings.IndexAny(after, "\n\t ;/"); i >= 0 {
    60  			n = i
    61  		}
    62  		return after[:n]
    63  	}
    64  	panic("missing package header: " + src)
    65  }
    66  
    67  func TestValuesInfo(t *testing.T) {
    68  	var tests = []struct {
    69  		src  string
    70  		expr string // constant expression
    71  		typ  string // constant type
    72  		val  string // constant value
    73  	}{
    74  		{`package a0; const _ = false`, `false`, `untyped bool`, `false`},
    75  		{`package a1; const _ = 0`, `0`, `untyped int`, `0`},
    76  		{`package a2; const _ = 'A'`, `'A'`, `untyped rune`, `65`},
    77  		{`package a3; const _ = 0.`, `0.`, `untyped float`, `0`},
    78  		{`package a4; const _ = 0i`, `0i`, `untyped complex`, `(0 + 0i)`},
    79  		{`package a5; const _ = "foo"`, `"foo"`, `untyped string`, `"foo"`},
    80  
    81  		{`package b0; var _ = false`, `false`, `bool`, `false`},
    82  		{`package b1; var _ = 0`, `0`, `int`, `0`},
    83  		{`package b2; var _ = 'A'`, `'A'`, `rune`, `65`},
    84  		{`package b3; var _ = 0.`, `0.`, `float64`, `0`},
    85  		{`package b4; var _ = 0i`, `0i`, `complex128`, `(0 + 0i)`},
    86  		{`package b5; var _ = "foo"`, `"foo"`, `string`, `"foo"`},
    87  
    88  		{`package c0a; var _ = bool(false)`, `false`, `bool`, `false`},
    89  		{`package c0b; var _ = bool(false)`, `bool(false)`, `bool`, `false`},
    90  		{`package c0c; type T bool; var _ = T(false)`, `T(false)`, `c0c.T`, `false`},
    91  
    92  		{`package c1a; var _ = int(0)`, `0`, `int`, `0`},
    93  		{`package c1b; var _ = int(0)`, `int(0)`, `int`, `0`},
    94  		{`package c1c; type T int; var _ = T(0)`, `T(0)`, `c1c.T`, `0`},
    95  
    96  		{`package c2a; var _ = rune('A')`, `'A'`, `rune`, `65`},
    97  		{`package c2b; var _ = rune('A')`, `rune('A')`, `rune`, `65`},
    98  		{`package c2c; type T rune; var _ = T('A')`, `T('A')`, `c2c.T`, `65`},
    99  
   100  		{`package c3a; var _ = float32(0.)`, `0.`, `float32`, `0`},
   101  		{`package c3b; var _ = float32(0.)`, `float32(0.)`, `float32`, `0`},
   102  		{`package c3c; type T float32; var _ = T(0.)`, `T(0.)`, `c3c.T`, `0`},
   103  
   104  		{`package c4a; var _ = complex64(0i)`, `0i`, `complex64`, `(0 + 0i)`},
   105  		{`package c4b; var _ = complex64(0i)`, `complex64(0i)`, `complex64`, `(0 + 0i)`},
   106  		{`package c4c; type T complex64; var _ = T(0i)`, `T(0i)`, `c4c.T`, `(0 + 0i)`},
   107  
   108  		{`package c5a; var _ = string("foo")`, `"foo"`, `string`, `"foo"`},
   109  		{`package c5b; var _ = string("foo")`, `string("foo")`, `string`, `"foo"`},
   110  		{`package c5c; type T string; var _ = T("foo")`, `T("foo")`, `c5c.T`, `"foo"`},
   111  		{`package c5d; var _ = string(65)`, `65`, `untyped int`, `65`},
   112  		{`package c5e; var _ = string('A')`, `'A'`, `untyped rune`, `65`},
   113  		{`package c5f; type T string; var _ = T('A')`, `'A'`, `untyped rune`, `65`},
   114  
   115  		{`package d0; var _ = []byte("foo")`, `"foo"`, `string`, `"foo"`},
   116  		{`package d1; var _ = []byte(string("foo"))`, `"foo"`, `string`, `"foo"`},
   117  		{`package d2; var _ = []byte(string("foo"))`, `string("foo")`, `string`, `"foo"`},
   118  		{`package d3; type T []byte; var _ = T("foo")`, `"foo"`, `string`, `"foo"`},
   119  
   120  		{`package e0; const _ = float32( 1e-200)`, `float32(1e-200)`, `float32`, `0`},
   121  		{`package e1; const _ = float32(-1e-200)`, `float32(-1e-200)`, `float32`, `0`},
   122  		{`package e2; const _ = float64( 1e-2000)`, `float64(1e-2000)`, `float64`, `0`},
   123  		{`package e3; const _ = float64(-1e-2000)`, `float64(-1e-2000)`, `float64`, `0`},
   124  		{`package e4; const _ = complex64( 1e-200)`, `complex64(1e-200)`, `complex64`, `(0 + 0i)`},
   125  		{`package e5; const _ = complex64(-1e-200)`, `complex64(-1e-200)`, `complex64`, `(0 + 0i)`},
   126  		{`package e6; const _ = complex128( 1e-2000)`, `complex128(1e-2000)`, `complex128`, `(0 + 0i)`},
   127  		{`package e7; const _ = complex128(-1e-2000)`, `complex128(-1e-2000)`, `complex128`, `(0 + 0i)`},
   128  
   129  		{`package f0 ; var _ float32 =  1e-200`, `1e-200`, `float32`, `0`},
   130  		{`package f1 ; var _ float32 = -1e-200`, `-1e-200`, `float32`, `0`},
   131  		{`package f2a; var _ float64 =  1e-2000`, `1e-2000`, `float64`, `0`},
   132  		{`package f3a; var _ float64 = -1e-2000`, `-1e-2000`, `float64`, `0`},
   133  		{`package f2b; var _         =  1e-2000`, `1e-2000`, `float64`, `0`},
   134  		{`package f3b; var _         = -1e-2000`, `-1e-2000`, `float64`, `0`},
   135  		{`package f4 ; var _ complex64  =  1e-200 `, `1e-200`, `complex64`, `(0 + 0i)`},
   136  		{`package f5 ; var _ complex64  = -1e-200 `, `-1e-200`, `complex64`, `(0 + 0i)`},
   137  		{`package f6a; var _ complex128 =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
   138  		{`package f7a; var _ complex128 = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
   139  		{`package f6b; var _            =  1e-2000i`, `1e-2000i`, `complex128`, `(0 + 0i)`},
   140  		{`package f7b; var _            = -1e-2000i`, `-1e-2000i`, `complex128`, `(0 + 0i)`},
   141  
   142  		{`package g0; const (a = len([iota]int{}); b; c); const _ = c`, `c`, `int`, `2`}, // go.dev/issue/22341
   143  		{`package g1; var(j int32; s int; n = 1.0<<s == j)`, `1.0`, `int32`, `1`},        // go.dev/issue/48422
   144  	}
   145  
   146  	for _, test := range tests {
   147  		info := Info{
   148  			Types: make(map[syntax.Expr]TypeAndValue),
   149  		}
   150  		name := mustTypecheck(test.src, nil, &info).Name()
   151  
   152  		// look for expression
   153  		var expr syntax.Expr
   154  		for e := range info.Types {
   155  			if ExprString(e) == test.expr {
   156  				expr = e
   157  				break
   158  			}
   159  		}
   160  		if expr == nil {
   161  			t.Errorf("package %s: no expression found for %s", name, test.expr)
   162  			continue
   163  		}
   164  		tv := info.Types[expr]
   165  
   166  		// check that type is correct
   167  		if got := tv.Type.String(); got != test.typ {
   168  			t.Errorf("package %s: got type %s; want %s", name, got, test.typ)
   169  			continue
   170  		}
   171  
   172  		// if we have a constant, check that value is correct
   173  		if tv.Value != nil {
   174  			if got := tv.Value.ExactString(); got != test.val {
   175  				t.Errorf("package %s: got value %s; want %s", name, got, test.val)
   176  			}
   177  		} else {
   178  			if test.val != "" {
   179  				t.Errorf("package %s: no constant found; want %s", name, test.val)
   180  			}
   181  		}
   182  	}
   183  }
   184  
   185  func TestTypesInfo(t *testing.T) {
   186  	// Test sources that are not expected to typecheck must start with the broken prefix.
   187  	const brokenPkg = "package broken_"
   188  
   189  	var tests = []struct {
   190  		src  string
   191  		expr string // expression
   192  		typ  string // value type
   193  	}{
   194  		// single-valued expressions of untyped constants
   195  		{`package b0; var x interface{} = false`, `false`, `bool`},
   196  		{`package b1; var x interface{} = 0`, `0`, `int`},
   197  		{`package b2; var x interface{} = 0.`, `0.`, `float64`},
   198  		{`package b3; var x interface{} = 0i`, `0i`, `complex128`},
   199  		{`package b4; var x interface{} = "foo"`, `"foo"`, `string`},
   200  
   201  		// uses of nil
   202  		{`package n0; var _ *int = nil`, `nil`, `*int`},
   203  		{`package n1; var _ func() = nil`, `nil`, `func()`},
   204  		{`package n2; var _ []byte = nil`, `nil`, `[]byte`},
   205  		{`package n3; var _ map[int]int = nil`, `nil`, `map[int]int`},
   206  		{`package n4; var _ chan int = nil`, `nil`, `chan int`},
   207  		{`package n5a; var _ interface{} = (*int)(nil)`, `nil`, `*int`},
   208  		{`package n5b; var _ interface{m()} = nil`, `nil`, `interface{m()}`},
   209  		{`package n6; import "unsafe"; var _ unsafe.Pointer = nil`, `nil`, `unsafe.Pointer`},
   210  
   211  		{`package n10; var (x *int; _ = x == nil)`, `nil`, `*int`},
   212  		{`package n11; var (x func(); _ = x == nil)`, `nil`, `func()`},
   213  		{`package n12; var (x []byte; _ = x == nil)`, `nil`, `[]byte`},
   214  		{`package n13; var (x map[int]int; _ = x == nil)`, `nil`, `map[int]int`},
   215  		{`package n14; var (x chan int; _ = x == nil)`, `nil`, `chan int`},
   216  		{`package n15a; var (x interface{}; _ = x == (*int)(nil))`, `nil`, `*int`},
   217  		{`package n15b; var (x interface{m()}; _ = x == nil)`, `nil`, `interface{m()}`},
   218  		{`package n15; import "unsafe"; var (x unsafe.Pointer; _ = x == nil)`, `nil`, `unsafe.Pointer`},
   219  
   220  		{`package n20; var _ = (*int)(nil)`, `nil`, `*int`},
   221  		{`package n21; var _ = (func())(nil)`, `nil`, `func()`},
   222  		{`package n22; var _ = ([]byte)(nil)`, `nil`, `[]byte`},
   223  		{`package n23; var _ = (map[int]int)(nil)`, `nil`, `map[int]int`},
   224  		{`package n24; var _ = (chan int)(nil)`, `nil`, `chan int`},
   225  		{`package n25a; var _ = (interface{})((*int)(nil))`, `nil`, `*int`},
   226  		{`package n25b; var _ = (interface{m()})(nil)`, `nil`, `interface{m()}`},
   227  		{`package n26; import "unsafe"; var _ = unsafe.Pointer(nil)`, `nil`, `unsafe.Pointer`},
   228  
   229  		{`package n30; func f(*int) { f(nil) }`, `nil`, `*int`},
   230  		{`package n31; func f(func()) { f(nil) }`, `nil`, `func()`},
   231  		{`package n32; func f([]byte) { f(nil) }`, `nil`, `[]byte`},
   232  		{`package n33; func f(map[int]int) { f(nil) }`, `nil`, `map[int]int`},
   233  		{`package n34; func f(chan int) { f(nil) }`, `nil`, `chan int`},
   234  		{`package n35a; func f(interface{}) { f((*int)(nil)) }`, `nil`, `*int`},
   235  		{`package n35b; func f(interface{m()}) { f(nil) }`, `nil`, `interface{m()}`},
   236  		{`package n35; import "unsafe"; func f(unsafe.Pointer) { f(nil) }`, `nil`, `unsafe.Pointer`},
   237  
   238  		// comma-ok expressions
   239  		{`package p0; var x interface{}; var _, _ = x.(int)`,
   240  			`x.(int)`,
   241  			`(int, bool)`,
   242  		},
   243  		{`package p1; var x interface{}; func _() { _, _ = x.(int) }`,
   244  			`x.(int)`,
   245  			`(int, bool)`,
   246  		},
   247  		{`package p2a; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
   248  			`m["foo"]`,
   249  			`(complex128, p2a.mybool)`,
   250  		},
   251  		{`package p2b; var m map[string]complex128; var b bool; func _() { _, b = m["foo"] }`,
   252  			`m["foo"]`,
   253  			`(complex128, bool)`,
   254  		},
   255  		{`package p3; var c chan string; var _, _ = <-c`,
   256  			`<-c`,
   257  			`(string, bool)`,
   258  		},
   259  
   260  		// go.dev/issue/6796
   261  		{`package issue6796_a; var x interface{}; var _, _ = (x.(int))`,
   262  			`x.(int)`,
   263  			`(int, bool)`,
   264  		},
   265  		{`package issue6796_b; var c chan string; var _, _ = (<-c)`,
   266  			`(<-c)`,
   267  			`(string, bool)`,
   268  		},
   269  		{`package issue6796_c; var c chan string; var _, _ = (<-c)`,
   270  			`<-c`,
   271  			`(string, bool)`,
   272  		},
   273  		{`package issue6796_d; var c chan string; var _, _ = ((<-c))`,
   274  			`(<-c)`,
   275  			`(string, bool)`,
   276  		},
   277  		{`package issue6796_e; func f(c chan string) { _, _ = ((<-c)) }`,
   278  			`(<-c)`,
   279  			`(string, bool)`,
   280  		},
   281  
   282  		// go.dev/issue/7060
   283  		{`package issue7060_a; var ( m map[int]string; x, ok = m[0] )`,
   284  			`m[0]`,
   285  			`(string, bool)`,
   286  		},
   287  		{`package issue7060_b; var ( m map[int]string; x, ok interface{} = m[0] )`,
   288  			`m[0]`,
   289  			`(string, bool)`,
   290  		},
   291  		{`package issue7060_c; func f(x interface{}, ok bool, m map[int]string) { x, ok = m[0] }`,
   292  			`m[0]`,
   293  			`(string, bool)`,
   294  		},
   295  		{`package issue7060_d; var ( ch chan string; x, ok = <-ch )`,
   296  			`<-ch`,
   297  			`(string, bool)`,
   298  		},
   299  		{`package issue7060_e; var ( ch chan string; x, ok interface{} = <-ch )`,
   300  			`<-ch`,
   301  			`(string, bool)`,
   302  		},
   303  		{`package issue7060_f; func f(x interface{}, ok bool, ch chan string) { x, ok = <-ch }`,
   304  			`<-ch`,
   305  			`(string, bool)`,
   306  		},
   307  
   308  		// go.dev/issue/28277
   309  		{`package issue28277_a; func f(...int)`,
   310  			`...int`,
   311  			`[]int`,
   312  		},
   313  		{`package issue28277_b; func f(a, b int, c ...[]struct{})`,
   314  			`...[]struct{}`,
   315  			`[][]struct{}`,
   316  		},
   317  
   318  		// go.dev/issue/47243
   319  		{`package issue47243_a; var x int32; var _ = x << 3`, `3`, `untyped int`},
   320  		{`package issue47243_b; var x int32; var _ = x << 3.`, `3.`, `untyped float`},
   321  		{`package issue47243_c; var x int32; var _ = 1 << x`, `1 << x`, `int`},
   322  		{`package issue47243_d; var x int32; var _ = 1 << x`, `1`, `int`},
   323  		{`package issue47243_e; var x int32; var _ = 1 << 2`, `1`, `untyped int`},
   324  		{`package issue47243_f; var x int32; var _ = 1 << 2`, `2`, `untyped int`},
   325  		{`package issue47243_g; var x int32; var _ = int(1) << 2`, `2`, `untyped int`},
   326  		{`package issue47243_h; var x int32; var _ = 1 << (2 << x)`, `1`, `int`},
   327  		{`package issue47243_i; var x int32; var _ = 1 << (2 << x)`, `(2 << x)`, `untyped int`},
   328  		{`package issue47243_j; var x int32; var _ = 1 << (2 << x)`, `2`, `untyped int`},
   329  
   330  		// tests for broken code that doesn't type-check
   331  		{brokenPkg + `x0; func _() { var x struct {f string}; x.f := 0 }`, `x.f`, `string`},
   332  		{brokenPkg + `x1; func _() { var z string; type x struct {f string}; y := &x{q: z}}`, `z`, `string`},
   333  		{brokenPkg + `x2; func _() { var a, b string; type x struct {f string}; z := &x{f: a, f: b,}}`, `b`, `string`},
   334  		{brokenPkg + `x3; var x = panic("");`, `panic`, `func(interface{})`},
   335  		{`package x4; func _() { panic("") }`, `panic`, `func(interface{})`},
   336  		{brokenPkg + `x5; func _() { var x map[string][...]int; x = map[string][...]int{"": {1,2,3}} }`, `x`, `map[string]invalid type`},
   337  
   338  		// parameterized functions
   339  		{`package p0; func f[T any](T) {}; var _ = f[int]`, `f`, `func[T any](T)`},
   340  		{`package p1; func f[T any](T) {}; var _ = f[int]`, `f[int]`, `func(int)`},
   341  		{`package p2; func f[T any](T) {}; func _() { f(42) }`, `f`, `func(int)`},
   342  		{`package p3; func f[T any](T) {}; func _() { f[int](42) }`, `f[int]`, `func(int)`},
   343  		{`package p4; func f[T any](T) {}; func _() { f[int](42) }`, `f`, `func[T any](T)`},
   344  		{`package p5; func f[T any](T) {}; func _() { f(42) }`, `f(42)`, `()`},
   345  
   346  		// type parameters
   347  		{`package t0; type t[] int; var _ t`, `t`, `t0.t`}, // t[] is a syntax error that is ignored in this test in favor of t
   348  		{`package t1; type t[P any] int; var _ t[int]`, `t`, `t1.t[P any]`},
   349  		{`package t2; type t[P interface{}] int; var _ t[int]`, `t`, `t2.t[P interface{}]`},
   350  		{`package t3; type t[P, Q interface{}] int; var _ t[int, int]`, `t`, `t3.t[P, Q interface{}]`},
   351  		{brokenPkg + `t4; type t[P, Q interface{ m() }] int; var _ t[int, int]`, `t`, `broken_t4.t[P, Q interface{m()}]`},
   352  
   353  		// instantiated types must be sanitized
   354  		{`package g0; type t[P any] int; var x struct{ f t[int] }; var _ = x.f`, `x.f`, `g0.t[int]`},
   355  
   356  		// go.dev/issue/45096
   357  		{`package issue45096; func _[T interface{ ~int8 | ~int16 | ~int32 }](x T) { _ = x < 0 }`, `0`, `T`},
   358  
   359  		// go.dev/issue/47895
   360  		{`package p; import "unsafe"; type S struct { f int }; var s S; var _ = unsafe.Offsetof(s.f)`, `s.f`, `int`},
   361  
   362  		// go.dev/issue/50093
   363  		{`package u0a; func _[_ interface{int}]() {}`, `int`, `int`},
   364  		{`package u1a; func _[_ interface{~int}]() {}`, `~int`, `~int`},
   365  		{`package u2a; func _[_ interface{int | string}]() {}`, `int | string`, `int | string`},
   366  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string | ~bool`, `int | string | ~bool`},
   367  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `int | string`, `int | string`},
   368  		{`package u3a; func _[_ interface{int | string | ~bool}]() {}`, `~bool`, `~bool`},
   369  		{`package u3a; func _[_ interface{int | string | ~float64|~bool}]() {}`, `int | string | ~float64`, `int | string | ~float64`},
   370  
   371  		{`package u0b; func _[_ int]() {}`, `int`, `int`},
   372  		{`package u1b; func _[_ ~int]() {}`, `~int`, `~int`},
   373  		{`package u2b; func _[_ int | string]() {}`, `int | string`, `int | string`},
   374  		{`package u3b; func _[_ int | string | ~bool]() {}`, `int | string | ~bool`, `int | string | ~bool`},
   375  		{`package u3b; func _[_ int | string | ~bool]() {}`, `int | string`, `int | string`},
   376  		{`package u3b; func _[_ int | string | ~bool]() {}`, `~bool`, `~bool`},
   377  		{`package u3b; func _[_ int | string | ~float64|~bool]() {}`, `int | string | ~float64`, `int | string | ~float64`},
   378  
   379  		{`package u0c; type _ interface{int}`, `int`, `int`},
   380  		{`package u1c; type _ interface{~int}`, `~int`, `~int`},
   381  		{`package u2c; type _ interface{int | string}`, `int | string`, `int | string`},
   382  		{`package u3c; type _ interface{int | string | ~bool}`, `int | string | ~bool`, `int | string | ~bool`},
   383  		{`package u3c; type _ interface{int | string | ~bool}`, `int | string`, `int | string`},
   384  		{`package u3c; type _ interface{int | string | ~bool}`, `~bool`, `~bool`},
   385  		{`package u3c; type _ interface{int | string | ~float64|~bool}`, `int | string | ~float64`, `int | string | ~float64`},
   386  
   387  		// reverse type inference
   388  		{`package r1; var _ func(int) = g; func g[P any](P) {}`, `g`, `func(int)`},
   389  		{`package r2; var _ func(int) = g[int]; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
   390  		{`package r3; var _ func(int) = g[int]; func g[P any](P) {}`, `g[int]`, `func(int)`},
   391  		{`package r4; var _ func(int, string) = g; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
   392  		{`package r5; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
   393  		{`package r6; var _ func(int, string) = g[int]; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
   394  
   395  		{`package s1; func _() { f(g) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func(int)`},
   396  		{`package s2; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g`, `func[P any](P)`}, // go.dev/issues/60212
   397  		{`package s3; func _() { f(g[int]) }; func f(func(int)) {}; func g[P any](P) {}`, `g[int]`, `func(int)`},
   398  		{`package s4; func _() { f(g) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func(int, string)`},
   399  		{`package s5; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
   400  		{`package s6; func _() { f(g[int]) }; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}`, `g[int]`, `func(int, string)`},
   401  
   402  		{`package s7; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `g`, `func(int, int)`},
   403  		{`package s8; func _() { f(g, h) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func(int, string)`},
   404  		{`package s9; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h`, `func[P, Q any](P, Q)`}, // go.dev/issues/60212
   405  		{`package s10; func _() { f(g, h[int]) }; func f[P any](func(int, P), func(P, string)) {}; func g[P any](P, P) {}; func h[P, Q any](P, Q) {}`, `h[int]`, `func(int, string)`},
   406  	}
   407  
   408  	for _, test := range tests {
   409  		info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
   410  		var name string
   411  		if strings.HasPrefix(test.src, brokenPkg) {
   412  			pkg, err := typecheck(test.src, nil, &info)
   413  			if err == nil {
   414  				t.Errorf("package %s: expected to fail but passed", pkg.Name())
   415  				continue
   416  			}
   417  			if pkg != nil {
   418  				name = pkg.Name()
   419  			}
   420  		} else {
   421  			name = mustTypecheck(test.src, nil, &info).Name()
   422  		}
   423  
   424  		// look for expression type
   425  		var typ Type
   426  		for e, tv := range info.Types {
   427  			if ExprString(e) == test.expr {
   428  				typ = tv.Type
   429  				break
   430  			}
   431  		}
   432  		if typ == nil {
   433  			t.Errorf("package %s: no type found for %s", name, test.expr)
   434  			continue
   435  		}
   436  
   437  		// check that type is correct
   438  		if got := typ.String(); got != test.typ {
   439  			t.Errorf("package %s: expr = %s: got %s; want %s", name, test.expr, got, test.typ)
   440  		}
   441  	}
   442  }
   443  
   444  func TestInstanceInfo(t *testing.T) {
   445  	const lib = `package lib
   446  
   447  func F[P any](P) {}
   448  
   449  type T[P any] []P
   450  `
   451  
   452  	type testInst struct {
   453  		name  string
   454  		targs []string
   455  		typ   string
   456  	}
   457  
   458  	var tests = []struct {
   459  		src       string
   460  		instances []testInst // recorded instances in source order
   461  	}{
   462  		{`package p0; func f[T any](T) {}; func _() { f(42) }`,
   463  			[]testInst{{`f`, []string{`int`}, `func(int)`}},
   464  		},
   465  		{`package p1; func f[T any](T) T { panic(0) }; func _() { f('@') }`,
   466  			[]testInst{{`f`, []string{`rune`}, `func(rune) rune`}},
   467  		},
   468  		{`package p2; func f[T any](...T) T { panic(0) }; func _() { f(0i) }`,
   469  			[]testInst{{`f`, []string{`complex128`}, `func(...complex128) complex128`}},
   470  		},
   471  		{`package p3; func f[A, B, C any](A, *B, []C) {}; func _() { f(1.2, new(string), []byte{}) }`,
   472  			[]testInst{{`f`, []string{`float64`, `string`, `byte`}, `func(float64, *string, []byte)`}},
   473  		},
   474  		{`package p4; func f[A, B any](A, *B, ...[]B) {}; func _() { f(1.2, new(byte)) }`,
   475  			[]testInst{{`f`, []string{`float64`, `byte`}, `func(float64, *byte, ...[]byte)`}},
   476  		},
   477  
   478  		{`package s1; func f[T any, P interface{*T}](x T) {}; func _(x string) { f(x) }`,
   479  			[]testInst{{`f`, []string{`string`, `*string`}, `func(x string)`}},
   480  		},
   481  		{`package s2; func f[T any, P interface{*T}](x []T) {}; func _(x []int) { f(x) }`,
   482  			[]testInst{{`f`, []string{`int`, `*int`}, `func(x []int)`}},
   483  		},
   484  		{`package s3; type C[T any] interface{chan<- T}; func f[T any, P C[T]](x []T) {}; func _(x []int) { f(x) }`,
   485  			[]testInst{
   486  				{`C`, []string{`T`}, `interface{chan<- T}`},
   487  				{`f`, []string{`int`, `chan<- int`}, `func(x []int)`},
   488  			},
   489  		},
   490  		{`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) }`,
   491  			[]testInst{
   492  				{`C`, []string{`T`}, `interface{chan<- T}`},
   493  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
   494  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func(x []int)`},
   495  			},
   496  		},
   497  
   498  		{`package t1; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = f[string] }`,
   499  			[]testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
   500  		},
   501  		{`package t2; func f[T any, P interface{*T}]() T { panic(0) }; func _() { _ = (f[string]) }`,
   502  			[]testInst{{`f`, []string{`string`, `*string`}, `func() string`}},
   503  		},
   504  		{`package t3; type C[T any] interface{chan<- T}; func f[T any, P C[T], Q C[[]*P]]() []T { return nil }; func _() { _ = f[int] }`,
   505  			[]testInst{
   506  				{`C`, []string{`T`}, `interface{chan<- T}`},
   507  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
   508  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
   509  			},
   510  		},
   511  		{`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]) }`,
   512  			[]testInst{
   513  				{`C`, []string{`T`}, `interface{chan<- T}`},
   514  				{`C`, []string{`[]*P`}, `interface{chan<- []*P}`},
   515  				{`f`, []string{`int`, `chan<- int`, `chan<- []*chan<- int`}, `func() []int`},
   516  			},
   517  		},
   518  		{`package i0; import "lib"; func _() { lib.F(42) }`,
   519  			[]testInst{{`F`, []string{`int`}, `func(int)`}},
   520  		},
   521  
   522  		{`package duplfunc0; func f[T any](T) {}; func _() { f(42); f("foo"); f[int](3) }`,
   523  			[]testInst{
   524  				{`f`, []string{`int`}, `func(int)`},
   525  				{`f`, []string{`string`}, `func(string)`},
   526  				{`f`, []string{`int`}, `func(int)`},
   527  			},
   528  		},
   529  		{`package duplfunc1; import "lib"; func _() { lib.F(42); lib.F("foo"); lib.F(3) }`,
   530  			[]testInst{
   531  				{`F`, []string{`int`}, `func(int)`},
   532  				{`F`, []string{`string`}, `func(string)`},
   533  				{`F`, []string{`int`}, `func(int)`},
   534  			},
   535  		},
   536  
   537  		{`package type0; type T[P interface{~int}] struct{ x P }; var _ T[int]`,
   538  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
   539  		},
   540  		{`package type1; type T[P interface{~int}] struct{ x P }; var _ (T[int])`,
   541  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
   542  		},
   543  		{`package type2; type T[P interface{~int}] struct{ x P }; var _ T[(int)]`,
   544  			[]testInst{{`T`, []string{`int`}, `struct{x int}`}},
   545  		},
   546  		{`package type3; type T[P1 interface{~[]P2}, P2 any] struct{ x P1; y P2 }; var _ T[[]int, int]`,
   547  			[]testInst{{`T`, []string{`[]int`, `int`}, `struct{x []int; y int}`}},
   548  		},
   549  		{`package type4; import "lib"; var _ lib.T[int]`,
   550  			[]testInst{{`T`, []string{`int`}, `[]int`}},
   551  		},
   552  
   553  		{`package dupltype0; type T[P interface{~int}] struct{ x P }; var x T[int]; var y T[int]`,
   554  			[]testInst{
   555  				{`T`, []string{`int`}, `struct{x int}`},
   556  				{`T`, []string{`int`}, `struct{x int}`},
   557  			},
   558  		},
   559  		{`package dupltype1; type T[P ~int] struct{ x P }; func (r *T[Q]) add(z T[Q]) { r.x += z.x }`,
   560  			[]testInst{
   561  				{`T`, []string{`Q`}, `struct{x Q}`},
   562  				{`T`, []string{`Q`}, `struct{x Q}`},
   563  			},
   564  		},
   565  		{`package dupltype1; import "lib"; var x lib.T[int]; var y lib.T[int]; var z lib.T[string]`,
   566  			[]testInst{
   567  				{`T`, []string{`int`}, `[]int`},
   568  				{`T`, []string{`int`}, `[]int`},
   569  				{`T`, []string{`string`}, `[]string`},
   570  			},
   571  		},
   572  		{`package issue51803; func foo[T any](T) {}; func _() { foo[int]( /* leave arg away on purpose */ ) }`,
   573  			[]testInst{{`foo`, []string{`int`}, `func(int)`}},
   574  		},
   575  
   576  		// reverse type inference
   577  		{`package reverse1a; var f func(int) = g; func g[P any](P) {}`,
   578  			[]testInst{{`g`, []string{`int`}, `func(int)`}},
   579  		},
   580  		{`package reverse1b; func f(func(int)) {}; func g[P any](P) {}; func _() { f(g) }`,
   581  			[]testInst{{`g`, []string{`int`}, `func(int)`}},
   582  		},
   583  		{`package reverse2a; var f func(int, string) = g; func g[P, Q any](P, Q) {}`,
   584  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
   585  		},
   586  		{`package reverse2b; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g) }`,
   587  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
   588  		},
   589  		{`package reverse2c; func f(func(int, string)) {}; func g[P, Q any](P, Q) {}; func _() { f(g[int]) }`,
   590  			[]testInst{{`g`, []string{`int`, `string`}, `func(int, string)`}},
   591  		},
   592  		// reverse3a not possible (cannot assign to generic function outside of argument passing)
   593  		{`package reverse3b; func f[R any](func(int) R) {}; func g[P any](P) string { return "" }; func _() { f(g) }`,
   594  			[]testInst{
   595  				{`f`, []string{`string`}, `func(func(int) string)`},
   596  				{`g`, []string{`int`}, `func(int) string`},
   597  			},
   598  		},
   599  		{`package reverse4a; var _, _ func([]int, *float32) = g, h; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}`,
   600  			[]testInst{
   601  				{`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
   602  				{`h`, []string{`int`}, `func([]int, *float32)`},
   603  			},
   604  		},
   605  		{`package reverse4b; func f(_, _ func([]int, *float32)) {}; func g[P, Q any]([]P, *Q) {}; func h[R any]([]R, *float32) {}; func _() { f(g, h) }`,
   606  			[]testInst{
   607  				{`g`, []string{`int`, `float32`}, `func([]int, *float32)`},
   608  				{`h`, []string{`int`}, `func([]int, *float32)`},
   609  			},
   610  		},
   611  		{`package issue59956; func f(func(int), func(string), func(bool)) {}; func g[P any](P) {}; func _() { f(g, g, g) }`,
   612  			[]testInst{
   613  				{`g`, []string{`int`}, `func(int)`},
   614  				{`g`, []string{`string`}, `func(string)`},
   615  				{`g`, []string{`bool`}, `func(bool)`},
   616  			},
   617  		},
   618  	}
   619  
   620  	for _, test := range tests {
   621  		imports := make(testImporter)
   622  		conf := Config{Importer: imports}
   623  		instMap := make(map[*syntax.Name]Instance)
   624  		useMap := make(map[*syntax.Name]Object)
   625  		makePkg := func(src string) *Package {
   626  			pkg, err := typecheck(src, &conf, &Info{Instances: instMap, Uses: useMap})
   627  			// allow error for issue51803
   628  			if err != nil && (pkg == nil || pkg.Name() != "issue51803") {
   629  				t.Fatal(err)
   630  			}
   631  			imports[pkg.Name()] = pkg
   632  			return pkg
   633  		}
   634  		makePkg(lib)
   635  		pkg := makePkg(test.src)
   636  
   637  		t.Run(pkg.Name(), func(t *testing.T) {
   638  			// Sort instances in source order for stability.
   639  			instances := sortedInstances(instMap)
   640  			if got, want := len(instances), len(test.instances); got != want {
   641  				t.Fatalf("got %d instances, want %d", got, want)
   642  			}
   643  
   644  			// Pairwise compare with the expected instances.
   645  			for ii, inst := range instances {
   646  				var targs []Type
   647  				for i := 0; i < inst.Inst.TypeArgs.Len(); i++ {
   648  					targs = append(targs, inst.Inst.TypeArgs.At(i))
   649  				}
   650  				typ := inst.Inst.Type
   651  
   652  				testInst := test.instances[ii]
   653  				if got := inst.Name.Value; got != testInst.name {
   654  					t.Fatalf("got name %s, want %s", got, testInst.name)
   655  				}
   656  
   657  				if len(targs) != len(testInst.targs) {
   658  					t.Fatalf("got %d type arguments; want %d", len(targs), len(testInst.targs))
   659  				}
   660  				for i, targ := range targs {
   661  					if got := targ.String(); got != testInst.targs[i] {
   662  						t.Errorf("type argument %d: got %s; want %s", i, got, testInst.targs[i])
   663  					}
   664  				}
   665  				if got := typ.Underlying().String(); got != testInst.typ {
   666  					t.Errorf("package %s: got %s; want %s", pkg.Name(), got, testInst.typ)
   667  				}
   668  
   669  				// Verify the invariant that re-instantiating the corresponding generic
   670  				// type with TypeArgs results in an identical instance.
   671  				ptype := useMap[inst.Name].Type()
   672  				lister, _ := ptype.(interface{ TypeParams() *TypeParamList })
   673  				if lister == nil || lister.TypeParams().Len() == 0 {
   674  					t.Fatalf("info.Types[%v] = %v, want parameterized type", inst.Name, ptype)
   675  				}
   676  				inst2, err := Instantiate(nil, ptype, targs, true)
   677  				if err != nil {
   678  					t.Errorf("Instantiate(%v, %v) failed: %v", ptype, targs, err)
   679  				}
   680  				if !Identical(inst.Inst.Type, inst2) {
   681  					t.Errorf("%v and %v are not identical", inst.Inst.Type, inst2)
   682  				}
   683  			}
   684  		})
   685  	}
   686  }
   687  
   688  type recordedInstance struct {
   689  	Name *syntax.Name
   690  	Inst Instance
   691  }
   692  
   693  func sortedInstances(m map[*syntax.Name]Instance) (instances []recordedInstance) {
   694  	for id, inst := range m {
   695  		instances = append(instances, recordedInstance{id, inst})
   696  	}
   697  	sort.Slice(instances, func(i, j int) bool {
   698  		return CmpPos(instances[i].Name.Pos(), instances[j].Name.Pos()) < 0
   699  	})
   700  	return instances
   701  }
   702  
   703  func TestDefsInfo(t *testing.T) {
   704  	var tests = []struct {
   705  		src  string
   706  		obj  string
   707  		want string
   708  	}{
   709  		{`package p0; const x = 42`, `x`, `const p0.x untyped int`},
   710  		{`package p1; const x int = 42`, `x`, `const p1.x int`},
   711  		{`package p2; var x int`, `x`, `var p2.x int`},
   712  		{`package p3; type x int`, `x`, `type p3.x int`},
   713  		{`package p4; func f()`, `f`, `func p4.f()`},
   714  		{`package p5; func f() int { x, _ := 1, 2; return x }`, `_`, `var _ int`},
   715  
   716  		// Tests using generics.
   717  		{`package g0; type x[T any] int`, `x`, `type g0.x[T any] int`},
   718  		{`package g1; func f[T any]() {}`, `f`, `func g1.f[T any]()`},
   719  		{`package g2; type x[T any] int; func (*x[_]) m() {}`, `m`, `func (*g2.x[_]).m()`},
   720  	}
   721  
   722  	for _, test := range tests {
   723  		info := Info{
   724  			Defs: make(map[*syntax.Name]Object),
   725  		}
   726  		name := mustTypecheck(test.src, nil, &info).Name()
   727  
   728  		// find object
   729  		var def Object
   730  		for id, obj := range info.Defs {
   731  			if id.Value == test.obj {
   732  				def = obj
   733  				break
   734  			}
   735  		}
   736  		if def == nil {
   737  			t.Errorf("package %s: %s not found", name, test.obj)
   738  			continue
   739  		}
   740  
   741  		if got := def.String(); got != test.want {
   742  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
   743  		}
   744  	}
   745  }
   746  
   747  func TestUsesInfo(t *testing.T) {
   748  	var tests = []struct {
   749  		src  string
   750  		obj  string
   751  		want string
   752  	}{
   753  		{`package p0; func _() { _ = x }; const x = 42`, `x`, `const p0.x untyped int`},
   754  		{`package p1; func _() { _ = x }; const x int = 42`, `x`, `const p1.x int`},
   755  		{`package p2; func _() { _ = x }; var x int`, `x`, `var p2.x int`},
   756  		{`package p3; func _() { type _ x }; type x int`, `x`, `type p3.x int`},
   757  		{`package p4; func _() { _ = f }; func f()`, `f`, `func p4.f()`},
   758  
   759  		// Tests using generics.
   760  		{`package g0; func _[T any]() { _ = x }; const x = 42`, `x`, `const g0.x untyped int`},
   761  		{`package g1; func _[T any](x T) { }`, `T`, `type parameter T any`},
   762  		{`package g2; type N[A any] int; var _ N[int]`, `N`, `type g2.N[A any] int`},
   763  		{`package g3; type N[A any] int; func (N[_]) m() {}`, `N`, `type g3.N[A any] int`},
   764  
   765  		// Uses of fields are instantiated.
   766  		{`package s1; type N[A any] struct{ a A }; var f = N[int]{}.a`, `a`, `field a int`},
   767  		{`package s1; type N[A any] struct{ a A }; func (r N[B]) m(b B) { r.a = b }`, `a`, `field a B`},
   768  
   769  		// Uses of methods are uses of the instantiated method.
   770  		{`package m0; type N[A any] int; func (r N[B]) m() { r.n() }; func (N[C]) n() {}`, `n`, `func (m0.N[B]).n()`},
   771  		{`package m1; type N[A any] int; func (r N[B]) m() { }; var f = N[int].m`, `m`, `func (m1.N[int]).m()`},
   772  		{`package m2; func _[A any](v interface{ m() A }) { v.m() }`, `m`, `func (interface).m() A`},
   773  		{`package m3; func f[A any]() interface{ m() A } { return nil }; var _ = f[int]().m()`, `m`, `func (interface).m() int`},
   774  		{`package m4; type T[A any] func() interface{ m() A }; var x T[int]; var y = x().m`, `m`, `func (interface).m() int`},
   775  		{`package m5; type T[A any] interface{ m() A }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m5.T[B]).m() B`},
   776  		{`package m6; type T[A any] interface{ m() }; func _[B any](t T[B]) { t.m() }`, `m`, `func (m6.T[B]).m()`},
   777  		{`package m7; type T[A any] interface{ m() A }; func _(t T[int]) { t.m() }`, `m`, `func (m7.T[int]).m() int`},
   778  		{`package m8; type T[A any] interface{ m() }; func _(t T[int]) { t.m() }`, `m`, `func (m8.T[int]).m()`},
   779  		{`package m9; type T[A any] interface{ m() }; func _(t T[int]) { _ = t.m }`, `m`, `func (m9.T[int]).m()`},
   780  		{
   781  			`package m10; type E[A any] interface{ m() }; type T[B any] interface{ E[B]; n() }; func _(t T[int]) { t.m() }`,
   782  			`m`,
   783  			`func (m10.E[int]).m()`,
   784  		},
   785  	}
   786  
   787  	for _, test := range tests {
   788  		info := Info{
   789  			Uses: make(map[*syntax.Name]Object),
   790  		}
   791  		name := mustTypecheck(test.src, nil, &info).Name()
   792  
   793  		// find object
   794  		var use Object
   795  		for id, obj := range info.Uses {
   796  			if id.Value == test.obj {
   797  				if use != nil {
   798  					panic(fmt.Sprintf("multiple uses of %q", id.Value))
   799  				}
   800  				use = obj
   801  			}
   802  		}
   803  		if use == nil {
   804  			t.Errorf("package %s: %s not found", name, test.obj)
   805  			continue
   806  		}
   807  
   808  		if got := use.String(); got != test.want {
   809  			t.Errorf("package %s: got %s; want %s", name, got, test.want)
   810  		}
   811  	}
   812  }
   813  
   814  func TestGenericMethodInfo(t *testing.T) {
   815  	src := `package p
   816  
   817  type N[A any] int
   818  
   819  func (r N[B]) m() { r.m(); r.n() }
   820  
   821  func (r *N[C]) n() {  }
   822  `
   823  	f := mustParse(src)
   824  	info := Info{
   825  		Defs:       make(map[*syntax.Name]Object),
   826  		Uses:       make(map[*syntax.Name]Object),
   827  		Selections: make(map[*syntax.SelectorExpr]*Selection),
   828  	}
   829  	var conf Config
   830  	pkg, err := conf.Check("p", []*syntax.File{f}, &info)
   831  	if err != nil {
   832  		t.Fatal(err)
   833  	}
   834  
   835  	N := pkg.Scope().Lookup("N").Type().(*Named)
   836  
   837  	// Find the generic methods stored on N.
   838  	gm, gn := N.Method(0), N.Method(1)
   839  	if gm.Name() == "n" {
   840  		gm, gn = gn, gm
   841  	}
   842  
   843  	// Collect objects from info.
   844  	var dm, dn *Func   // the declared methods
   845  	var dmm, dmn *Func // the methods used in the body of m
   846  	for _, decl := range f.DeclList {
   847  		fdecl, ok := decl.(*syntax.FuncDecl)
   848  		if !ok {
   849  			continue
   850  		}
   851  		def := info.Defs[fdecl.Name].(*Func)
   852  		switch fdecl.Name.Value {
   853  		case "m":
   854  			dm = def
   855  			syntax.Inspect(fdecl.Body, func(n syntax.Node) bool {
   856  				if call, ok := n.(*syntax.CallExpr); ok {
   857  					sel := call.Fun.(*syntax.SelectorExpr)
   858  					use := info.Uses[sel.Sel].(*Func)
   859  					selection := info.Selections[sel]
   860  					if selection.Kind() != MethodVal {
   861  						t.Errorf("Selection kind = %v, want %v", selection.Kind(), MethodVal)
   862  					}
   863  					if selection.Obj() != use {
   864  						t.Errorf("info.Selections contains %v, want %v", selection.Obj(), use)
   865  					}
   866  					switch sel.Sel.Value {
   867  					case "m":
   868  						dmm = use
   869  					case "n":
   870  						dmn = use
   871  					}
   872  				}
   873  				return true
   874  			})
   875  		case "n":
   876  			dn = def
   877  		}
   878  	}
   879  
   880  	if gm != dm {
   881  		t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
   882  	}
   883  	if gn != dn {
   884  		t.Errorf(`N.Method(...) returns %v for "m", but Info.Defs has %v`, gm, dm)
   885  	}
   886  	if dmm != dm {
   887  		t.Errorf(`Inside "m", r.m uses %v, want the defined func %v`, dmm, dm)
   888  	}
   889  	if dmn == dn {
   890  		t.Errorf(`Inside "m", r.n uses %v, want a func distinct from %v`, dmm, dm)
   891  	}
   892  }
   893  
   894  func TestImplicitsInfo(t *testing.T) {
   895  	testenv.MustHaveGoBuild(t)
   896  
   897  	var tests = []struct {
   898  		src  string
   899  		want string
   900  	}{
   901  		{`package p2; import . "fmt"; var _ = Println`, ""},           // no Implicits entry
   902  		{`package p0; import local "fmt"; var _ = local.Println`, ""}, // no Implicits entry
   903  		{`package p1; import "fmt"; var _ = fmt.Println`, "importSpec: package fmt"},
   904  
   905  		{`package p3; func f(x interface{}) { switch x.(type) { case int: } }`, ""}, // no Implicits entry
   906  		{`package p4; func f(x interface{}) { switch t := x.(type) { case int: _ = t } }`, "caseClause: var t int"},
   907  		{`package p5; func f(x interface{}) { switch t := x.(type) { case int, uint: _ = t } }`, "caseClause: var t interface{}"},
   908  		{`package p6; func f(x interface{}) { switch t := x.(type) { default: _ = t } }`, "caseClause: var t interface{}"},
   909  
   910  		{`package p7; func f(x int) {}`, ""}, // no Implicits entry
   911  		{`package p8; func f(int) {}`, "field: var  int"},
   912  		{`package p9; func f() (complex64) { return 0 }`, "field: var  complex64"},
   913  		{`package p10; type T struct{}; func (*T) f() {}`, "field: var  *p10.T"},
   914  
   915  		// Tests using generics.
   916  		{`package f0; func f[T any](x int) {}`, ""}, // no Implicits entry
   917  		{`package f1; func f[T any](int) {}`, "field: var  int"},
   918  		{`package f2; func f[T any](T) {}`, "field: var  T"},
   919  		{`package f3; func f[T any]() (complex64) { return 0 }`, "field: var  complex64"},
   920  		{`package f4; func f[T any](t T) (T) { return t }`, "field: var  T"},
   921  		{`package t0; type T[A any] struct{}; func (*T[_]) f() {}`, "field: var  *t0.T[_]"},
   922  		{`package t1; type T[A any] struct{}; func _(x interface{}) { switch t := x.(type) { case T[int]: _ = t } }`, "caseClause: var t t1.T[int]"},
   923  		{`package t2; type T[A any] struct{}; func _[P any](x interface{}) { switch t := x.(type) { case T[P]: _ = t } }`, "caseClause: var t t2.T[P]"},
   924  		{`package t3; func _[P any](x interface{}) { switch t := x.(type) { case P: _ = t } }`, "caseClause: var t P"},
   925  	}
   926  
   927  	for _, test := range tests {
   928  		info := Info{
   929  			Implicits: make(map[syntax.Node]Object),
   930  		}
   931  		name := mustTypecheck(test.src, nil, &info).Name()
   932  
   933  		// the test cases expect at most one Implicits entry
   934  		if len(info.Implicits) > 1 {
   935  			t.Errorf("package %s: %d Implicits entries found", name, len(info.Implicits))
   936  			continue
   937  		}
   938  
   939  		// extract Implicits entry, if any
   940  		var got string
   941  		for n, obj := range info.Implicits {
   942  			switch x := n.(type) {
   943  			case *syntax.ImportDecl:
   944  				got = "importSpec"
   945  			case *syntax.CaseClause:
   946  				got = "caseClause"
   947  			case *syntax.Field:
   948  				got = "field"
   949  			default:
   950  				t.Fatalf("package %s: unexpected %T", name, x)
   951  			}
   952  			got += ": " + obj.String()
   953  		}
   954  
   955  		// verify entry
   956  		if got != test.want {
   957  			t.Errorf("package %s: got %q; want %q", name, got, test.want)
   958  		}
   959  	}
   960  }
   961  
   962  func TestPkgNameOf(t *testing.T) {
   963  	testenv.MustHaveGoBuild(t)
   964  
   965  	const src = `
   966  package p
   967  
   968  import (
   969  	. "os"
   970  	_ "io"
   971  	"math"
   972  	"path/filepath"
   973  	snort "sort"
   974  )
   975  
   976  // avoid imported and not used errors
   977  var (
   978  	_ = Open // os.Open
   979  	_ = math.Sin
   980  	_ = filepath.Abs
   981  	_ = snort.Ints
   982  )
   983  `
   984  
   985  	var tests = []struct {
   986  		path string // path string enclosed in "'s
   987  		want string
   988  	}{
   989  		{`"os"`, "."},
   990  		{`"io"`, "_"},
   991  		{`"math"`, "math"},
   992  		{`"path/filepath"`, "filepath"},
   993  		{`"sort"`, "snort"},
   994  	}
   995  
   996  	f := mustParse(src)
   997  	info := Info{
   998  		Defs:      make(map[*syntax.Name]Object),
   999  		Implicits: make(map[syntax.Node]Object),
  1000  	}
  1001  	var conf Config
  1002  	conf.Importer = defaultImporter()
  1003  	_, err := conf.Check("p", []*syntax.File{f}, &info)
  1004  	if err != nil {
  1005  		t.Fatal(err)
  1006  	}
  1007  
  1008  	// map import paths to importDecl
  1009  	imports := make(map[string]*syntax.ImportDecl)
  1010  	for _, d := range f.DeclList {
  1011  		if imp, _ := d.(*syntax.ImportDecl); imp != nil {
  1012  			imports[imp.Path.Value] = imp
  1013  		}
  1014  	}
  1015  
  1016  	for _, test := range tests {
  1017  		imp := imports[test.path]
  1018  		if imp == nil {
  1019  			t.Fatalf("invalid test case: import path %s not found", test.path)
  1020  		}
  1021  		got := info.PkgNameOf(imp)
  1022  		if got == nil {
  1023  			t.Fatalf("import %s: package name not found", test.path)
  1024  		}
  1025  		if got.Name() != test.want {
  1026  			t.Errorf("import %s: got %s; want %s", test.path, got.Name(), test.want)
  1027  		}
  1028  	}
  1029  
  1030  	// test non-existing importDecl
  1031  	if got := info.PkgNameOf(new(syntax.ImportDecl)); got != nil {
  1032  		t.Errorf("got %s for non-existing import declaration", got.Name())
  1033  	}
  1034  }
  1035  
  1036  func predString(tv TypeAndValue) string {
  1037  	var buf strings.Builder
  1038  	pred := func(b bool, s string) {
  1039  		if b {
  1040  			if buf.Len() > 0 {
  1041  				buf.WriteString(", ")
  1042  			}
  1043  			buf.WriteString(s)
  1044  		}
  1045  	}
  1046  
  1047  	pred(tv.IsVoid(), "void")
  1048  	pred(tv.IsType(), "type")
  1049  	pred(tv.IsBuiltin(), "builtin")
  1050  	pred(tv.IsValue() && tv.Value != nil, "const")
  1051  	pred(tv.IsValue() && tv.Value == nil, "value")
  1052  	pred(tv.IsNil(), "nil")
  1053  	pred(tv.Addressable(), "addressable")
  1054  	pred(tv.Assignable(), "assignable")
  1055  	pred(tv.HasOk(), "hasOk")
  1056  
  1057  	if buf.Len() == 0 {
  1058  		return "invalid"
  1059  	}
  1060  	return buf.String()
  1061  }
  1062  
  1063  func TestPredicatesInfo(t *testing.T) {
  1064  	testenv.MustHaveGoBuild(t)
  1065  
  1066  	var tests = []struct {
  1067  		src  string
  1068  		expr string
  1069  		pred string
  1070  	}{
  1071  		// void
  1072  		{`package n0; func f() { f() }`, `f()`, `void`},
  1073  
  1074  		// types
  1075  		{`package t0; type _ int`, `int`, `type`},
  1076  		{`package t1; type _ []int`, `[]int`, `type`},
  1077  		{`package t2; type _ func()`, `func()`, `type`},
  1078  		{`package t3; type _ func(int)`, `int`, `type`},
  1079  		{`package t3; type _ func(...int)`, `...int`, `type`},
  1080  
  1081  		// built-ins
  1082  		{`package b0; var _ = len("")`, `len`, `builtin`},
  1083  		{`package b1; var _ = (len)("")`, `(len)`, `builtin`},
  1084  
  1085  		// constants
  1086  		{`package c0; var _ = 42`, `42`, `const`},
  1087  		{`package c1; var _ = "foo" + "bar"`, `"foo" + "bar"`, `const`},
  1088  		{`package c2; const (i = 1i; _ = i)`, `i`, `const`},
  1089  
  1090  		// values
  1091  		{`package v0; var (a, b int; _ = a + b)`, `a + b`, `value`},
  1092  		{`package v1; var _ = &[]int{1}`, `[]int{…}`, `value`},
  1093  		{`package v2; var _ = func(){}`, `func() {}`, `value`},
  1094  		{`package v4; func f() { _ = f }`, `f`, `value`},
  1095  		{`package v3; var _ *int = nil`, `nil`, `value, nil`},
  1096  		{`package v3; var _ *int = (nil)`, `(nil)`, `value, nil`},
  1097  
  1098  		// addressable (and thus assignable) operands
  1099  		{`package a0; var (x int; _ = x)`, `x`, `value, addressable, assignable`},
  1100  		{`package a1; var (p *int; _ = *p)`, `*p`, `value, addressable, assignable`},
  1101  		{`package a2; var (s []int; _ = s[0])`, `s[0]`, `value, addressable, assignable`},
  1102  		{`package a3; var (s struct{f int}; _ = s.f)`, `s.f`, `value, addressable, assignable`},
  1103  		{`package a4; var (a [10]int; _ = a[0])`, `a[0]`, `value, addressable, assignable`},
  1104  		{`package a5; func _(x int) { _ = x }`, `x`, `value, addressable, assignable`},
  1105  		{`package a6; func _()(x int) { _ = x; return }`, `x`, `value, addressable, assignable`},
  1106  		{`package a7; type T int; func (x T) _() { _ = x }`, `x`, `value, addressable, assignable`},
  1107  		// composite literals are not addressable
  1108  
  1109  		// assignable but not addressable values
  1110  		{`package s0; var (m map[int]int; _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
  1111  		{`package s1; var (m map[int]int; _, _ = m[0])`, `m[0]`, `value, assignable, hasOk`},
  1112  
  1113  		// hasOk expressions
  1114  		{`package k0; var (ch chan int; _ = <-ch)`, `<-ch`, `value, hasOk`},
  1115  		{`package k1; var (ch chan int; _, _ = <-ch)`, `<-ch`, `value, hasOk`},
  1116  
  1117  		// missing entries
  1118  		// - package names are collected in the Uses map
  1119  		// - identifiers being declared are collected in the Defs map
  1120  		{`package m0; import "os"; func _() { _ = os.Stdout }`, `os`, `<missing>`},
  1121  		{`package m1; import p "os"; func _() { _ = p.Stdout }`, `p`, `<missing>`},
  1122  		{`package m2; const c = 0`, `c`, `<missing>`},
  1123  		{`package m3; type T int`, `T`, `<missing>`},
  1124  		{`package m4; var v int`, `v`, `<missing>`},
  1125  		{`package m5; func f() {}`, `f`, `<missing>`},
  1126  		{`package m6; func _(x int) {}`, `x`, `<missing>`},
  1127  		{`package m6; func _()(x int) { return }`, `x`, `<missing>`},
  1128  		{`package m6; type T int; func (x T) _() {}`, `x`, `<missing>`},
  1129  	}
  1130  
  1131  	for _, test := range tests {
  1132  		info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
  1133  		name := mustTypecheck(test.src, nil, &info).Name()
  1134  
  1135  		// look for expression predicates
  1136  		got := "<missing>"
  1137  		for e, tv := range info.Types {
  1138  			//println(name, ExprString(e))
  1139  			if ExprString(e) == test.expr {
  1140  				got = predString(tv)
  1141  				break
  1142  			}
  1143  		}
  1144  
  1145  		if got != test.pred {
  1146  			t.Errorf("package %s: got %s; want %s", name, got, test.pred)
  1147  		}
  1148  	}
  1149  }
  1150  
  1151  func TestScopesInfo(t *testing.T) {
  1152  	testenv.MustHaveGoBuild(t)
  1153  
  1154  	var tests = []struct {
  1155  		src    string
  1156  		scopes []string // list of scope descriptors of the form kind:varlist
  1157  	}{
  1158  		{`package p0`, []string{
  1159  			"file:",
  1160  		}},
  1161  		{`package p1; import ( "fmt"; m "math"; _ "os" ); var ( _ = fmt.Println; _ = m.Pi )`, []string{
  1162  			"file:fmt m",
  1163  		}},
  1164  		{`package p2; func _() {}`, []string{
  1165  			"file:", "func:",
  1166  		}},
  1167  		{`package p3; func _(x, y int) {}`, []string{
  1168  			"file:", "func:x y",
  1169  		}},
  1170  		{`package p4; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
  1171  			"file:", "func:x y z", // redeclaration of x
  1172  		}},
  1173  		{`package p5; func _(x, y int) (u, _ int) { return }`, []string{
  1174  			"file:", "func:u x y",
  1175  		}},
  1176  		{`package p6; func _() { { var x int; _ = x } }`, []string{
  1177  			"file:", "func:", "block:x",
  1178  		}},
  1179  		{`package p7; func _() { if true {} }`, []string{
  1180  			"file:", "func:", "if:", "block:",
  1181  		}},
  1182  		{`package p8; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
  1183  			"file:", "func:", "if:x", "block:y",
  1184  		}},
  1185  		{`package p9; func _() { switch x := 0; x {} }`, []string{
  1186  			"file:", "func:", "switch:x",
  1187  		}},
  1188  		{`package p10; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
  1189  			"file:", "func:", "switch:x", "case:y", "case:",
  1190  		}},
  1191  		{`package p11; func _(t interface{}) { switch t.(type) {} }`, []string{
  1192  			"file:", "func:t", "switch:",
  1193  		}},
  1194  		{`package p12; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
  1195  			"file:", "func:t", "switch:t",
  1196  		}},
  1197  		{`package p13; func _(t interface{}) { switch x := t.(type) { case int: _ = x } }`, []string{
  1198  			"file:", "func:t", "switch:", "case:x", // x implicitly declared
  1199  		}},
  1200  		{`package p14; func _() { select{} }`, []string{
  1201  			"file:", "func:",
  1202  		}},
  1203  		{`package p15; func _(c chan int) { select{ case <-c: } }`, []string{
  1204  			"file:", "func:c", "comm:",
  1205  		}},
  1206  		{`package p16; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
  1207  			"file:", "func:c", "comm:i x",
  1208  		}},
  1209  		{`package p17; func _() { for{} }`, []string{
  1210  			"file:", "func:", "for:", "block:",
  1211  		}},
  1212  		{`package p18; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
  1213  			"file:", "func:n", "for:i", "block:",
  1214  		}},
  1215  		{`package p19; func _(a []int) { for i := range a { _ = i} }`, []string{
  1216  			"file:", "func:a", "for:i", "block:",
  1217  		}},
  1218  		{`package p20; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
  1219  			"file:", "func:a", "for:i x", "block:",
  1220  		}},
  1221  	}
  1222  
  1223  	for _, test := range tests {
  1224  		info := Info{Scopes: make(map[syntax.Node]*Scope)}
  1225  		name := mustTypecheck(test.src, nil, &info).Name()
  1226  
  1227  		// number of scopes must match
  1228  		if len(info.Scopes) != len(test.scopes) {
  1229  			t.Errorf("package %s: got %d scopes; want %d", name, len(info.Scopes), len(test.scopes))
  1230  		}
  1231  
  1232  		// scope descriptions must match
  1233  		for node, scope := range info.Scopes {
  1234  			var kind string
  1235  			switch node.(type) {
  1236  			case *syntax.File:
  1237  				kind = "file"
  1238  			case *syntax.FuncType:
  1239  				kind = "func"
  1240  			case *syntax.BlockStmt:
  1241  				kind = "block"
  1242  			case *syntax.IfStmt:
  1243  				kind = "if"
  1244  			case *syntax.SwitchStmt:
  1245  				kind = "switch"
  1246  			case *syntax.SelectStmt:
  1247  				kind = "select"
  1248  			case *syntax.CaseClause:
  1249  				kind = "case"
  1250  			case *syntax.CommClause:
  1251  				kind = "comm"
  1252  			case *syntax.ForStmt:
  1253  				kind = "for"
  1254  			default:
  1255  				kind = fmt.Sprintf("%T", node)
  1256  			}
  1257  
  1258  			// look for matching scope description
  1259  			desc := kind + ":" + strings.Join(scope.Names(), " ")
  1260  			found := false
  1261  			for _, d := range test.scopes {
  1262  				if desc == d {
  1263  					found = true
  1264  					break
  1265  				}
  1266  			}
  1267  			if !found {
  1268  				t.Errorf("package %s: no matching scope found for %s", name, desc)
  1269  			}
  1270  		}
  1271  	}
  1272  }
  1273  
  1274  func TestInitOrderInfo(t *testing.T) {
  1275  	var tests = []struct {
  1276  		src   string
  1277  		inits []string
  1278  	}{
  1279  		{`package p0; var (x = 1; y = x)`, []string{
  1280  			"x = 1", "y = x",
  1281  		}},
  1282  		{`package p1; var (a = 1; b = 2; c = 3)`, []string{
  1283  			"a = 1", "b = 2", "c = 3",
  1284  		}},
  1285  		{`package p2; var (a, b, c = 1, 2, 3)`, []string{
  1286  			"a = 1", "b = 2", "c = 3",
  1287  		}},
  1288  		{`package p3; var _ = f(); func f() int { return 1 }`, []string{
  1289  			"_ = f()", // blank var
  1290  		}},
  1291  		{`package p4; var (a = 0; x = y; y = z; z = 0)`, []string{
  1292  			"a = 0", "z = 0", "y = z", "x = y",
  1293  		}},
  1294  		{`package p5; var (a, _ = m[0]; m map[int]string)`, []string{
  1295  			"a, _ = m[0]", // blank var
  1296  		}},
  1297  		{`package p6; var a, b = f(); func f() (_, _ int) { return z, z }; var z = 0`, []string{
  1298  			"z = 0", "a, b = f()",
  1299  		}},
  1300  		{`package p7; var (a = func() int { return b }(); b = 1)`, []string{
  1301  			"b = 1", "a = func() int {…}()",
  1302  		}},
  1303  		{`package p8; var (a, b = func() (_, _ int) { return c, c }(); c = 1)`, []string{
  1304  			"c = 1", "a, b = func() (_, _ int) {…}()",
  1305  		}},
  1306  		{`package p9; type T struct{}; func (T) m() int { _ = y; return 0 }; var x, y = T.m, 1`, []string{
  1307  			"y = 1", "x = T.m",
  1308  		}},
  1309  		{`package p10; var (d = c + b; a = 0; b = 0; c = 0)`, []string{
  1310  			"a = 0", "b = 0", "c = 0", "d = c + b",
  1311  		}},
  1312  		{`package p11; var (a = e + c; b = d + c; c = 0; d = 0; e = 0)`, []string{
  1313  			"c = 0", "d = 0", "b = d + c", "e = 0", "a = e + c",
  1314  		}},
  1315  		// emit an initializer for n:1 initializations only once (not for each node
  1316  		// on the lhs which may appear in different order in the dependency graph)
  1317  		{`package p12; var (a = x; b = 0; x, y = m[0]; m map[int]int)`, []string{
  1318  			"b = 0", "x, y = m[0]", "a = x",
  1319  		}},
  1320  		// test case from spec section on package initialization
  1321  		{`package p12
  1322  
  1323  		var (
  1324  			a = c + b
  1325  			b = f()
  1326  			c = f()
  1327  			d = 3
  1328  		)
  1329  
  1330  		func f() int {
  1331  			d++
  1332  			return d
  1333  		}`, []string{
  1334  			"d = 3", "b = f()", "c = f()", "a = c + b",
  1335  		}},
  1336  		// test case for go.dev/issue/7131
  1337  		{`package main
  1338  
  1339  		var counter int
  1340  		func next() int { counter++; return counter }
  1341  
  1342  		var _ = makeOrder()
  1343  		func makeOrder() []int { return []int{f, b, d, e, c, a} }
  1344  
  1345  		var a       = next()
  1346  		var b, c    = next(), next()
  1347  		var d, e, f = next(), next(), next()
  1348  		`, []string{
  1349  			"a = next()", "b = next()", "c = next()", "d = next()", "e = next()", "f = next()", "_ = makeOrder()",
  1350  		}},
  1351  		// test case for go.dev/issue/10709
  1352  		{`package p13
  1353  
  1354  		var (
  1355  		    v = t.m()
  1356  		    t = makeT(0)
  1357  		)
  1358  
  1359  		type T struct{}
  1360  
  1361  		func (T) m() int { return 0 }
  1362  
  1363  		func makeT(n int) T {
  1364  		    if n > 0 {
  1365  		        return makeT(n-1)
  1366  		    }
  1367  		    return T{}
  1368  		}`, []string{
  1369  			"t = makeT(0)", "v = t.m()",
  1370  		}},
  1371  		// test case for go.dev/issue/10709: same as test before, but variable decls swapped
  1372  		{`package p14
  1373  
  1374  		var (
  1375  		    t = makeT(0)
  1376  		    v = t.m()
  1377  		)
  1378  
  1379  		type T struct{}
  1380  
  1381  		func (T) m() int { return 0 }
  1382  
  1383  		func makeT(n int) T {
  1384  		    if n > 0 {
  1385  		        return makeT(n-1)
  1386  		    }
  1387  		    return T{}
  1388  		}`, []string{
  1389  			"t = makeT(0)", "v = t.m()",
  1390  		}},
  1391  		// another candidate possibly causing problems with go.dev/issue/10709
  1392  		{`package p15
  1393  
  1394  		var y1 = f1()
  1395  
  1396  		func f1() int { return g1() }
  1397  		func g1() int { f1(); return x1 }
  1398  
  1399  		var x1 = 0
  1400  
  1401  		var y2 = f2()
  1402  
  1403  		func f2() int { return g2() }
  1404  		func g2() int { return x2 }
  1405  
  1406  		var x2 = 0`, []string{
  1407  			"x1 = 0", "y1 = f1()", "x2 = 0", "y2 = f2()",
  1408  		}},
  1409  	}
  1410  
  1411  	for _, test := range tests {
  1412  		info := Info{}
  1413  		name := mustTypecheck(test.src, nil, &info).Name()
  1414  
  1415  		// number of initializers must match
  1416  		if len(info.InitOrder) != len(test.inits) {
  1417  			t.Errorf("package %s: got %d initializers; want %d", name, len(info.InitOrder), len(test.inits))
  1418  			continue
  1419  		}
  1420  
  1421  		// initializers must match
  1422  		for i, want := range test.inits {
  1423  			got := info.InitOrder[i].String()
  1424  			if got != want {
  1425  				t.Errorf("package %s, init %d: got %s; want %s", name, i, got, want)
  1426  				continue
  1427  			}
  1428  		}
  1429  	}
  1430  }
  1431  
  1432  func TestMultiFileInitOrder(t *testing.T) {
  1433  	fileA := mustParse(`package main; var a = 1`)
  1434  	fileB := mustParse(`package main; var b = 2`)
  1435  
  1436  	// The initialization order must not depend on the parse
  1437  	// order of the files, only on the presentation order to
  1438  	// the type-checker.
  1439  	for _, test := range []struct {
  1440  		files []*syntax.File
  1441  		want  string
  1442  	}{
  1443  		{[]*syntax.File{fileA, fileB}, "[a = 1 b = 2]"},
  1444  		{[]*syntax.File{fileB, fileA}, "[b = 2 a = 1]"},
  1445  	} {
  1446  		var info Info
  1447  		if _, err := new(Config).Check("main", test.files, &info); err != nil {
  1448  			t.Fatal(err)
  1449  		}
  1450  		if got := fmt.Sprint(info.InitOrder); got != test.want {
  1451  			t.Fatalf("got %s; want %s", got, test.want)
  1452  		}
  1453  	}
  1454  }
  1455  
  1456  func TestFiles(t *testing.T) {
  1457  	var sources = []string{
  1458  		"package p; type T struct{}; func (T) m1() {}",
  1459  		"package p; func (T) m2() {}; var x interface{ m1(); m2() } = T{}",
  1460  		"package p; func (T) m3() {}; var y interface{ m1(); m2(); m3() } = T{}",
  1461  		"package p",
  1462  	}
  1463  
  1464  	var conf Config
  1465  	pkg := NewPackage("p", "p")
  1466  	var info Info
  1467  	check := NewChecker(&conf, pkg, &info)
  1468  
  1469  	for _, src := range sources {
  1470  		if err := check.Files([]*syntax.File{mustParse(src)}); err != nil {
  1471  			t.Error(err)
  1472  		}
  1473  	}
  1474  
  1475  	// check InitOrder is [x y]
  1476  	var vars []string
  1477  	for _, init := range info.InitOrder {
  1478  		for _, v := range init.Lhs {
  1479  			vars = append(vars, v.Name())
  1480  		}
  1481  	}
  1482  	if got, want := fmt.Sprint(vars), "[x y]"; got != want {
  1483  		t.Errorf("InitOrder == %s, want %s", got, want)
  1484  	}
  1485  }
  1486  
  1487  type testImporter map[string]*Package
  1488  
  1489  func (m testImporter) Import(path string) (*Package, error) {
  1490  	if pkg := m[path]; pkg != nil {
  1491  		return pkg, nil
  1492  	}
  1493  	return nil, fmt.Errorf("package %q not found", path)
  1494  }
  1495  
  1496  func TestSelection(t *testing.T) {
  1497  	selections := make(map[*syntax.SelectorExpr]*Selection)
  1498  
  1499  	imports := make(testImporter)
  1500  	conf := Config{Importer: imports}
  1501  	makePkg := func(path, src string) {
  1502  		pkg := mustTypecheck(src, &conf, &Info{Selections: selections})
  1503  		imports[path] = pkg
  1504  	}
  1505  
  1506  	const libSrc = `
  1507  package lib
  1508  type T float64
  1509  const C T = 3
  1510  var V T
  1511  func F() {}
  1512  func (T) M() {}
  1513  `
  1514  	const mainSrc = `
  1515  package main
  1516  import "lib"
  1517  
  1518  type A struct {
  1519  	*B
  1520  	C
  1521  }
  1522  
  1523  type B struct {
  1524  	b int
  1525  }
  1526  
  1527  func (B) f(int)
  1528  
  1529  type C struct {
  1530  	c int
  1531  }
  1532  
  1533  type G[P any] struct {
  1534  	p P
  1535  }
  1536  
  1537  func (G[P]) m(P) {}
  1538  
  1539  var Inst G[int]
  1540  
  1541  func (C) g()
  1542  func (*C) h()
  1543  
  1544  func main() {
  1545  	// qualified identifiers
  1546  	var _ lib.T
  1547  	_ = lib.C
  1548  	_ = lib.F
  1549  	_ = lib.V
  1550  	_ = lib.T.M
  1551  
  1552  	// fields
  1553  	_ = A{}.B
  1554  	_ = new(A).B
  1555  
  1556  	_ = A{}.C
  1557  	_ = new(A).C
  1558  
  1559  	_ = A{}.b
  1560  	_ = new(A).b
  1561  
  1562  	_ = A{}.c
  1563  	_ = new(A).c
  1564  
  1565  	_ = Inst.p
  1566  	_ = G[string]{}.p
  1567  
  1568  	// methods
  1569  	_ = A{}.f
  1570  	_ = new(A).f
  1571  	_ = A{}.g
  1572  	_ = new(A).g
  1573  	_ = new(A).h
  1574  
  1575  	_ = B{}.f
  1576  	_ = new(B).f
  1577  
  1578  	_ = C{}.g
  1579  	_ = new(C).g
  1580  	_ = new(C).h
  1581  	_ = Inst.m
  1582  
  1583  	// method expressions
  1584  	_ = A.f
  1585  	_ = (*A).f
  1586  	_ = B.f
  1587  	_ = (*B).f
  1588  	_ = G[string].m
  1589  }`
  1590  
  1591  	wantOut := map[string][2]string{
  1592  		"lib.T.M": {"method expr (lib.T) M(lib.T)", ".[0]"},
  1593  
  1594  		"A{}.B":    {"field (main.A) B *main.B", ".[0]"},
  1595  		"new(A).B": {"field (*main.A) B *main.B", "->[0]"},
  1596  		"A{}.C":    {"field (main.A) C main.C", ".[1]"},
  1597  		"new(A).C": {"field (*main.A) C main.C", "->[1]"},
  1598  		"A{}.b":    {"field (main.A) b int", "->[0 0]"},
  1599  		"new(A).b": {"field (*main.A) b int", "->[0 0]"},
  1600  		"A{}.c":    {"field (main.A) c int", ".[1 0]"},
  1601  		"new(A).c": {"field (*main.A) c int", "->[1 0]"},
  1602  		"Inst.p":   {"field (main.G[int]) p int", ".[0]"},
  1603  
  1604  		"A{}.f":    {"method (main.A) f(int)", "->[0 0]"},
  1605  		"new(A).f": {"method (*main.A) f(int)", "->[0 0]"},
  1606  		"A{}.g":    {"method (main.A) g()", ".[1 0]"},
  1607  		"new(A).g": {"method (*main.A) g()", "->[1 0]"},
  1608  		"new(A).h": {"method (*main.A) h()", "->[1 1]"}, // TODO(gri) should this report .[1 1] ?
  1609  		"B{}.f":    {"method (main.B) f(int)", ".[0]"},
  1610  		"new(B).f": {"method (*main.B) f(int)", "->[0]"},
  1611  		"C{}.g":    {"method (main.C) g()", ".[0]"},
  1612  		"new(C).g": {"method (*main.C) g()", "->[0]"},
  1613  		"new(C).h": {"method (*main.C) h()", "->[1]"}, // TODO(gri) should this report .[1] ?
  1614  		"Inst.m":   {"method (main.G[int]) m(int)", ".[0]"},
  1615  
  1616  		"A.f":           {"method expr (main.A) f(main.A, int)", "->[0 0]"},
  1617  		"(*A).f":        {"method expr (*main.A) f(*main.A, int)", "->[0 0]"},
  1618  		"B.f":           {"method expr (main.B) f(main.B, int)", ".[0]"},
  1619  		"(*B).f":        {"method expr (*main.B) f(*main.B, int)", "->[0]"},
  1620  		"G[string].m":   {"method expr (main.G[string]) m(main.G[string], string)", ".[0]"},
  1621  		"G[string]{}.p": {"field (main.G[string]) p string", ".[0]"},
  1622  	}
  1623  
  1624  	makePkg("lib", libSrc)
  1625  	makePkg("main", mainSrc)
  1626  
  1627  	for e, sel := range selections {
  1628  		_ = sel.String() // assertion: must not panic
  1629  
  1630  		start := indexFor(mainSrc, syntax.StartPos(e))
  1631  		end := indexFor(mainSrc, syntax.EndPos(e))
  1632  		segment := mainSrc[start:end] // (all SelectorExprs are in main, not lib)
  1633  
  1634  		direct := "."
  1635  		if sel.Indirect() {
  1636  			direct = "->"
  1637  		}
  1638  		got := [2]string{
  1639  			sel.String(),
  1640  			fmt.Sprintf("%s%v", direct, sel.Index()),
  1641  		}
  1642  		want := wantOut[segment]
  1643  		if want != got {
  1644  			t.Errorf("%s: got %q; want %q", segment, got, want)
  1645  		}
  1646  		delete(wantOut, segment)
  1647  
  1648  		// We must explicitly assert properties of the
  1649  		// Signature's receiver since it doesn't participate
  1650  		// in Identical() or String().
  1651  		sig, _ := sel.Type().(*Signature)
  1652  		if sel.Kind() == MethodVal {
  1653  			got := sig.Recv().Type()
  1654  			want := sel.Recv()
  1655  			if !Identical(got, want) {
  1656  				t.Errorf("%s: Recv() = %s, want %s", segment, got, want)
  1657  			}
  1658  		} else if sig != nil && sig.Recv() != nil {
  1659  			t.Errorf("%s: signature has receiver %s", sig, sig.Recv().Type())
  1660  		}
  1661  	}
  1662  	// Assert that all wantOut entries were used exactly once.
  1663  	for segment := range wantOut {
  1664  		t.Errorf("no syntax.Selection found with syntax %q", segment)
  1665  	}
  1666  }
  1667  
  1668  // indexFor returns the index into s corresponding to the position pos.
  1669  func indexFor(s string, pos syntax.Pos) int {
  1670  	i, line := 0, 1 // string index and corresponding line
  1671  	target := int(pos.Line())
  1672  	for line < target && i < len(s) {
  1673  		if s[i] == '\n' {
  1674  			line++
  1675  		}
  1676  		i++
  1677  	}
  1678  	return i + int(pos.Col()-1) // columns are 1-based
  1679  }
  1680  
  1681  func TestIssue8518(t *testing.T) {
  1682  	imports := make(testImporter)
  1683  	conf := Config{
  1684  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
  1685  		Importer: imports,
  1686  	}
  1687  	makePkg := func(path, src string) {
  1688  		imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
  1689  	}
  1690  
  1691  	const libSrc = `
  1692  package a
  1693  import "missing"
  1694  const C1 = foo
  1695  const C2 = missing.C
  1696  `
  1697  
  1698  	const mainSrc = `
  1699  package main
  1700  import "a"
  1701  var _ = a.C1
  1702  var _ = a.C2
  1703  `
  1704  
  1705  	makePkg("a", libSrc)
  1706  	makePkg("main", mainSrc) // don't crash when type-checking this package
  1707  }
  1708  
  1709  func TestIssue59603(t *testing.T) {
  1710  	imports := make(testImporter)
  1711  	conf := Config{
  1712  		Error:    func(err error) { t.Log(err) }, // don't exit after first error
  1713  		Importer: imports,
  1714  	}
  1715  	makePkg := func(path, src string) {
  1716  		imports[path], _ = conf.Check(path, []*syntax.File{mustParse(src)}, nil) // errors logged via conf.Error
  1717  	}
  1718  
  1719  	const libSrc = `
  1720  package a
  1721  const C = foo
  1722  `
  1723  
  1724  	const mainSrc = `
  1725  package main
  1726  import "a"
  1727  const _ = a.C
  1728  `
  1729  
  1730  	makePkg("a", libSrc)
  1731  	makePkg("main", mainSrc) // don't crash when type-checking this package
  1732  }
  1733  
  1734  func TestLookupFieldOrMethodOnNil(t *testing.T) {
  1735  	// LookupFieldOrMethod on a nil type is expected to produce a run-time panic.
  1736  	defer func() {
  1737  		const want = "LookupFieldOrMethod on nil type"
  1738  		p := recover()
  1739  		if s, ok := p.(string); !ok || s != want {
  1740  			t.Fatalf("got %v, want %s", p, want)
  1741  		}
  1742  	}()
  1743  	LookupFieldOrMethod(nil, false, nil, "")
  1744  }
  1745  
  1746  func TestLookupFieldOrMethod(t *testing.T) {
  1747  	// Test cases assume a lookup of the form a.f or x.f, where a stands for an
  1748  	// addressable value, and x for a non-addressable value (even though a variable
  1749  	// for ease of test case writing).
  1750  	var tests = []struct {
  1751  		src      string
  1752  		found    bool
  1753  		index    []int
  1754  		indirect bool
  1755  	}{
  1756  		// field lookups
  1757  		{"var x T; type T struct{}", false, nil, false},
  1758  		{"var x T; type T struct{ f int }", true, []int{0}, false},
  1759  		{"var x T; type T struct{ a, b, f, c int }", true, []int{2}, false},
  1760  
  1761  		// field lookups on a generic type
  1762  		{"var x T[int]; type T[P any] struct{}", false, nil, false},
  1763  		{"var x T[int]; type T[P any] struct{ f P }", true, []int{0}, false},
  1764  		{"var x T[int]; type T[P any] struct{ a, b, f, c P }", true, []int{2}, false},
  1765  
  1766  		// method lookups
  1767  		{"var a T; type T struct{}; func (T) f() {}", true, []int{0}, false},
  1768  		{"var a *T; type T struct{}; func (T) f() {}", true, []int{0}, true},
  1769  		{"var a T; type T struct{}; func (*T) f() {}", true, []int{0}, false},
  1770  		{"var a *T; type T struct{}; func (*T) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
  1771  
  1772  		// method lookups on a generic type
  1773  		{"var a T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, false},
  1774  		{"var a *T[int]; type T[P any] struct{}; func (T[P]) f() {}", true, []int{0}, true},
  1775  		{"var a T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, false},
  1776  		{"var a *T[int]; type T[P any] struct{}; func (*T[P]) f() {}", true, []int{0}, true}, // TODO(gri) should this report indirect = false?
  1777  
  1778  		// collisions
  1779  		{"type ( E1 struct{ f int }; E2 struct{ f int }; x struct{ E1; *E2 })", false, []int{1, 0}, false},
  1780  		{"type ( E1 struct{ f int }; E2 struct{}; x struct{ E1; *E2 }); func (E2) f() {}", false, []int{1, 0}, false},
  1781  
  1782  		// collisions on a generic type
  1783  		{"type ( E1[P any] struct{ f P }; E2[P any] struct{ f P }; x struct{ E1[int]; *E2[int] })", false, []int{1, 0}, false},
  1784  		{"type ( E1[P any] struct{ f P }; E2[P any] struct{}; x struct{ E1[int]; *E2[int] }); func (E2[P]) f() {}", false, []int{1, 0}, false},
  1785  
  1786  		// outside methodset
  1787  		// (*T).f method exists, but value of type T is not addressable
  1788  		{"var x T; type T struct{}; func (*T) f() {}", false, nil, true},
  1789  
  1790  		// outside method set of a generic type
  1791  		{"var x T[int]; type T[P any] struct{}; func (*T[P]) f() {}", false, nil, true},
  1792  
  1793  		// recursive generic types; see go.dev/issue/52715
  1794  		{"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (N[P]) f() {}", true, []int{0, 0}, true},
  1795  		{"var a T[int]; type ( T[P any] struct { *N[P] }; N[P any] struct { *T[P] } ); func (T[P]) f() {}", true, []int{0}, false},
  1796  	}
  1797  
  1798  	for _, test := range tests {
  1799  		pkg := mustTypecheck("package p;"+test.src, nil, nil)
  1800  
  1801  		obj := pkg.Scope().Lookup("a")
  1802  		if obj == nil {
  1803  			if obj = pkg.Scope().Lookup("x"); obj == nil {
  1804  				t.Errorf("%s: incorrect test case - no object a or x", test.src)
  1805  				continue
  1806  			}
  1807  		}
  1808  
  1809  		f, index, indirect := LookupFieldOrMethod(obj.Type(), obj.Name() == "a", pkg, "f")
  1810  		if (f != nil) != test.found {
  1811  			if f == nil {
  1812  				t.Errorf("%s: got no object; want one", test.src)
  1813  			} else {
  1814  				t.Errorf("%s: got object = %v; want none", test.src, f)
  1815  			}
  1816  		}
  1817  		if !sameSlice(index, test.index) {
  1818  			t.Errorf("%s: got index = %v; want %v", test.src, index, test.index)
  1819  		}
  1820  		if indirect != test.indirect {
  1821  			t.Errorf("%s: got indirect = %v; want %v", test.src, indirect, test.indirect)
  1822  		}
  1823  	}
  1824  }
  1825  
  1826  // Test for go.dev/issue/52715
  1827  func TestLookupFieldOrMethod_RecursiveGeneric(t *testing.T) {
  1828  	const src = `
  1829  package pkg
  1830  
  1831  type Tree[T any] struct {
  1832  	*Node[T]
  1833  }
  1834  
  1835  func (*Tree[R]) N(r R) R { return r }
  1836  
  1837  type Node[T any] struct {
  1838  	*Tree[T]
  1839  }
  1840  
  1841  type Instance = *Tree[int]
  1842  `
  1843  
  1844  	f := mustParse(src)
  1845  	pkg := NewPackage("pkg", f.PkgName.Value)
  1846  	if err := NewChecker(nil, pkg, nil).Files([]*syntax.File{f}); err != nil {
  1847  		panic(err)
  1848  	}
  1849  
  1850  	T := pkg.Scope().Lookup("Instance").Type()
  1851  	_, _, _ = LookupFieldOrMethod(T, false, pkg, "M") // verify that LookupFieldOrMethod terminates
  1852  }
  1853  
  1854  func sameSlice(a, b []int) bool {
  1855  	if len(a) != len(b) {
  1856  		return false
  1857  	}
  1858  	for i, x := range a {
  1859  		if x != b[i] {
  1860  			return false
  1861  		}
  1862  	}
  1863  	return true
  1864  }
  1865  
  1866  // TestScopeLookupParent ensures that (*Scope).LookupParent returns
  1867  // the correct result at various positions within the source.
  1868  func TestScopeLookupParent(t *testing.T) {
  1869  	imports := make(testImporter)
  1870  	conf := Config{
  1871  		Importer:    imports,
  1872  		EnableAlias: true, // must match default Universe.Lookup behavior
  1873  	}
  1874  	var info Info
  1875  	makePkg := func(path, src string) {
  1876  		var err error
  1877  		imports[path], err = conf.Check(path, []*syntax.File{mustParse(src)}, &info)
  1878  		if err != nil {
  1879  			t.Fatal(err)
  1880  		}
  1881  	}
  1882  
  1883  	makePkg("lib", "package lib; var X int")
  1884  	// Each /*name=kind:line*/ comment makes the test look up the
  1885  	// name at that point and checks that it resolves to a decl of
  1886  	// the specified kind and line number.  "undef" means undefined.
  1887  	mainSrc := `
  1888  /*lib=pkgname:5*/ /*X=var:1*/ /*Pi=const:8*/ /*T=typename:9*/ /*Y=var:10*/ /*F=func:12*/
  1889  package main
  1890  
  1891  import "lib"
  1892  import . "lib"
  1893  
  1894  const Pi = 3.1415
  1895  type T struct{}
  1896  var Y, _ = lib.X, X
  1897  
  1898  func F[T *U, U any](param1, param2 int) /*param1=undef*/ (res1 /*res1=undef*/, res2 int) /*param1=var:12*/ /*res1=var:12*/ /*U=typename:12*/ {
  1899  	const pi, e = 3.1415, /*pi=undef*/ 2.71828 /*pi=const:13*/ /*e=const:13*/
  1900  	type /*t=undef*/ t /*t=typename:14*/ *t
  1901  	print(Y) /*Y=var:10*/
  1902  	x, Y := Y, /*x=undef*/ /*Y=var:10*/ Pi /*x=var:16*/ /*Y=var:16*/ ; _ = x; _ = Y
  1903  	var F = /*F=func:12*/ F[*int, int] /*F=var:17*/ ; _ = F
  1904  
  1905  	var a []int
  1906  	for i, x := range a /*i=undef*/ /*x=var:16*/ { _ = i; _ = x }
  1907  
  1908  	var i interface{}
  1909  	switch y := i.(type) { /*y=undef*/
  1910  	case /*y=undef*/ int /*y=var:23*/ :
  1911  	case float32, /*y=undef*/ float64 /*y=var:23*/ :
  1912  	default /*y=var:23*/:
  1913  		println(y)
  1914  	}
  1915  	/*y=undef*/
  1916  
  1917          switch int := i.(type) {
  1918          case /*int=typename:0*/ int /*int=var:31*/ :
  1919          	println(int)
  1920          default /*int=var:31*/ :
  1921          }
  1922  
  1923  	_ = param1
  1924  	_ = res1
  1925  	return
  1926  }
  1927  /*main=undef*/
  1928  `
  1929  
  1930  	info.Uses = make(map[*syntax.Name]Object)
  1931  	makePkg("main", mainSrc)
  1932  	mainScope := imports["main"].Scope()
  1933  
  1934  	rx := regexp.MustCompile(`^/\*(\w*)=([\w:]*)\*/$`)
  1935  
  1936  	base := syntax.NewFileBase("main")
  1937  	syntax.CommentsDo(strings.NewReader(mainSrc), func(line, col uint, text string) {
  1938  		pos := syntax.MakePos(base, line, col)
  1939  
  1940  		// Syntax errors are not comments.
  1941  		if text[0] != '/' {
  1942  			t.Errorf("%s: %s", pos, text)
  1943  			return
  1944  		}
  1945  
  1946  		// Parse the assertion in the comment.
  1947  		m := rx.FindStringSubmatch(text)
  1948  		if m == nil {
  1949  			t.Errorf("%s: bad comment: %s", pos, text)
  1950  			return
  1951  		}
  1952  		name, want := m[1], m[2]
  1953  
  1954  		// Look up the name in the innermost enclosing scope.
  1955  		inner := mainScope.Innermost(pos)
  1956  		if inner == nil {
  1957  			t.Errorf("%s: at %s: can't find innermost scope", pos, text)
  1958  			return
  1959  		}
  1960  		got := "undef"
  1961  		if _, obj := inner.LookupParent(name, pos); obj != nil {
  1962  			kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types2."))
  1963  			got = fmt.Sprintf("%s:%d", kind, obj.Pos().Line())
  1964  		}
  1965  		if got != want {
  1966  			t.Errorf("%s: at %s: %s resolved to %s, want %s", pos, text, name, got, want)
  1967  		}
  1968  	})
  1969  
  1970  	// Check that for each referring identifier,
  1971  	// a lookup of its name on the innermost
  1972  	// enclosing scope returns the correct object.
  1973  
  1974  	for id, wantObj := range info.Uses {
  1975  		inner := mainScope.Innermost(id.Pos())
  1976  		if inner == nil {
  1977  			t.Errorf("%s: can't find innermost scope enclosing %q", id.Pos(), id.Value)
  1978  			continue
  1979  		}
  1980  
  1981  		// Exclude selectors and qualified identifiers---lexical
  1982  		// refs only.  (Ideally, we'd see if the AST parent is a
  1983  		// SelectorExpr, but that requires PathEnclosingInterval
  1984  		// from golang.org/x/tools/go/ast/astutil.)
  1985  		if id.Value == "X" {
  1986  			continue
  1987  		}
  1988  
  1989  		_, gotObj := inner.LookupParent(id.Value, id.Pos())
  1990  		if gotObj != wantObj {
  1991  			// Print the scope tree of mainScope in case of error.
  1992  			var printScopeTree func(indent string, s *Scope)
  1993  			printScopeTree = func(indent string, s *Scope) {
  1994  				t.Logf("%sscope %s %v-%v = %v",
  1995  					indent,
  1996  					ScopeComment(s),
  1997  					s.Pos(),
  1998  					s.End(),
  1999  					s.Names())
  2000  				for i := range s.NumChildren() {
  2001  					printScopeTree(indent+"  ", s.Child(i))
  2002  				}
  2003  			}
  2004  			printScopeTree("", mainScope)
  2005  
  2006  			t.Errorf("%s: Scope(%s).LookupParent(%s@%v) got %v, want %v [scopePos=%v]",
  2007  				id.Pos(),
  2008  				ScopeComment(inner),
  2009  				id.Value,
  2010  				id.Pos(),
  2011  				gotObj,
  2012  				wantObj,
  2013  				ObjectScopePos(wantObj))
  2014  			continue
  2015  		}
  2016  	}
  2017  }
  2018  
  2019  // newDefined creates a new defined type named T with the given underlying type.
  2020  func newDefined(underlying Type) *Named {
  2021  	tname := NewTypeName(nopos, nil, "T", nil)
  2022  	return NewNamed(tname, underlying, nil)
  2023  }
  2024  
  2025  func TestConvertibleTo(t *testing.T) {
  2026  	for _, test := range []struct {
  2027  		v, t Type
  2028  		want bool
  2029  	}{
  2030  		{Typ[Int], Typ[Int], true},
  2031  		{Typ[Int], Typ[Float32], true},
  2032  		{Typ[Int], Typ[String], true},
  2033  		{newDefined(Typ[Int]), Typ[Int], true},
  2034  		{newDefined(new(Struct)), new(Struct), true},
  2035  		{newDefined(Typ[Int]), new(Struct), false},
  2036  		{Typ[UntypedInt], Typ[Int], true},
  2037  		{NewSlice(Typ[Int]), NewArray(Typ[Int], 10), true},
  2038  		{NewSlice(Typ[Int]), NewArray(Typ[Uint], 10), false},
  2039  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Int], 10)), true},
  2040  		{NewSlice(Typ[Int]), NewPointer(NewArray(Typ[Uint], 10)), false},
  2041  		// Untyped string values are not permitted by the spec, so the behavior below is undefined.
  2042  		{Typ[UntypedString], Typ[String], true},
  2043  	} {
  2044  		if got := ConvertibleTo(test.v, test.t); got != test.want {
  2045  			t.Errorf("ConvertibleTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
  2046  		}
  2047  	}
  2048  }
  2049  
  2050  func TestAssignableTo(t *testing.T) {
  2051  	for _, test := range []struct {
  2052  		v, t Type
  2053  		want bool
  2054  	}{
  2055  		{Typ[Int], Typ[Int], true},
  2056  		{Typ[Int], Typ[Float32], false},
  2057  		{newDefined(Typ[Int]), Typ[Int], false},
  2058  		{newDefined(new(Struct)), new(Struct), true},
  2059  		{Typ[UntypedBool], Typ[Bool], true},
  2060  		{Typ[UntypedString], Typ[Bool], false},
  2061  		// Neither untyped string nor untyped numeric assignments arise during
  2062  		// normal type checking, so the below behavior is technically undefined by
  2063  		// the spec.
  2064  		{Typ[UntypedString], Typ[String], true},
  2065  		{Typ[UntypedInt], Typ[Int], true},
  2066  	} {
  2067  		if got := AssignableTo(test.v, test.t); got != test.want {
  2068  			t.Errorf("AssignableTo(%v, %v) = %t, want %t", test.v, test.t, got, test.want)
  2069  		}
  2070  	}
  2071  }
  2072  
  2073  func TestIdentical(t *testing.T) {
  2074  	// For each test, we compare the types of objects X and Y in the source.
  2075  	tests := []struct {
  2076  		src  string
  2077  		want bool
  2078  	}{
  2079  		// Basic types.
  2080  		{"var X int; var Y int", true},
  2081  		{"var X int; var Y string", false},
  2082  
  2083  		// TODO: add more tests for complex types.
  2084  
  2085  		// Named types.
  2086  		{"type X int; type Y int", false},
  2087  
  2088  		// Aliases.
  2089  		{"type X = int; type Y = int", true},
  2090  
  2091  		// Functions.
  2092  		{`func X(int) string { return "" }; func Y(int) string { return "" }`, true},
  2093  		{`func X() string { return "" }; func Y(int) string { return "" }`, false},
  2094  		{`func X(int) string { return "" }; func Y(int) {}`, false},
  2095  
  2096  		// Generic functions. Type parameters should be considered identical modulo
  2097  		// renaming. See also go.dev/issue/49722.
  2098  		{`func X[P ~int](){}; func Y[Q ~int]() {}`, true},
  2099  		{`func X[P1 any, P2 ~*P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, true},
  2100  		{`func X[P1 any, P2 ~[]P1](){}; func Y[Q1 any, Q2 ~*Q1]() {}`, false},
  2101  		{`func X[P ~int](P){}; func Y[Q ~int](Q) {}`, true},
  2102  		{`func X[P ~string](P){}; func Y[Q ~int](Q) {}`, false},
  2103  		{`func X[P ~int]([]P){}; func Y[Q ~int]([]Q) {}`, true},
  2104  	}
  2105  
  2106  	for _, test := range tests {
  2107  		pkg := mustTypecheck("package p;"+test.src, nil, nil)
  2108  		X := pkg.Scope().Lookup("X")
  2109  		Y := pkg.Scope().Lookup("Y")
  2110  		if X == nil || Y == nil {
  2111  			t.Fatal("test must declare both X and Y")
  2112  		}
  2113  		if got := Identical(X.Type(), Y.Type()); got != test.want {
  2114  			t.Errorf("Identical(%s, %s) = %t, want %t", X.Type(), Y.Type(), got, test.want)
  2115  		}
  2116  	}
  2117  }
  2118  
  2119  func TestIdentical_issue15173(t *testing.T) {
  2120  	// Identical should allow nil arguments and be symmetric.
  2121  	for _, test := range []struct {
  2122  		x, y Type
  2123  		want bool
  2124  	}{
  2125  		{Typ[Int], Typ[Int], true},
  2126  		{Typ[Int], nil, false},
  2127  		{nil, Typ[Int], false},
  2128  		{nil, nil, true},
  2129  	} {
  2130  		if got := Identical(test.x, test.y); got != test.want {
  2131  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
  2132  		}
  2133  	}
  2134  }
  2135  
  2136  func TestIdenticalUnions(t *testing.T) {
  2137  	tname := NewTypeName(nopos, nil, "myInt", nil)
  2138  	myInt := NewNamed(tname, Typ[Int], nil)
  2139  	tmap := map[string]*Term{
  2140  		"int":     NewTerm(false, Typ[Int]),
  2141  		"~int":    NewTerm(true, Typ[Int]),
  2142  		"string":  NewTerm(false, Typ[String]),
  2143  		"~string": NewTerm(true, Typ[String]),
  2144  		"myInt":   NewTerm(false, myInt),
  2145  	}
  2146  	makeUnion := func(s string) *Union {
  2147  		parts := strings.Split(s, "|")
  2148  		var terms []*Term
  2149  		for _, p := range parts {
  2150  			term := tmap[p]
  2151  			if term == nil {
  2152  				t.Fatalf("missing term %q", p)
  2153  			}
  2154  			terms = append(terms, term)
  2155  		}
  2156  		return NewUnion(terms)
  2157  	}
  2158  	for _, test := range []struct {
  2159  		x, y string
  2160  		want bool
  2161  	}{
  2162  		// These tests are just sanity checks. The tests for type sets and
  2163  		// interfaces provide much more test coverage.
  2164  		{"int|~int", "~int", true},
  2165  		{"myInt|~int", "~int", true},
  2166  		{"int|string", "string|int", true},
  2167  		{"int|int|string", "string|int", true},
  2168  		{"myInt|string", "int|string", false},
  2169  	} {
  2170  		x := makeUnion(test.x)
  2171  		y := makeUnion(test.y)
  2172  		if got := Identical(x, y); got != test.want {
  2173  			t.Errorf("Identical(%v, %v) = %t", test.x, test.y, got)
  2174  		}
  2175  	}
  2176  }
  2177  
  2178  func TestIssue61737(t *testing.T) {
  2179  	// This test verifies that it is possible to construct invalid interfaces
  2180  	// containing duplicate methods using the go/types API.
  2181  	//
  2182  	// It must be possible for importers to construct such invalid interfaces.
  2183  	// Previously, this panicked.
  2184  
  2185  	sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
  2186  	sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
  2187  
  2188  	methods := []*Func{
  2189  		NewFunc(nopos, nil, "M", sig1),
  2190  		NewFunc(nopos, nil, "M", sig2),
  2191  	}
  2192  
  2193  	embeddedMethods := []*Func{
  2194  		NewFunc(nopos, nil, "M", sig2),
  2195  	}
  2196  	embedded := NewInterfaceType(embeddedMethods, nil)
  2197  	iface := NewInterfaceType(methods, []Type{embedded})
  2198  	iface.NumMethods() // unlike go/types, there is no Complete() method, so we complete implicitly
  2199  }
  2200  
  2201  func TestNewAlias_Issue65455(t *testing.T) {
  2202  	obj := NewTypeName(nopos, nil, "A", nil)
  2203  	alias := NewAlias(obj, Typ[Int])
  2204  	alias.Underlying() // must not panic
  2205  }
  2206  
  2207  func TestIssue15305(t *testing.T) {
  2208  	const src = "package p; func f() int16; var _ = f(undef)"
  2209  	f := mustParse(src)
  2210  	conf := Config{
  2211  		Error: func(err error) {}, // allow errors
  2212  	}
  2213  	info := &Info{
  2214  		Types: make(map[syntax.Expr]TypeAndValue),
  2215  	}
  2216  	conf.Check("p", []*syntax.File{f}, info) // ignore result
  2217  	for e, tv := range info.Types {
  2218  		if _, ok := e.(*syntax.CallExpr); ok {
  2219  			if tv.Type != Typ[Int16] {
  2220  				t.Errorf("CallExpr has type %v, want int16", tv.Type)
  2221  			}
  2222  			return
  2223  		}
  2224  	}
  2225  	t.Errorf("CallExpr has no type")
  2226  }
  2227  
  2228  // TestCompositeLitTypes verifies that Info.Types registers the correct
  2229  // types for composite literal expressions and composite literal type
  2230  // expressions.
  2231  func TestCompositeLitTypes(t *testing.T) {
  2232  	for i, test := range []struct {
  2233  		lit, typ string
  2234  	}{
  2235  		{`[16]byte{}`, `[16]byte`},
  2236  		{`[...]byte{}`, `[0]byte`},                // test for go.dev/issue/14092
  2237  		{`[...]int{1, 2, 3}`, `[3]int`},           // test for go.dev/issue/14092
  2238  		{`[...]int{90: 0, 98: 1, 2}`, `[100]int`}, // test for go.dev/issue/14092
  2239  		{`[]int{}`, `[]int`},
  2240  		{`map[string]bool{"foo": true}`, `map[string]bool`},
  2241  		{`struct{}{}`, `struct{}`},
  2242  		{`struct{x, y int; z complex128}{}`, `struct{x int; y int; z complex128}`},
  2243  	} {
  2244  		f := mustParse(fmt.Sprintf("package p%d; var _ = %s", i, test.lit))
  2245  		types := make(map[syntax.Expr]TypeAndValue)
  2246  		if _, err := new(Config).Check("p", []*syntax.File{f}, &Info{Types: types}); err != nil {
  2247  			t.Fatalf("%s: %v", test.lit, err)
  2248  		}
  2249  
  2250  		cmptype := func(x syntax.Expr, want string) {
  2251  			tv, ok := types[x]
  2252  			if !ok {
  2253  				t.Errorf("%s: no Types entry found", test.lit)
  2254  				return
  2255  			}
  2256  			if tv.Type == nil {
  2257  				t.Errorf("%s: type is nil", test.lit)
  2258  				return
  2259  			}
  2260  			if got := tv.Type.String(); got != want {
  2261  				t.Errorf("%s: got %v, want %s", test.lit, got, want)
  2262  			}
  2263  		}
  2264  
  2265  		// test type of composite literal expression
  2266  		rhs := f.DeclList[0].(*syntax.VarDecl).Values
  2267  		cmptype(rhs, test.typ)
  2268  
  2269  		// test type of composite literal type expression
  2270  		cmptype(rhs.(*syntax.CompositeLit).Type, test.typ)
  2271  	}
  2272  }
  2273  
  2274  // TestObjectParents verifies that objects have parent scopes or not
  2275  // as specified by the Object interface.
  2276  func TestObjectParents(t *testing.T) {
  2277  	const src = `
  2278  package p
  2279  
  2280  const C = 0
  2281  
  2282  type T1 struct {
  2283  	a, b int
  2284  	T2
  2285  }
  2286  
  2287  type T2 interface {
  2288  	im1()
  2289  	im2()
  2290  }
  2291  
  2292  func (T1) m1() {}
  2293  func (*T1) m2() {}
  2294  
  2295  func f(x int) { y := x; print(y) }
  2296  `
  2297  
  2298  	f := mustParse(src)
  2299  
  2300  	info := &Info{
  2301  		Defs: make(map[*syntax.Name]Object),
  2302  	}
  2303  	if _, err := new(Config).Check("p", []*syntax.File{f}, info); err != nil {
  2304  		t.Fatal(err)
  2305  	}
  2306  
  2307  	for ident, obj := range info.Defs {
  2308  		if obj == nil {
  2309  			// only package names and implicit vars have a nil object
  2310  			// (in this test we only need to handle the package name)
  2311  			if ident.Value != "p" {
  2312  				t.Errorf("%v has nil object", ident)
  2313  			}
  2314  			continue
  2315  		}
  2316  
  2317  		// struct fields, type-associated and interface methods
  2318  		// have no parent scope
  2319  		wantParent := true
  2320  		switch obj := obj.(type) {
  2321  		case *Var:
  2322  			if obj.IsField() {
  2323  				wantParent = false
  2324  			}
  2325  		case *Func:
  2326  			if obj.Type().(*Signature).Recv() != nil { // method
  2327  				wantParent = false
  2328  			}
  2329  		}
  2330  
  2331  		gotParent := obj.Parent() != nil
  2332  		switch {
  2333  		case gotParent && !wantParent:
  2334  			t.Errorf("%v: want no parent, got %s", ident, obj.Parent())
  2335  		case !gotParent && wantParent:
  2336  			t.Errorf("%v: no parent found", ident)
  2337  		}
  2338  	}
  2339  }
  2340  
  2341  // TestFailedImport tests that we don't get follow-on errors
  2342  // elsewhere in a package due to failing to import a package.
  2343  func TestFailedImport(t *testing.T) {
  2344  	testenv.MustHaveGoBuild(t)
  2345  
  2346  	const src = `
  2347  package p
  2348  
  2349  import foo "go/types/thisdirectorymustnotexistotherwisethistestmayfail/foo" // should only see an error here
  2350  
  2351  const c = foo.C
  2352  type T = foo.T
  2353  var v T = c
  2354  func f(x T) T { return foo.F(x) }
  2355  `
  2356  	f := mustParse(src)
  2357  	files := []*syntax.File{f}
  2358  
  2359  	// type-check using all possible importers
  2360  	for _, compiler := range []string{"gc", "gccgo", "source"} {
  2361  		errcount := 0
  2362  		conf := Config{
  2363  			Error: func(err error) {
  2364  				// we should only see the import error
  2365  				if errcount > 0 || !strings.Contains(err.Error(), "could not import") {
  2366  					t.Errorf("for %s importer, got unexpected error: %v", compiler, err)
  2367  				}
  2368  				errcount++
  2369  			},
  2370  			//Importer: importer.For(compiler, nil),
  2371  		}
  2372  
  2373  		info := &Info{
  2374  			Uses: make(map[*syntax.Name]Object),
  2375  		}
  2376  		pkg, _ := conf.Check("p", files, info)
  2377  		if pkg == nil {
  2378  			t.Errorf("for %s importer, type-checking failed to return a package", compiler)
  2379  			continue
  2380  		}
  2381  
  2382  		imports := pkg.Imports()
  2383  		if len(imports) != 1 {
  2384  			t.Errorf("for %s importer, got %d imports, want 1", compiler, len(imports))
  2385  			continue
  2386  		}
  2387  		imp := imports[0]
  2388  		if imp.Name() != "foo" {
  2389  			t.Errorf(`for %s importer, got %q, want "foo"`, compiler, imp.Name())
  2390  			continue
  2391  		}
  2392  
  2393  		// verify that all uses of foo refer to the imported package foo (imp)
  2394  		for ident, obj := range info.Uses {
  2395  			if ident.Value == "foo" {
  2396  				if obj, ok := obj.(*PkgName); ok {
  2397  					if obj.Imported() != imp {
  2398  						t.Errorf("%s resolved to %v; want %v", ident.Value, obj.Imported(), imp)
  2399  					}
  2400  				} else {
  2401  					t.Errorf("%s resolved to %v; want package name", ident.Value, obj)
  2402  				}
  2403  			}
  2404  		}
  2405  	}
  2406  }
  2407  
  2408  func TestInstantiate(t *testing.T) {
  2409  	// eventually we like more tests but this is a start
  2410  	const src = "package p; type T[P any] *T[P]"
  2411  	pkg := mustTypecheck(src, nil, nil)
  2412  
  2413  	// type T should have one type parameter
  2414  	T := pkg.Scope().Lookup("T").Type().(*Named)
  2415  	if n := T.TypeParams().Len(); n != 1 {
  2416  		t.Fatalf("expected 1 type parameter; found %d", n)
  2417  	}
  2418  
  2419  	// instantiation should succeed (no endless recursion)
  2420  	// even with a nil *Checker
  2421  	res, err := Instantiate(nil, T, []Type{Typ[Int]}, false)
  2422  	if err != nil {
  2423  		t.Fatal(err)
  2424  	}
  2425  
  2426  	// instantiated type should point to itself
  2427  	if p := res.Underlying().(*Pointer).Elem(); p != res {
  2428  		t.Fatalf("unexpected result type: %s points to %s", res, p)
  2429  	}
  2430  }
  2431  
  2432  func TestInstantiateConcurrent(t *testing.T) {
  2433  	const src = `package p
  2434  
  2435  type I[P any] interface {
  2436  	m(P)
  2437  	n() P
  2438  }
  2439  
  2440  type J = I[int]
  2441  
  2442  type Nested[P any] *interface{b(P)}
  2443  
  2444  type K = Nested[string]
  2445  `
  2446  	pkg := mustTypecheck(src, nil, nil)
  2447  
  2448  	insts := []*Interface{
  2449  		pkg.Scope().Lookup("J").Type().Underlying().(*Interface),
  2450  		pkg.Scope().Lookup("K").Type().Underlying().(*Pointer).Elem().(*Interface),
  2451  	}
  2452  
  2453  	// Use the interface instances concurrently.
  2454  	for _, inst := range insts {
  2455  		var (
  2456  			counts  [2]int      // method counts
  2457  			methods [2][]string // method strings
  2458  		)
  2459  		var wg sync.WaitGroup
  2460  		for i := 0; i < 2; i++ {
  2461  			i := i
  2462  			wg.Add(1)
  2463  			go func() {
  2464  				defer wg.Done()
  2465  
  2466  				counts[i] = inst.NumMethods()
  2467  				for mi := 0; mi < counts[i]; mi++ {
  2468  					methods[i] = append(methods[i], inst.Method(mi).String())
  2469  				}
  2470  			}()
  2471  		}
  2472  		wg.Wait()
  2473  
  2474  		if counts[0] != counts[1] {
  2475  			t.Errorf("mismatching method counts for %s: %d vs %d", inst, counts[0], counts[1])
  2476  			continue
  2477  		}
  2478  		for i := 0; i < counts[0]; i++ {
  2479  			if m0, m1 := methods[0][i], methods[1][i]; m0 != m1 {
  2480  				t.Errorf("mismatching methods for %s: %s vs %s", inst, m0, m1)
  2481  			}
  2482  		}
  2483  	}
  2484  }
  2485  
  2486  func TestInstantiateErrors(t *testing.T) {
  2487  	tests := []struct {
  2488  		src    string // by convention, T must be the type being instantiated
  2489  		targs  []Type
  2490  		wantAt int // -1 indicates no error
  2491  	}{
  2492  		{"type T[P interface{~string}] int", []Type{Typ[Int]}, 0},
  2493  		{"type T[P1 interface{int}, P2 interface{~string}] int", []Type{Typ[Int], Typ[Int]}, 1},
  2494  		{"type T[P1 any, P2 interface{~[]P1}] int", []Type{Typ[Int], NewSlice(Typ[String])}, 1},
  2495  		{"type T[P1 interface{~[]P2}, P2 any] int", []Type{NewSlice(Typ[String]), Typ[Int]}, 0},
  2496  	}
  2497  
  2498  	for _, test := range tests {
  2499  		src := "package p; " + test.src
  2500  		pkg := mustTypecheck(src, nil, nil)
  2501  
  2502  		T := pkg.Scope().Lookup("T").Type().(*Named)
  2503  
  2504  		_, err := Instantiate(nil, T, test.targs, true)
  2505  		if err == nil {
  2506  			t.Fatalf("Instantiate(%v, %v) returned nil error, want non-nil", T, test.targs)
  2507  		}
  2508  
  2509  		var argErr *ArgumentError
  2510  		if !errors.As(err, &argErr) {
  2511  			t.Fatalf("Instantiate(%v, %v): error is not an *ArgumentError", T, test.targs)
  2512  		}
  2513  
  2514  		if argErr.Index != test.wantAt {
  2515  			t.Errorf("Instantiate(%v, %v): error at index %d, want index %d", T, test.targs, argErr.Index, test.wantAt)
  2516  		}
  2517  	}
  2518  }
  2519  
  2520  func TestArgumentErrorUnwrapping(t *testing.T) {
  2521  	var err error = &ArgumentError{
  2522  		Index: 1,
  2523  		Err:   Error{Msg: "test"},
  2524  	}
  2525  	var e Error
  2526  	if !errors.As(err, &e) {
  2527  		t.Fatalf("error %v does not wrap types.Error", err)
  2528  	}
  2529  	if e.Msg != "test" {
  2530  		t.Errorf("e.Msg = %q, want %q", e.Msg, "test")
  2531  	}
  2532  }
  2533  
  2534  func TestInstanceIdentity(t *testing.T) {
  2535  	imports := make(testImporter)
  2536  	conf := Config{Importer: imports}
  2537  	makePkg := func(src string) {
  2538  		f := mustParse(src)
  2539  		name := f.PkgName.Value
  2540  		pkg, err := conf.Check(name, []*syntax.File{f}, nil)
  2541  		if err != nil {
  2542  			t.Fatal(err)
  2543  		}
  2544  		imports[name] = pkg
  2545  	}
  2546  	makePkg(`package lib; type T[P any] struct{}`)
  2547  	makePkg(`package a; import "lib"; var A lib.T[int]`)
  2548  	makePkg(`package b; import "lib"; var B lib.T[int]`)
  2549  	a := imports["a"].Scope().Lookup("A")
  2550  	b := imports["b"].Scope().Lookup("B")
  2551  	if !Identical(a.Type(), b.Type()) {
  2552  		t.Errorf("mismatching types: a.A: %s, b.B: %s", a.Type(), b.Type())
  2553  	}
  2554  }
  2555  
  2556  // TestInstantiatedObjects verifies properties of instantiated objects.
  2557  func TestInstantiatedObjects(t *testing.T) {
  2558  	const src = `
  2559  package p
  2560  
  2561  type T[P any] struct {
  2562  	field P
  2563  }
  2564  
  2565  func (recv *T[Q]) concreteMethod(mParam Q) (mResult Q) { return }
  2566  
  2567  type FT[P any] func(ftParam P) (ftResult P)
  2568  
  2569  func F[P any](fParam P) (fResult P){ return }
  2570  
  2571  type I[P any] interface {
  2572  	interfaceMethod(P)
  2573  }
  2574  
  2575  type R[P any] T[P]
  2576  
  2577  func (R[P]) m() {} // having a method triggers expansion of R
  2578  
  2579  var (
  2580  	t T[int]
  2581  	ft FT[int]
  2582  	f = F[int]
  2583  	i I[int]
  2584  )
  2585  
  2586  func fn() {
  2587  	var r R[int]
  2588  	_ = r
  2589  }
  2590  `
  2591  	info := &Info{
  2592  		Defs: make(map[*syntax.Name]Object),
  2593  	}
  2594  	f := mustParse(src)
  2595  	conf := Config{}
  2596  	pkg, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
  2597  	if err != nil {
  2598  		t.Fatal(err)
  2599  	}
  2600  
  2601  	lookup := func(name string) Type { return pkg.Scope().Lookup(name).Type() }
  2602  	fnScope := pkg.Scope().Lookup("fn").(*Func).Scope()
  2603  
  2604  	tests := []struct {
  2605  		name string
  2606  		obj  Object
  2607  	}{
  2608  		// Struct fields
  2609  		{"field", lookup("t").Underlying().(*Struct).Field(0)},
  2610  		{"field", fnScope.Lookup("r").Type().Underlying().(*Struct).Field(0)},
  2611  
  2612  		// Methods and method fields
  2613  		{"concreteMethod", lookup("t").(*Named).Method(0)},
  2614  		{"recv", lookup("t").(*Named).Method(0).Type().(*Signature).Recv()},
  2615  		{"mParam", lookup("t").(*Named).Method(0).Type().(*Signature).Params().At(0)},
  2616  		{"mResult", lookup("t").(*Named).Method(0).Type().(*Signature).Results().At(0)},
  2617  
  2618  		// Interface methods
  2619  		{"interfaceMethod", lookup("i").Underlying().(*Interface).Method(0)},
  2620  
  2621  		// Function type fields
  2622  		{"ftParam", lookup("ft").Underlying().(*Signature).Params().At(0)},
  2623  		{"ftResult", lookup("ft").Underlying().(*Signature).Results().At(0)},
  2624  
  2625  		// Function fields
  2626  		{"fParam", lookup("f").(*Signature).Params().At(0)},
  2627  		{"fResult", lookup("f").(*Signature).Results().At(0)},
  2628  	}
  2629  
  2630  	// Collect all identifiers by name.
  2631  	idents := make(map[string][]*syntax.Name)
  2632  	syntax.Inspect(f, func(n syntax.Node) bool {
  2633  		if id, ok := n.(*syntax.Name); ok {
  2634  			idents[id.Value] = append(idents[id.Value], id)
  2635  		}
  2636  		return true
  2637  	})
  2638  
  2639  	for _, test := range tests {
  2640  		test := test
  2641  		t.Run(test.name, func(t *testing.T) {
  2642  			if got := len(idents[test.name]); got != 1 {
  2643  				t.Fatalf("found %d identifiers named %s, want 1", got, test.name)
  2644  			}
  2645  			ident := idents[test.name][0]
  2646  			def := info.Defs[ident]
  2647  			if def == test.obj {
  2648  				t.Fatalf("info.Defs[%s] contains the test object", test.name)
  2649  			}
  2650  			if orig := originObject(test.obj); def != orig {
  2651  				t.Errorf("info.Defs[%s] does not match obj.Origin()", test.name)
  2652  			}
  2653  			if def.Pkg() != test.obj.Pkg() {
  2654  				t.Errorf("Pkg() = %v, want %v", def.Pkg(), test.obj.Pkg())
  2655  			}
  2656  			if def.Name() != test.obj.Name() {
  2657  				t.Errorf("Name() = %v, want %v", def.Name(), test.obj.Name())
  2658  			}
  2659  			if def.Pos() != test.obj.Pos() {
  2660  				t.Errorf("Pos() = %v, want %v", def.Pos(), test.obj.Pos())
  2661  			}
  2662  			if def.Parent() != test.obj.Parent() {
  2663  				t.Fatalf("Parent() = %v, want %v", def.Parent(), test.obj.Parent())
  2664  			}
  2665  			if def.Exported() != test.obj.Exported() {
  2666  				t.Fatalf("Exported() = %v, want %v", def.Exported(), test.obj.Exported())
  2667  			}
  2668  			if def.Id() != test.obj.Id() {
  2669  				t.Fatalf("Id() = %v, want %v", def.Id(), test.obj.Id())
  2670  			}
  2671  			// String and Type are expected to differ.
  2672  		})
  2673  	}
  2674  }
  2675  
  2676  func originObject(obj Object) Object {
  2677  	switch obj := obj.(type) {
  2678  	case *Var:
  2679  		return obj.Origin()
  2680  	case *Func:
  2681  		return obj.Origin()
  2682  	}
  2683  	return obj
  2684  }
  2685  
  2686  func TestImplements(t *testing.T) {
  2687  	const src = `
  2688  package p
  2689  
  2690  type EmptyIface interface{}
  2691  
  2692  type I interface {
  2693  	m()
  2694  }
  2695  
  2696  type C interface {
  2697  	m()
  2698  	~int
  2699  }
  2700  
  2701  type Integer interface{
  2702  	int8 | int16 | int32 | int64
  2703  }
  2704  
  2705  type EmptyTypeSet interface{
  2706  	Integer
  2707  	~string
  2708  }
  2709  
  2710  type N1 int
  2711  func (N1) m() {}
  2712  
  2713  type N2 int
  2714  func (*N2) m() {}
  2715  
  2716  type N3 int
  2717  func (N3) m(int) {}
  2718  
  2719  type N4 string
  2720  func (N4) m()
  2721  
  2722  type Bad Bad // invalid type
  2723  `
  2724  
  2725  	f := mustParse(src)
  2726  	conf := Config{Error: func(error) {}}
  2727  	pkg, _ := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
  2728  
  2729  	lookup := func(tname string) Type { return pkg.Scope().Lookup(tname).Type() }
  2730  	var (
  2731  		EmptyIface   = lookup("EmptyIface").Underlying().(*Interface)
  2732  		I            = lookup("I").(*Named)
  2733  		II           = I.Underlying().(*Interface)
  2734  		C            = lookup("C").(*Named)
  2735  		CI           = C.Underlying().(*Interface)
  2736  		Integer      = lookup("Integer").Underlying().(*Interface)
  2737  		EmptyTypeSet = lookup("EmptyTypeSet").Underlying().(*Interface)
  2738  		N1           = lookup("N1")
  2739  		N1p          = NewPointer(N1)
  2740  		N2           = lookup("N2")
  2741  		N2p          = NewPointer(N2)
  2742  		N3           = lookup("N3")
  2743  		N4           = lookup("N4")
  2744  		Bad          = lookup("Bad")
  2745  	)
  2746  
  2747  	tests := []struct {
  2748  		V    Type
  2749  		T    *Interface
  2750  		want bool
  2751  	}{
  2752  		{I, II, true},
  2753  		{I, CI, false},
  2754  		{C, II, true},
  2755  		{C, CI, true},
  2756  		{Typ[Int8], Integer, true},
  2757  		{Typ[Int64], Integer, true},
  2758  		{Typ[String], Integer, false},
  2759  		{EmptyTypeSet, II, true},
  2760  		{EmptyTypeSet, EmptyTypeSet, true},
  2761  		{Typ[Int], EmptyTypeSet, false},
  2762  		{N1, II, true},
  2763  		{N1, CI, true},
  2764  		{N1p, II, true},
  2765  		{N1p, CI, false},
  2766  		{N2, II, false},
  2767  		{N2, CI, false},
  2768  		{N2p, II, true},
  2769  		{N2p, CI, false},
  2770  		{N3, II, false},
  2771  		{N3, CI, false},
  2772  		{N4, II, true},
  2773  		{N4, CI, false},
  2774  		{Bad, II, false},
  2775  		{Bad, CI, false},
  2776  		{Bad, EmptyIface, true},
  2777  	}
  2778  
  2779  	for _, test := range tests {
  2780  		if got := Implements(test.V, test.T); got != test.want {
  2781  			t.Errorf("Implements(%s, %s) = %t, want %t", test.V, test.T, got, test.want)
  2782  		}
  2783  
  2784  		// The type assertion x.(T) is valid if T is an interface or if T implements the type of x.
  2785  		// The assertion is never valid if T is a bad type.
  2786  		V := test.T
  2787  		T := test.V
  2788  		want := false
  2789  		if _, ok := T.Underlying().(*Interface); (ok || Implements(T, V)) && T != Bad {
  2790  			want = true
  2791  		}
  2792  		if got := AssertableTo(V, T); got != want {
  2793  			t.Errorf("AssertableTo(%s, %s) = %t, want %t", V, T, got, want)
  2794  		}
  2795  	}
  2796  }
  2797  
  2798  func TestMissingMethodAlternative(t *testing.T) {
  2799  	const src = `
  2800  package p
  2801  type T interface {
  2802  	m()
  2803  }
  2804  
  2805  type V0 struct{}
  2806  func (V0) m() {}
  2807  
  2808  type V1 struct{}
  2809  
  2810  type V2 struct{}
  2811  func (V2) m() int
  2812  
  2813  type V3 struct{}
  2814  func (*V3) m()
  2815  
  2816  type V4 struct{}
  2817  func (V4) M()
  2818  `
  2819  
  2820  	pkg := mustTypecheck(src, nil, nil)
  2821  
  2822  	T := pkg.Scope().Lookup("T").Type().Underlying().(*Interface)
  2823  	lookup := func(name string) (*Func, bool) {
  2824  		return MissingMethod(pkg.Scope().Lookup(name).Type(), T, true)
  2825  	}
  2826  
  2827  	// V0 has method m with correct signature. Should not report wrongType.
  2828  	method, wrongType := lookup("V0")
  2829  	if method != nil || wrongType {
  2830  		t.Fatalf("V0: got method = %v, wrongType = %v", method, wrongType)
  2831  	}
  2832  
  2833  	checkMissingMethod := func(tname string, reportWrongType bool) {
  2834  		method, wrongType := lookup(tname)
  2835  		if method == nil || method.Name() != "m" || wrongType != reportWrongType {
  2836  			t.Fatalf("%s: got method = %v, wrongType = %v", tname, method, wrongType)
  2837  		}
  2838  	}
  2839  
  2840  	// V1 has no method m. Should not report wrongType.
  2841  	checkMissingMethod("V1", false)
  2842  
  2843  	// V2 has method m with wrong signature type (ignoring receiver). Should report wrongType.
  2844  	checkMissingMethod("V2", true)
  2845  
  2846  	// V3 has no method m but it exists on *V3. Should report wrongType.
  2847  	checkMissingMethod("V3", true)
  2848  
  2849  	// V4 has no method m but has M. Should not report wrongType.
  2850  	checkMissingMethod("V4", false)
  2851  }
  2852  
  2853  func TestErrorURL(t *testing.T) {
  2854  	conf := Config{ErrorURL: " [go.dev/e/%s]"}
  2855  
  2856  	// test case for a one-line error
  2857  	const src1 = `
  2858  package p
  2859  var _ T
  2860  `
  2861  	_, err := typecheck(src1, &conf, nil)
  2862  	if err == nil || !strings.HasSuffix(err.Error(), " [go.dev/e/UndeclaredName]") {
  2863  		t.Errorf("src1: unexpected error: got %v", err)
  2864  	}
  2865  
  2866  	// test case for a multi-line error
  2867  	const src2 = `
  2868  package p
  2869  func f() int { return 0 }
  2870  var _ = f(1, 2)
  2871  `
  2872  	_, err = typecheck(src2, &conf, nil)
  2873  	if err == nil || !strings.Contains(err.Error(), " [go.dev/e/WrongArgCount]\n") {
  2874  		t.Errorf("src1: unexpected error: got %v", err)
  2875  	}
  2876  }
  2877  
  2878  func TestModuleVersion(t *testing.T) {
  2879  	// version go1.dd must be able to typecheck go1.dd.0, go1.dd.1, etc.
  2880  	goversion := fmt.Sprintf("go1.%d", goversion.Version)
  2881  	for _, v := range []string{
  2882  		goversion,
  2883  		goversion + ".0",
  2884  		goversion + ".1",
  2885  		goversion + ".rc",
  2886  	} {
  2887  		conf := Config{GoVersion: v}
  2888  		pkg := mustTypecheck("package p", &conf, nil)
  2889  		if pkg.GoVersion() != conf.GoVersion {
  2890  			t.Errorf("got %s; want %s", pkg.GoVersion(), conf.GoVersion)
  2891  		}
  2892  	}
  2893  }
  2894  
  2895  func TestFileVersions(t *testing.T) {
  2896  	for _, test := range []struct {
  2897  		goVersion   string
  2898  		fileVersion string
  2899  		wantVersion string
  2900  	}{
  2901  		{"", "", ""},                    // no versions specified
  2902  		{"go1.19", "", "go1.19"},        // module version specified
  2903  		{"", "go1.20", "go1.21"},        // file version specified below minimum of 1.21
  2904  		{"go1", "", "go1"},              // no file version specified
  2905  		{"go1", "goo1.22", "go1"},       // invalid file version specified
  2906  		{"go1", "go1.19", "go1.21"},     // file version specified below minimum of 1.21
  2907  		{"go1", "go1.20", "go1.21"},     // file version specified below minimum of 1.21
  2908  		{"go1", "go1.21", "go1.21"},     // file version specified at 1.21
  2909  		{"go1", "go1.22", "go1.22"},     // file version specified above 1.21
  2910  		{"go1.19", "", "go1.19"},        // no file version specified
  2911  		{"go1.19", "goo1.22", "go1.19"}, // invalid file version specified
  2912  		{"go1.19", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
  2913  		{"go1.19", "go1.21", "go1.21"},  // file version specified at 1.21
  2914  		{"go1.19", "go1.22", "go1.22"},  // file version specified above 1.21
  2915  		{"go1.20", "", "go1.20"},        // no file version specified
  2916  		{"go1.20", "goo1.22", "go1.20"}, // invalid file version specified
  2917  		{"go1.20", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
  2918  		{"go1.20", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
  2919  		{"go1.20", "go1.21", "go1.21"},  // file version specified at 1.21
  2920  		{"go1.20", "go1.22", "go1.22"},  // file version specified above 1.21
  2921  		{"go1.21", "", "go1.21"},        // no file version specified
  2922  		{"go1.21", "goo1.22", "go1.21"}, // invalid file version specified
  2923  		{"go1.21", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
  2924  		{"go1.21", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
  2925  		{"go1.21", "go1.21", "go1.21"},  // file version specified at 1.21
  2926  		{"go1.21", "go1.22", "go1.22"},  // file version specified above 1.21
  2927  		{"go1.22", "", "go1.22"},        // no file version specified
  2928  		{"go1.22", "goo1.22", "go1.22"}, // invalid file version specified
  2929  		{"go1.22", "go1.19", "go1.21"},  // file version specified below minimum of 1.21
  2930  		{"go1.22", "go1.20", "go1.21"},  // file version specified below minimum of 1.21
  2931  		{"go1.22", "go1.21", "go1.21"},  // file version specified at 1.21
  2932  		{"go1.22", "go1.22", "go1.22"},  // file version specified above 1.21
  2933  
  2934  		// versions containing release numbers
  2935  		// (file versions containing release numbers are considered invalid)
  2936  		{"go1.19.0", "", "go1.19.0"},         // no file version specified
  2937  		{"go1.20.1", "go1.19.1", "go1.20.1"}, // invalid file version
  2938  		{"go1.20.1", "go1.21.1", "go1.20.1"}, // invalid file version
  2939  		{"go1.21.1", "go1.19.1", "go1.21.1"}, // invalid file version
  2940  		{"go1.21.1", "go1.21.1", "go1.21.1"}, // invalid file version
  2941  		{"go1.22.1", "go1.19.1", "go1.22.1"}, // invalid file version
  2942  		{"go1.22.1", "go1.21.1", "go1.22.1"}, // invalid file version
  2943  	} {
  2944  		var src string
  2945  		if test.fileVersion != "" {
  2946  			src = "//go:build " + test.fileVersion + "\n"
  2947  		}
  2948  		src += "package p"
  2949  
  2950  		conf := Config{GoVersion: test.goVersion}
  2951  		versions := make(map[*syntax.PosBase]string)
  2952  		var info Info
  2953  		info.FileVersions = versions
  2954  		mustTypecheck(src, &conf, &info)
  2955  
  2956  		n := 0
  2957  		for _, v := range info.FileVersions {
  2958  			want := test.wantVersion
  2959  			if v != want {
  2960  				t.Errorf("%q: unexpected file version: got %v, want %v", src, v, want)
  2961  			}
  2962  			n++
  2963  		}
  2964  		if n != 1 {
  2965  			t.Errorf("%q: incorrect number of map entries: got %d", src, n)
  2966  		}
  2967  	}
  2968  }
  2969  
  2970  // TestTooNew ensures that "too new" errors are emitted when the file
  2971  // or module is tagged with a newer version of Go than this go/types.
  2972  func TestTooNew(t *testing.T) {
  2973  	for _, test := range []struct {
  2974  		goVersion   string // package's Go version (as if derived from go.mod file)
  2975  		fileVersion string // file's Go version (becomes a build tag)
  2976  		wantErr     string // expected substring of concatenation of all errors
  2977  	}{
  2978  		{"go1.98", "", "package requires newer Go version go1.98"},
  2979  		{"", "go1.99", "p:2:9: file requires newer Go version go1.99"},
  2980  		{"go1.98", "go1.99", "package requires newer Go version go1.98"}, // (two
  2981  		{"go1.98", "go1.99", "file requires newer Go version go1.99"},    // errors)
  2982  	} {
  2983  		var src string
  2984  		if test.fileVersion != "" {
  2985  			src = "//go:build " + test.fileVersion + "\n"
  2986  		}
  2987  		src += "package p; func f()"
  2988  
  2989  		var errs []error
  2990  		conf := Config{
  2991  			GoVersion: test.goVersion,
  2992  			Error:     func(err error) { errs = append(errs, err) },
  2993  		}
  2994  		info := &Info{Defs: make(map[*syntax.Name]Object)}
  2995  		typecheck(src, &conf, info)
  2996  		got := fmt.Sprint(errs)
  2997  		if !strings.Contains(got, test.wantErr) {
  2998  			t.Errorf("%q: unexpected error: got %q, want substring %q",
  2999  				src, got, test.wantErr)
  3000  		}
  3001  
  3002  		// Assert that declarations were type checked nonetheless.
  3003  		var gotObjs []string
  3004  		for id, obj := range info.Defs {
  3005  			if obj != nil {
  3006  				objStr := strings.ReplaceAll(fmt.Sprintf("%s:%T", id.Value, obj), "types2", "types")
  3007  				gotObjs = append(gotObjs, objStr)
  3008  			}
  3009  		}
  3010  		wantObjs := "f:*types.Func"
  3011  		if !strings.Contains(fmt.Sprint(gotObjs), wantObjs) {
  3012  			t.Errorf("%q: got %s, want substring %q",
  3013  				src, gotObjs, wantObjs)
  3014  		}
  3015  	}
  3016  }
  3017  
  3018  // This is a regression test for #66704.
  3019  func TestUnaliasTooSoonInCycle(t *testing.T) {
  3020  	t.Setenv("GODEBUG", "gotypesalias=1")
  3021  	const src = `package a
  3022  
  3023  var x T[B] // this appears to cause Unalias to be called on B while still Invalid
  3024  
  3025  type T[_ any] struct{}
  3026  type A T[B]
  3027  type B = T[A]
  3028  `
  3029  	pkg := mustTypecheck(src, nil, nil)
  3030  	B := pkg.Scope().Lookup("B")
  3031  
  3032  	got, want := Unalias(B.Type()).String(), "a.T[a.A]"
  3033  	if got != want {
  3034  		t.Errorf("Unalias(type B = T[A]) = %q, want %q", got, want)
  3035  	}
  3036  }
  3037  
  3038  func TestAlias_Rhs(t *testing.T) {
  3039  	const src = `package p
  3040  
  3041  type A = B
  3042  type B = C
  3043  type C = int
  3044  `
  3045  
  3046  	pkg := mustTypecheck(src, &Config{EnableAlias: true}, nil)
  3047  	A := pkg.Scope().Lookup("A")
  3048  
  3049  	got, want := A.Type().(*Alias).Rhs().String(), "p.B"
  3050  	if got != want {
  3051  		t.Errorf("A.Rhs = %s, want %s", got, want)
  3052  	}
  3053  }
  3054  
  3055  // Test the hijacking described of "any" described in golang/go#66921, for
  3056  // (concurrent) type checking.
  3057  func TestAnyHijacking_Check(t *testing.T) {
  3058  	for _, enableAlias := range []bool{false, true} {
  3059  		t.Run(fmt.Sprintf("EnableAlias=%t", enableAlias), func(t *testing.T) {
  3060  			var wg sync.WaitGroup
  3061  			for i := 0; i < 10; i++ {
  3062  				wg.Add(1)
  3063  				go func() {
  3064  					defer wg.Done()
  3065  					pkg := mustTypecheck("package p; var x any", &Config{EnableAlias: enableAlias}, nil)
  3066  					x := pkg.Scope().Lookup("x")
  3067  					if _, gotAlias := x.Type().(*Alias); gotAlias != enableAlias {
  3068  						t.Errorf(`Lookup("x").Type() is %T: got Alias: %t, want %t`, x.Type(), gotAlias, enableAlias)
  3069  					}
  3070  				}()
  3071  			}
  3072  			wg.Wait()
  3073  		})
  3074  	}
  3075  }
  3076  

View as plain text