Source file src/go/types/issues_test.go

     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  // This file implements tests for various issues.
     6  
     7  package types_test
     8  
     9  import (
    10  	"fmt"
    11  	"go/ast"
    12  	"go/parser"
    13  	"go/token"
    14  	"internal/testenv"
    15  	"regexp"
    16  	"slices"
    17  	"strings"
    18  	"testing"
    19  
    20  	. "go/types"
    21  )
    22  
    23  func TestIssue5770(t *testing.T) {
    24  	_, err := typecheck(`package p; type S struct{T}`, nil, nil)
    25  	const want = "undefined: T"
    26  	if err == nil || !strings.Contains(err.Error(), want) {
    27  		t.Errorf("got: %v; want: %s", err, want)
    28  	}
    29  }
    30  
    31  func TestIssue5849(t *testing.T) {
    32  	src := `
    33  package p
    34  var (
    35  	s uint
    36  	_ = uint8(8)
    37  	_ = uint16(16) << s
    38  	_ = uint32(32 << s)
    39  	_ = uint64(64 << s + s)
    40  	_ = (interface{})("foo")
    41  	_ = (interface{})(nil)
    42  )`
    43  	types := make(map[ast.Expr]TypeAndValue)
    44  	mustTypecheck(src, nil, &Info{Types: types})
    45  
    46  	for x, tv := range types {
    47  		var want Type
    48  		switch x := x.(type) {
    49  		case *ast.BasicLit:
    50  			switch x.Value {
    51  			case `8`:
    52  				want = Typ[Uint8]
    53  			case `16`:
    54  				want = Typ[Uint16]
    55  			case `32`:
    56  				want = Typ[Uint32]
    57  			case `64`:
    58  				want = Typ[Uint] // because of "+ s", s is of type uint
    59  			case `"foo"`:
    60  				want = Typ[String]
    61  			}
    62  		case *ast.Ident:
    63  			if x.Name == "nil" {
    64  				want = Typ[UntypedNil]
    65  			}
    66  		}
    67  		if want != nil && !Identical(tv.Type, want) {
    68  			t.Errorf("got %s; want %s", tv.Type, want)
    69  		}
    70  	}
    71  }
    72  
    73  func TestIssue6413(t *testing.T) {
    74  	src := `
    75  package p
    76  func f() int {
    77  	defer f()
    78  	go f()
    79  	return 0
    80  }
    81  `
    82  	types := make(map[ast.Expr]TypeAndValue)
    83  	mustTypecheck(src, nil, &Info{Types: types})
    84  
    85  	want := Typ[Int]
    86  	n := 0
    87  	for x, tv := range types {
    88  		if _, ok := x.(*ast.CallExpr); ok {
    89  			if tv.Type != want {
    90  				t.Errorf("%s: got %s; want %s", fset.Position(x.Pos()), tv.Type, want)
    91  			}
    92  			n++
    93  		}
    94  	}
    95  
    96  	if n != 2 {
    97  		t.Errorf("got %d CallExprs; want 2", n)
    98  	}
    99  }
   100  
   101  func TestIssue7245(t *testing.T) {
   102  	src := `
   103  package p
   104  func (T) m() (res bool) { return }
   105  type T struct{} // receiver type after method declaration
   106  `
   107  	f := mustParse(fset, src)
   108  
   109  	var conf Config
   110  	defs := make(map[*ast.Ident]Object)
   111  	_, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs})
   112  	if err != nil {
   113  		t.Fatal(err)
   114  	}
   115  
   116  	m := f.Decls[0].(*ast.FuncDecl)
   117  	res1 := defs[m.Name].(*Func).Signature().Results().At(0)
   118  	res2 := defs[m.Type.Results.List[0].Names[0]].(*Var)
   119  
   120  	if res1 != res2 {
   121  		t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
   122  	}
   123  }
   124  
   125  // This tests that uses of existing vars on the LHS of an assignment
   126  // are Uses, not Defs; and also that the (illegal) use of a non-var on
   127  // the LHS of an assignment is a Use nonetheless.
   128  func TestIssue7827(t *testing.T) {
   129  	const src = `
   130  package p
   131  func _() {
   132  	const w = 1        // defs w
   133          x, y := 2, 3       // defs x, y
   134          w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
   135          _, _, _ = x, y, z  // uses x, y, z
   136  }
   137  `
   138  	// We need a specific fileset in this test below for positions.
   139  	// Cannot use typecheck helper.
   140  	fset := token.NewFileSet()
   141  	f := mustParse(fset, src)
   142  
   143  	const want = `L3 defs func p._()
   144  L4 defs const w untyped int
   145  L5 defs var x int
   146  L5 defs var y int
   147  L6 defs var z int
   148  L6 uses const w untyped int
   149  L6 uses var x int
   150  L7 uses var x int
   151  L7 uses var y int
   152  L7 uses var z int`
   153  
   154  	// don't abort at the first error
   155  	conf := Config{Error: func(err error) { t.Log(err) }}
   156  	defs := make(map[*ast.Ident]Object)
   157  	uses := make(map[*ast.Ident]Object)
   158  	_, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs, Uses: uses})
   159  	if s := err.Error(); !strings.HasSuffix(s, "cannot assign to w") {
   160  		t.Errorf("Check: unexpected error: %s", s)
   161  	}
   162  
   163  	var facts []string
   164  	for id, obj := range defs {
   165  		if obj != nil {
   166  			fact := fmt.Sprintf("L%d defs %s", fset.Position(id.Pos()).Line, obj)
   167  			facts = append(facts, fact)
   168  		}
   169  	}
   170  	for id, obj := range uses {
   171  		fact := fmt.Sprintf("L%d uses %s", fset.Position(id.Pos()).Line, obj)
   172  		facts = append(facts, fact)
   173  	}
   174  	slices.Sort(facts)
   175  
   176  	got := strings.Join(facts, "\n")
   177  	if got != want {
   178  		t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
   179  	}
   180  }
   181  
   182  // This tests that the package associated with the types.Object.Pkg method
   183  // is the type's package independent of the order in which the imports are
   184  // listed in the sources src1, src2 below.
   185  // The actual issue is in go/internal/gcimporter which has a corresponding
   186  // test; we leave this test here to verify correct behavior at the go/types
   187  // level.
   188  func TestIssue13898(t *testing.T) {
   189  	testenv.MustHaveGoBuild(t)
   190  
   191  	const src0 = `
   192  package main
   193  
   194  import "go/types"
   195  
   196  func main() {
   197  	var info types.Info
   198  	for _, obj := range info.Uses {
   199  		_ = obj.Pkg()
   200  	}
   201  }
   202  `
   203  	// like src0, but also imports go/importer
   204  	const src1 = `
   205  package main
   206  
   207  import (
   208  	"go/types"
   209  	_ "go/importer"
   210  )
   211  
   212  func main() {
   213  	var info types.Info
   214  	for _, obj := range info.Uses {
   215  		_ = obj.Pkg()
   216  	}
   217  }
   218  `
   219  	// like src1 but with different import order
   220  	// (used to fail with this issue)
   221  	const src2 = `
   222  package main
   223  
   224  import (
   225  	_ "go/importer"
   226  	"go/types"
   227  )
   228  
   229  func main() {
   230  	var info types.Info
   231  	for _, obj := range info.Uses {
   232  		_ = obj.Pkg()
   233  	}
   234  }
   235  `
   236  	f := func(test, src string) {
   237  		info := &Info{Uses: make(map[*ast.Ident]Object)}
   238  		mustTypecheck(src, nil, info)
   239  
   240  		var pkg *Package
   241  		count := 0
   242  		for id, obj := range info.Uses {
   243  			if id.Name == "Pkg" {
   244  				pkg = obj.Pkg()
   245  				count++
   246  			}
   247  		}
   248  		if count != 1 {
   249  			t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
   250  		}
   251  		if pkg.Name() != "types" {
   252  			t.Fatalf("%s: got %v; want package types", test, pkg)
   253  		}
   254  	}
   255  
   256  	f("src0", src0)
   257  	f("src1", src1)
   258  	f("src2", src2)
   259  }
   260  
   261  func TestIssue22525(t *testing.T) {
   262  	const src = `package p; func f() { var a, b, c, d, e int }`
   263  
   264  	got := "\n"
   265  	conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
   266  	typecheck(src, &conf, nil) // do not crash
   267  	want := "\n" +
   268  		"p:1:27: declared and not used: a\n" +
   269  		"p:1:30: declared and not used: b\n" +
   270  		"p:1:33: declared and not used: c\n" +
   271  		"p:1:36: declared and not used: d\n" +
   272  		"p:1:39: declared and not used: e\n"
   273  	if got != want {
   274  		t.Errorf("got: %swant: %s", got, want)
   275  	}
   276  }
   277  
   278  func TestIssue25627(t *testing.T) {
   279  	const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
   280  	// The src strings (without prefix) are constructed such that the number of semicolons
   281  	// plus one corresponds to the number of fields expected in the respective struct.
   282  	for _, src := range []string{
   283  		`struct { x Missing }`,
   284  		`struct { Missing }`,
   285  		`struct { *Missing }`,
   286  		`struct { unsafe.Pointer }`,
   287  		`struct { P }`,
   288  		`struct { *I }`,
   289  		`struct { a int; b Missing; *Missing }`,
   290  	} {
   291  		f := mustParse(fset, prefix+src)
   292  
   293  		cfg := Config{Importer: defaultImporter(fset), Error: func(err error) {}}
   294  		info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
   295  		_, err := cfg.Check(f.Name.Name, fset, []*ast.File{f}, info)
   296  		if err != nil {
   297  			if _, ok := err.(Error); !ok {
   298  				t.Fatal(err)
   299  			}
   300  		}
   301  
   302  		ast.Inspect(f, func(n ast.Node) bool {
   303  			if spec, _ := n.(*ast.TypeSpec); spec != nil {
   304  				if tv, ok := info.Types[spec.Type]; ok && spec.Name.Name == "T" {
   305  					want := strings.Count(src, ";") + 1
   306  					if got := tv.Type.(*Struct).NumFields(); got != want {
   307  						t.Errorf("%s: got %d fields; want %d", src, got, want)
   308  					}
   309  				}
   310  			}
   311  			return true
   312  		})
   313  	}
   314  }
   315  
   316  func TestIssue28005(t *testing.T) {
   317  	// method names must match defining interface name for this test
   318  	// (see last comment in this function)
   319  	sources := [...]string{
   320  		"package p; type A interface{ A() }",
   321  		"package p; type B interface{ B() }",
   322  		"package p; type X interface{ A; B }",
   323  	}
   324  
   325  	// compute original file ASTs
   326  	var orig [len(sources)]*ast.File
   327  	for i, src := range sources {
   328  		orig[i] = mustParse(fset, src)
   329  	}
   330  
   331  	// run the test for all order permutations of the incoming files
   332  	for _, perm := range [][len(sources)]int{
   333  		{0, 1, 2},
   334  		{0, 2, 1},
   335  		{1, 0, 2},
   336  		{1, 2, 0},
   337  		{2, 0, 1},
   338  		{2, 1, 0},
   339  	} {
   340  		// create file order permutation
   341  		files := make([]*ast.File, len(sources))
   342  		for i := range perm {
   343  			files[i] = orig[perm[i]]
   344  		}
   345  
   346  		// type-check package with given file order permutation
   347  		var conf Config
   348  		info := &Info{Defs: make(map[*ast.Ident]Object)}
   349  		_, err := conf.Check("", fset, files, info)
   350  		if err != nil {
   351  			t.Fatal(err)
   352  		}
   353  
   354  		// look for interface object X
   355  		var obj Object
   356  		for name, def := range info.Defs {
   357  			if name.Name == "X" {
   358  				obj = def
   359  				break
   360  			}
   361  		}
   362  		if obj == nil {
   363  			t.Fatal("object X not found")
   364  		}
   365  		iface := obj.Type().Underlying().(*Interface) // object X must be an interface
   366  
   367  		// Each iface method m is embedded; and m's receiver base type name
   368  		// must match the method's name per the choice in the source file.
   369  		for i := 0; i < iface.NumMethods(); i++ {
   370  			m := iface.Method(i)
   371  			recvName := m.Signature().Recv().Type().(*Named).Obj().Name()
   372  			if recvName != m.Name() {
   373  				t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
   374  			}
   375  		}
   376  	}
   377  }
   378  
   379  func TestIssue28282(t *testing.T) {
   380  	// create type interface { error }
   381  	et := Universe.Lookup("error").Type()
   382  	it := NewInterfaceType(nil, []Type{et})
   383  	it.Complete()
   384  	// verify that after completing the interface, the embedded method remains unchanged
   385  	want := et.Underlying().(*Interface).Method(0)
   386  	got := it.Method(0)
   387  	if got != want {
   388  		t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
   389  	}
   390  	// verify that lookup finds the same method in both interfaces (redundant check)
   391  	obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
   392  	if obj != want {
   393  		t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
   394  	}
   395  	obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
   396  	if obj != want {
   397  		t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
   398  	}
   399  }
   400  
   401  func TestIssue29029(t *testing.T) {
   402  	f1 := mustParse(fset, `package p; type A interface { M() }`)
   403  	f2 := mustParse(fset, `package p; var B interface { A }`)
   404  
   405  	// printInfo prints the *Func definitions recorded in info, one *Func per line.
   406  	printInfo := func(info *Info) string {
   407  		var buf strings.Builder
   408  		for _, obj := range info.Defs {
   409  			if fn, ok := obj.(*Func); ok {
   410  				fmt.Fprintln(&buf, fn)
   411  			}
   412  		}
   413  		return buf.String()
   414  	}
   415  
   416  	// The *Func (method) definitions for package p must be the same
   417  	// independent on whether f1 and f2 are type-checked together, or
   418  	// incrementally.
   419  
   420  	// type-check together
   421  	var conf Config
   422  	info := &Info{Defs: make(map[*ast.Ident]Object)}
   423  	check := NewChecker(&conf, fset, NewPackage("", "p"), info)
   424  	if err := check.Files([]*ast.File{f1, f2}); err != nil {
   425  		t.Fatal(err)
   426  	}
   427  	want := printInfo(info)
   428  
   429  	// type-check incrementally
   430  	info = &Info{Defs: make(map[*ast.Ident]Object)}
   431  	check = NewChecker(&conf, fset, NewPackage("", "p"), info)
   432  	if err := check.Files([]*ast.File{f1}); err != nil {
   433  		t.Fatal(err)
   434  	}
   435  	if err := check.Files([]*ast.File{f2}); err != nil {
   436  		t.Fatal(err)
   437  	}
   438  	got := printInfo(info)
   439  
   440  	if got != want {
   441  		t.Errorf("\ngot : %swant: %s", got, want)
   442  	}
   443  }
   444  
   445  func TestIssue34151(t *testing.T) {
   446  	const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
   447  	const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
   448  
   449  	a := mustTypecheck(asrc, nil, nil)
   450  
   451  	conf := Config{Importer: importHelper{pkg: a}}
   452  	mustTypecheck(bsrc, &conf, nil)
   453  }
   454  
   455  type importHelper struct {
   456  	pkg      *Package
   457  	fallback Importer
   458  }
   459  
   460  func (h importHelper) Import(path string) (*Package, error) {
   461  	if path == h.pkg.Path() {
   462  		return h.pkg, nil
   463  	}
   464  	if h.fallback == nil {
   465  		return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
   466  	}
   467  	return h.fallback.Import(path)
   468  }
   469  
   470  // TestIssue34921 verifies that we don't update an imported type's underlying
   471  // type when resolving an underlying type. Specifically, when determining the
   472  // underlying type of b.T (which is the underlying type of a.T, which is int)
   473  // we must not set the underlying type of a.T again since that would lead to
   474  // a race condition if package b is imported elsewhere, in a package that is
   475  // concurrently type-checked.
   476  func TestIssue34921(t *testing.T) {
   477  	defer func() {
   478  		if r := recover(); r != nil {
   479  			t.Error(r)
   480  		}
   481  	}()
   482  
   483  	var sources = []string{
   484  		`package a; type T int`,
   485  		`package b; import "a"; type T a.T`,
   486  	}
   487  
   488  	var pkg *Package
   489  	for _, src := range sources {
   490  		conf := Config{Importer: importHelper{pkg: pkg}}
   491  		pkg = mustTypecheck(src, &conf, nil) // pkg imported by the next package in this test
   492  	}
   493  }
   494  
   495  func TestIssue43088(t *testing.T) {
   496  	// type T1 struct {
   497  	//         _ T2
   498  	// }
   499  	//
   500  	// type T2 struct {
   501  	//         _ struct {
   502  	//                 _ T2
   503  	//         }
   504  	// }
   505  	n1 := NewTypeName(nopos, nil, "T1", nil)
   506  	T1 := NewNamed(n1, nil, nil)
   507  	n2 := NewTypeName(nopos, nil, "T2", nil)
   508  	T2 := NewNamed(n2, nil, nil)
   509  	s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
   510  	T1.SetUnderlying(s1)
   511  	s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
   512  	s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
   513  	T2.SetUnderlying(s3)
   514  
   515  	// These calls must terminate (no endless recursion).
   516  	Comparable(T1)
   517  	Comparable(T2)
   518  }
   519  
   520  func TestIssue44515(t *testing.T) {
   521  	typ := Unsafe.Scope().Lookup("Pointer").Type()
   522  
   523  	got := TypeString(typ, nil)
   524  	want := "unsafe.Pointer"
   525  	if got != want {
   526  		t.Errorf("got %q; want %q", got, want)
   527  	}
   528  
   529  	qf := func(pkg *Package) string {
   530  		if pkg == Unsafe {
   531  			return "foo"
   532  		}
   533  		return ""
   534  	}
   535  	got = TypeString(typ, qf)
   536  	want = "foo.Pointer"
   537  	if got != want {
   538  		t.Errorf("got %q; want %q", got, want)
   539  	}
   540  }
   541  
   542  func TestIssue43124(t *testing.T) {
   543  	// TODO(rFindley) move this to testdata by enhancing support for importing.
   544  
   545  	testenv.MustHaveGoBuild(t) // The go command is needed for the importer to determine the locations of stdlib .a files.
   546  
   547  	// All involved packages have the same name (template). Error messages should
   548  	// disambiguate between text/template and html/template by printing the full
   549  	// path.
   550  	const (
   551  		asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
   552  		bsrc = `
   553  package b
   554  
   555  import (
   556  	"a"
   557  	"html/template"
   558  )
   559  
   560  func _() {
   561  	// Packages should be fully qualified when there is ambiguity within the
   562  	// error string itself.
   563  	a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
   564  }
   565  `
   566  		csrc = `
   567  package c
   568  
   569  import (
   570  	"a"
   571  	"fmt"
   572  	"html/template"
   573  )
   574  
   575  // go.dev/issue/46905: make sure template is not the first package qualified.
   576  var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
   577  
   578  // Packages should be fully qualified when there is ambiguity in reachable
   579  // packages. In this case both a (and for that matter html/template) import
   580  // text/template.
   581  func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
   582  `
   583  
   584  		tsrc = `
   585  package template
   586  
   587  import "text/template"
   588  
   589  type T int
   590  
   591  // Verify that the current package name also causes disambiguation.
   592  var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
   593  `
   594  	)
   595  
   596  	a := mustTypecheck(asrc, nil, nil)
   597  	imp := importHelper{
   598  		pkg: a,
   599  		// TODO(adonovan): use same FileSet as mustTypecheck.
   600  		fallback: defaultImporter(token.NewFileSet()),
   601  	}
   602  
   603  	withImporter := func(cfg *Config) {
   604  		cfg.Importer = imp
   605  	}
   606  
   607  	testFiles(t, []string{"b.go"}, [][]byte{[]byte(bsrc)}, false, withImporter)
   608  	testFiles(t, []string{"c.go"}, [][]byte{[]byte(csrc)}, false, withImporter)
   609  	testFiles(t, []string{"t.go"}, [][]byte{[]byte(tsrc)}, false, withImporter)
   610  }
   611  
   612  func TestIssue50646(t *testing.T) {
   613  	anyType := Universe.Lookup("any").Type().Underlying()
   614  	comparableType := Universe.Lookup("comparable").Type()
   615  
   616  	if !Comparable(anyType) {
   617  		t.Error("any is not a comparable type")
   618  	}
   619  	if !Comparable(comparableType) {
   620  		t.Error("comparable is not a comparable type")
   621  	}
   622  
   623  	if Implements(anyType, comparableType.Underlying().(*Interface)) {
   624  		t.Error("any implements comparable")
   625  	}
   626  	if !Implements(comparableType, anyType.(*Interface)) {
   627  		t.Error("comparable does not implement any")
   628  	}
   629  
   630  	if AssignableTo(anyType, comparableType) {
   631  		t.Error("any assignable to comparable")
   632  	}
   633  	if !AssignableTo(comparableType, anyType) {
   634  		t.Error("comparable not assignable to any")
   635  	}
   636  }
   637  
   638  func TestIssue55030(t *testing.T) {
   639  	// makeSig makes the signature func(typ...)
   640  	makeSig := func(typ Type) {
   641  		par := NewVar(nopos, nil, "", typ)
   642  		params := NewTuple(par)
   643  		NewSignatureType(nil, nil, nil, params, nil, true)
   644  	}
   645  
   646  	// makeSig must not panic for the following (example) types:
   647  	// []int
   648  	makeSig(NewSlice(Typ[Int]))
   649  
   650  	// string
   651  	makeSig(Typ[String])
   652  
   653  	// P where P's core type is string
   654  	{
   655  		P := NewTypeName(nopos, nil, "P", nil) // [P string]
   656  		makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
   657  	}
   658  
   659  	// P where P's core type is an (unnamed) slice
   660  	{
   661  		P := NewTypeName(nopos, nil, "P", nil) // [P []int]
   662  		makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
   663  	}
   664  
   665  	// P where P's core type is bytestring (i.e., string or []byte)
   666  	{
   667  		t1 := NewTerm(true, Typ[String])          // ~string
   668  		t2 := NewTerm(false, NewSlice(Typ[Byte])) // []byte
   669  		u := NewUnion([]*Term{t1, t2})            // ~string | []byte
   670  		P := NewTypeName(nopos, nil, "P", nil)    // [P ~string | []byte]
   671  		makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
   672  	}
   673  }
   674  
   675  func TestIssue51093(t *testing.T) {
   676  	// Each test stands for a conversion of the form P(val)
   677  	// where P is a type parameter with typ as constraint.
   678  	// The test ensures that P(val) has the correct type P
   679  	// and is not a constant.
   680  	var tests = []struct {
   681  		typ string
   682  		val string
   683  	}{
   684  		{"bool", "false"},
   685  		{"int", "-1"},
   686  		{"uint", "1.0"},
   687  		{"rune", "'a'"},
   688  		{"float64", "3.5"},
   689  		{"complex64", "1.25"},
   690  		{"string", "\"foo\""},
   691  
   692  		// some more complex constraints
   693  		{"~byte", "1"},
   694  		{"~int | ~float64 | complex128", "1"},
   695  		{"~uint64 | ~rune", "'X'"},
   696  	}
   697  
   698  	for _, test := range tests {
   699  		src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
   700  		types := make(map[ast.Expr]TypeAndValue)
   701  		mustTypecheck(src, nil, &Info{Types: types})
   702  
   703  		var n int
   704  		for x, tv := range types {
   705  			if x, _ := x.(*ast.CallExpr); x != nil {
   706  				// there must be exactly one CallExpr which is the P(val) conversion
   707  				n++
   708  				tpar, _ := tv.Type.(*TypeParam)
   709  				if tpar == nil {
   710  					t.Fatalf("%s: got type %s, want type parameter", ExprString(x), tv.Type)
   711  				}
   712  				if name := tpar.Obj().Name(); name != "P" {
   713  					t.Fatalf("%s: got type parameter name %s, want P", ExprString(x), name)
   714  				}
   715  				// P(val) must not be constant
   716  				if tv.Value != nil {
   717  					t.Errorf("%s: got constant value %s (%s), want no constant", ExprString(x), tv.Value, tv.Value.String())
   718  				}
   719  			}
   720  		}
   721  
   722  		if n != 1 {
   723  			t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
   724  		}
   725  	}
   726  }
   727  
   728  func TestIssue54258(t *testing.T) {
   729  
   730  	tests := []struct{ main, b, want string }{
   731  		{ //---------------------------------------------------------------
   732  			`package main
   733  import "b"
   734  type I0 interface {
   735  	M0(w struct{ f string })
   736  }
   737  var _ I0 = b.S{}
   738  `,
   739  			`package b
   740  type S struct{}
   741  func (S) M0(struct{ f string }) {}
   742  `,
   743  			`6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I0 value in variable declaration: b[.]S does not implement I0 [(]wrong type for method M0[)]
   744  .*have M0[(]struct{f string /[*] package b [*]/ }[)]
   745  .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
   746  
   747  		{ //---------------------------------------------------------------
   748  			`package main
   749  import "b"
   750  type I1 interface {
   751  	M1(struct{ string })
   752  }
   753  var _ I1 = b.S{}
   754  `,
   755  			`package b
   756  type S struct{}
   757  func (S) M1(struct{ string }) {}
   758  `,
   759  			`6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I1 value in variable declaration: b[.]S does not implement I1 [(]wrong type for method M1[)]
   760  .*have M1[(]struct{string /[*] package b [*]/ }[)]
   761  .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
   762  
   763  		{ //---------------------------------------------------------------
   764  			`package main
   765  import "b"
   766  type I2 interface {
   767  	M2(y struct{ f struct{ f string } })
   768  }
   769  var _ I2 = b.S{}
   770  `,
   771  			`package b
   772  type S struct{}
   773  func (S) M2(struct{ f struct{ f string } }) {}
   774  `,
   775  			`6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I2 value in variable declaration: b[.]S does not implement I2 [(]wrong type for method M2[)]
   776  .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
   777  .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
   778  
   779  		{ //---------------------------------------------------------------
   780  			`package main
   781  import "b"
   782  type I3 interface {
   783  	M3(z struct{ F struct{ f string } })
   784  }
   785  var _ I3 = b.S{}
   786  `,
   787  			`package b
   788  type S struct{}
   789  func (S) M3(struct{ F struct{ f string } }) {}
   790  `,
   791  			`6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I3 value in variable declaration: b[.]S does not implement I3 [(]wrong type for method M3[)]
   792  .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
   793  .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
   794  
   795  		{ //---------------------------------------------------------------
   796  			`package main
   797  import "b"
   798  type I4 interface {
   799  	M4(_ struct { *string })
   800  }
   801  var _ I4 = b.S{}
   802  `,
   803  			`package b
   804  type S struct{}
   805  func (S) M4(struct { *string }) {}
   806  `,
   807  			`6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I4 value in variable declaration: b[.]S does not implement I4 [(]wrong type for method M4[)]
   808  .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
   809  .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
   810  
   811  		{ //---------------------------------------------------------------
   812  			`package main
   813  import "b"
   814  type t struct{ A int }
   815  type I5 interface {
   816  	M5(_ struct {b.S;t})
   817  }
   818  var _ I5 = b.S{}
   819  `,
   820  			`package b
   821  type S struct{}
   822  type t struct{ A int }
   823  func (S) M5(struct {S;t}) {}
   824  `,
   825  			`7:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I5 value in variable declaration: b[.]S does not implement I5 [(]wrong type for method M5[)]
   826  .*have M5[(]struct{b[.]S; b[.]t}[)]
   827  .*want M5[(]struct{b[.]S; t}[)]`},
   828  	}
   829  
   830  	fset := token.NewFileSet()
   831  	test := func(main, b, want string) {
   832  		re := regexp.MustCompile(want)
   833  		bpkg := mustTypecheck(b, nil, nil)
   834  		mast := mustParse(fset, main)
   835  		conf := Config{Importer: importHelper{pkg: bpkg}}
   836  		_, err := conf.Check(mast.Name.Name, fset, []*ast.File{mast}, nil)
   837  		if err == nil {
   838  			t.Error("Expected failure, but it did not")
   839  		} else if got := err.Error(); !re.MatchString(got) {
   840  			t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
   841  		} else if testing.Verbose() {
   842  			t.Logf("Saw expected\n\t%s", err.Error())
   843  		}
   844  	}
   845  	for _, t := range tests {
   846  		test(t.main, t.b, t.want)
   847  	}
   848  }
   849  
   850  func TestIssue59944(t *testing.T) {
   851  	testenv.MustHaveCGO(t)
   852  
   853  	// Methods declared on aliases of cgo types are not permitted.
   854  	const src = `// -gotypesalias=1
   855  
   856  package p
   857  
   858  /*
   859  struct layout {};
   860  */
   861  import "C"
   862  
   863  type Layout = C.struct_layout
   864  
   865  func (*Layout /* ERROR "cannot define new methods on non-local type Layout" */) Binding() {}
   866  `
   867  
   868  	// code generated by cmd/cgo for the above source.
   869  	const cgoTypes = `
   870  // Code generated by cmd/cgo; DO NOT EDIT.
   871  
   872  package p
   873  
   874  import "unsafe"
   875  
   876  import "syscall"
   877  
   878  import _cgopackage "runtime/cgo"
   879  
   880  type _ _cgopackage.Incomplete
   881  var _ syscall.Errno
   882  func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
   883  
   884  //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
   885  var _Cgo_always_false bool
   886  //go:linkname _Cgo_use runtime.cgoUse
   887  func _Cgo_use(interface{})
   888  //go:linkname _Cgo_keepalive runtime.cgoKeepAlive
   889  //go:noescape
   890  func _Cgo_keepalive(interface{})
   891  //go:linkname _Cgo_no_callback runtime.cgoNoCallback
   892  func _Cgo_no_callback(bool)
   893  type _Ctype_struct_layout struct {
   894  }
   895  
   896  type _Ctype_void [0]byte
   897  
   898  //go:linkname _cgo_runtime_cgocall runtime.cgocall
   899  func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
   900  
   901  //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
   902  //go:noescape
   903  func _cgoCheckPointer(interface{}, interface{})
   904  
   905  //go:linkname _cgoCheckResult runtime.cgoCheckResult
   906  //go:noescape
   907  func _cgoCheckResult(interface{})
   908  `
   909  	testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, false, func(cfg *Config) {
   910  		*boolFieldAddr(cfg, "go115UsesCgo") = true
   911  	})
   912  }
   913  
   914  func TestIssue61931(t *testing.T) {
   915  	const src = `
   916  package p
   917  
   918  func A(func(any), ...any) {}
   919  func B[T any](T)          {}
   920  
   921  func _() {
   922  	A(B, nil // syntax error: missing ',' before newline in argument list
   923  }
   924  `
   925  	fset := token.NewFileSet()
   926  	f, err := parser.ParseFile(fset, pkgName(src), src, 0)
   927  	if err == nil {
   928  		t.Fatal("expected syntax error")
   929  	}
   930  
   931  	var conf Config
   932  	conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // must not panic
   933  }
   934  
   935  func TestIssue61938(t *testing.T) {
   936  	const src = `
   937  package p
   938  
   939  func f[T any]() {}
   940  func _()        { f() }
   941  `
   942  	// no error handler provided (this issue)
   943  	var conf Config
   944  	typecheck(src, &conf, nil) // must not panic
   945  
   946  	// with error handler (sanity check)
   947  	conf.Error = func(error) {}
   948  	typecheck(src, &conf, nil) // must not panic
   949  }
   950  
   951  func TestIssue63260(t *testing.T) {
   952  	const src = `
   953  package p
   954  
   955  func _() {
   956          use(f[*string])
   957  }
   958  
   959  func use(func()) {}
   960  
   961  func f[I *T, T any]() {
   962          var v T
   963          _ = v
   964  }`
   965  
   966  	info := Info{
   967  		Defs: make(map[*ast.Ident]Object),
   968  	}
   969  	pkg := mustTypecheck(src, nil, &info)
   970  
   971  	// get type parameter T in signature of f
   972  	T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
   973  	if T.Obj().Name() != "T" {
   974  		t.Fatalf("got type parameter %s, want T", T)
   975  	}
   976  
   977  	// get type of variable v in body of f
   978  	var v Object
   979  	for name, obj := range info.Defs {
   980  		if name.Name == "v" {
   981  			v = obj
   982  			break
   983  		}
   984  	}
   985  	if v == nil {
   986  		t.Fatal("variable v not found")
   987  	}
   988  
   989  	// type of v and T must be pointer-identical
   990  	if v.Type() != T {
   991  		t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)
   992  	}
   993  }
   994  
   995  func TestIssue44410(t *testing.T) {
   996  	const src = `
   997  package p
   998  
   999  type A = []int
  1000  type S struct{ A }
  1001  `
  1002  
  1003  	t.Setenv("GODEBUG", "gotypesalias=1")
  1004  	pkg := mustTypecheck(src, nil, nil)
  1005  
  1006  	S := pkg.Scope().Lookup("S")
  1007  	if S == nil {
  1008  		t.Fatal("object S not found")
  1009  	}
  1010  
  1011  	got := S.String()
  1012  	const want = "type p.S struct{p.A}"
  1013  	if got != want {
  1014  		t.Fatalf("got %q; want %q", got, want)
  1015  	}
  1016  }
  1017  
  1018  func TestIssue59831(t *testing.T) {
  1019  	// Package a exports a type S with an unexported method m;
  1020  	// the tests check the error messages when m is not found.
  1021  	const asrc = `package a; type S struct{}; func (S) m() {}`
  1022  	apkg := mustTypecheck(asrc, nil, nil)
  1023  
  1024  	// Package b exports a type S with an exported method m;
  1025  	// the tests check the error messages when M is not found.
  1026  	const bsrc = `package b; type S struct{}; func (S) M() {}`
  1027  	bpkg := mustTypecheck(bsrc, nil, nil)
  1028  
  1029  	tests := []struct {
  1030  		imported *Package
  1031  		src, err string
  1032  	}{
  1033  		// tests importing a (or nothing)
  1034  		{apkg, `package a1; import "a"; var _ interface { M() } = a.S{}`,
  1035  			"a.S does not implement interface{M()} (missing method M) have m() want M()"},
  1036  
  1037  		{apkg, `package a2; import "a"; var _ interface { m() } = a.S{}`,
  1038  			"a.S does not implement interface{m()} (unexported method m)"}, // test for issue
  1039  
  1040  		{nil, `package a3; type S struct{}; func (S) m(); var _ interface { M() } = S{}`,
  1041  			"S does not implement interface{M()} (missing method M) have m() want M()"},
  1042  
  1043  		{nil, `package a4; type S struct{}; func (S) m(); var _ interface { m() } = S{}`,
  1044  			""}, // no error expected
  1045  
  1046  		{nil, `package a5; type S struct{}; func (S) m(); var _ interface { n() } = S{}`,
  1047  			"S does not implement interface{n()} (missing method n)"},
  1048  
  1049  		// tests importing b (or nothing)
  1050  		{bpkg, `package b1; import "b"; var _ interface { m() } = b.S{}`,
  1051  			"b.S does not implement interface{m()} (missing method m) have M() want m()"},
  1052  
  1053  		{bpkg, `package b2; import "b"; var _ interface { M() } = b.S{}`,
  1054  			""}, // no error expected
  1055  
  1056  		{nil, `package b3; type S struct{}; func (S) M(); var _ interface { M() } = S{}`,
  1057  			""}, // no error expected
  1058  
  1059  		{nil, `package b4; type S struct{}; func (S) M(); var _ interface { m() } = S{}`,
  1060  			"S does not implement interface{m()} (missing method m) have M() want m()"},
  1061  
  1062  		{nil, `package b5; type S struct{}; func (S) M(); var _ interface { n() } = S{}`,
  1063  			"S does not implement interface{n()} (missing method n)"},
  1064  	}
  1065  
  1066  	for _, test := range tests {
  1067  		// typecheck test source
  1068  		conf := Config{Importer: importHelper{pkg: test.imported}}
  1069  		pkg, err := typecheck(test.src, &conf, nil)
  1070  		if err == nil {
  1071  			if test.err != "" {
  1072  				t.Errorf("package %s: got no error, want %q", pkg.Name(), test.err)
  1073  			}
  1074  			continue
  1075  		}
  1076  		if test.err == "" {
  1077  			t.Errorf("package %s: got %q, want not error", pkg.Name(), err.Error())
  1078  		}
  1079  
  1080  		// flatten reported error message
  1081  		errmsg := strings.ReplaceAll(err.Error(), "\n", " ")
  1082  		errmsg = strings.ReplaceAll(errmsg, "\t", "")
  1083  
  1084  		// verify error message
  1085  		if !strings.Contains(errmsg, test.err) {
  1086  			t.Errorf("package %s: got %q, want %q", pkg.Name(), errmsg, test.err)
  1087  		}
  1088  	}
  1089  }
  1090  
  1091  func TestIssue64759(t *testing.T) {
  1092  	const src = `
  1093  //go:build go1.18
  1094  package p
  1095  
  1096  func f[S ~[]E, E any](S) {}
  1097  
  1098  func _() {
  1099  	f([]string{})
  1100  }
  1101  `
  1102  	// Per the go:build directive, the source must typecheck
  1103  	// even though the (module) Go version is set to go1.17.
  1104  	conf := Config{GoVersion: "go1.17"}
  1105  	mustTypecheck(src, &conf, nil)
  1106  }
  1107  
  1108  func TestIssue68334(t *testing.T) {
  1109  	const src = `
  1110  package p
  1111  
  1112  func f(x int) {
  1113  	for i, j := range x {
  1114  		_, _ = i, j
  1115  	}
  1116  	var a, b int
  1117  	for a, b = range x {
  1118  		_, _ = a, b
  1119  	}
  1120  }
  1121  `
  1122  
  1123  	got := ""
  1124  	conf := Config{
  1125  		GoVersion: "go1.21",                                      // #68334 requires GoVersion <= 1.21
  1126  		Error:     func(err error) { got += err.Error() + "\n" }, // #68334 requires Error != nil
  1127  	}
  1128  	typecheck(src, &conf, nil) // do not crash
  1129  
  1130  	want := "p:5:20: cannot range over x (variable of type int): requires go1.22 or later\n" +
  1131  		"p:9:19: cannot range over x (variable of type int): requires go1.22 or later\n"
  1132  	if got != want {
  1133  		t.Errorf("got: %s want: %s", got, want)
  1134  	}
  1135  }
  1136  
  1137  func TestIssue68877(t *testing.T) {
  1138  	const src = `
  1139  package p
  1140  
  1141  type (
  1142  	S struct{}
  1143  	A = S
  1144  	T A
  1145  )`
  1146  
  1147  	t.Setenv("GODEBUG", "gotypesalias=1")
  1148  	pkg := mustTypecheck(src, nil, nil)
  1149  	T := pkg.Scope().Lookup("T").(*TypeName)
  1150  	got := T.String() // this must not panic (was issue)
  1151  	const want = "type p.T struct{}"
  1152  	if got != want {
  1153  		t.Errorf("got %s, want %s", got, want)
  1154  	}
  1155  }
  1156  
  1157  func TestIssue69092(t *testing.T) {
  1158  	const src = `
  1159  package p
  1160  
  1161  var _ = T{{x}}
  1162  `
  1163  
  1164  	fset := token.NewFileSet()
  1165  	file := mustParse(fset, src)
  1166  	conf := Config{Error: func(err error) {}} // ignore errors
  1167  	info := Info{Types: make(map[ast.Expr]TypeAndValue)}
  1168  	conf.Check("p", fset, []*ast.File{file}, &info)
  1169  
  1170  	// look for {x} expression
  1171  	outer := file.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values[0].(*ast.CompositeLit) // T{{x}}
  1172  	inner := outer.Elts[0]                                                                        // {x}
  1173  
  1174  	// type of {x} must have been recorded
  1175  	tv, ok := info.Types[inner]
  1176  	if !ok {
  1177  		t.Fatal("no type found for {x}")
  1178  	}
  1179  	if tv.Type != Typ[Invalid] {
  1180  		t.Fatalf("unexpected type for {x}: %s", tv.Type)
  1181  	}
  1182  }
  1183  

View as plain text