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.
5 // This file implements tests for various issues.
24 func TestIssue5770(t *testing.T) {
25 _, err := typecheck(`package p; type S struct{T}`, nil, nil)
26 const want = "undefined: T"
27 if err == nil || !strings.Contains(err.Error(), want) {
28 t.Errorf("got: %v; want: %s", err, want)
32 func TestIssue5849(t *testing.T) {
40 _ = uint64(64 << s + s)
41 _ = (interface{})("foo")
42 _ = (interface{})(nil)
44 types := make(map[ast.Expr]TypeAndValue)
45 mustTypecheck(src, nil, &Info{Types: types})
47 for x, tv := range types {
49 switch x := x.(type) {
59 want = Typ[Uint] // because of "+ s", s is of type uint
65 want = Typ[UntypedNil]
68 if want != nil && !Identical(tv.Type, want) {
69 t.Errorf("got %s; want %s", tv.Type, want)
74 func TestIssue6413(t *testing.T) {
83 types := make(map[ast.Expr]TypeAndValue)
84 mustTypecheck(src, nil, &Info{Types: types})
88 for x, tv := range types {
89 if _, ok := x.(*ast.CallExpr); ok {
91 t.Errorf("%s: got %s; want %s", fset.Position(x.Pos()), tv.Type, want)
98 t.Errorf("got %d CallExprs; want 2", n)
102 func TestIssue7245(t *testing.T) {
105 func (T) m() (res bool) { return }
106 type T struct{} // receiver type after method declaration
108 f := mustParse(fset, src)
111 defs := make(map[*ast.Ident]Object)
112 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs})
117 m := f.Decls[0].(*ast.FuncDecl)
118 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
119 res2 := defs[m.Type.Results.List[0].Names[0]].(*Var)
122 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
126 // This tests that uses of existing vars on the LHS of an assignment
127 // are Uses, not Defs; and also that the (illegal) use of a non-var on
128 // the LHS of an assignment is a Use nonetheless.
129 func TestIssue7827(t *testing.T) {
133 const w = 1 // defs w
134 x, y := 2, 3 // defs x, y
135 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
136 _, _, _ = x, y, z // uses x, y, z
139 // We need a specific fileset in this test below for positions.
140 // Cannot use typecheck helper.
141 fset := token.NewFileSet()
142 f := mustParse(fset, src)
144 const want = `L3 defs func p._()
145 L4 defs const w untyped int
149 L6 uses const w untyped int
155 // don't abort at the first error
156 conf := Config{Error: func(err error) { t.Log(err) }}
157 defs := make(map[*ast.Ident]Object)
158 uses := make(map[*ast.Ident]Object)
159 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs, Uses: uses})
160 if s := err.Error(); !strings.HasSuffix(s, "cannot assign to w") {
161 t.Errorf("Check: unexpected error: %s", s)
165 for id, obj := range defs {
167 fact := fmt.Sprintf("L%d defs %s", fset.Position(id.Pos()).Line, obj)
168 facts = append(facts, fact)
171 for id, obj := range uses {
172 fact := fmt.Sprintf("L%d uses %s", fset.Position(id.Pos()).Line, obj)
173 facts = append(facts, fact)
177 got := strings.Join(facts, "\n")
179 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
183 // This tests that the package associated with the types.Object.Pkg method
184 // is the type's package independent of the order in which the imports are
185 // listed in the sources src1, src2 below.
186 // The actual issue is in go/internal/gcimporter which has a corresponding
187 // test; we leave this test here to verify correct behavior at the go/types
189 func TestIssue13898(t *testing.T) {
190 testenv.MustHaveGoBuild(t)
199 for _, obj := range info.Uses {
204 // like src0, but also imports go/importer
215 for _, obj := range info.Uses {
220 // like src1 but with different import order
221 // (used to fail with this issue)
232 for _, obj := range info.Uses {
237 f := func(test, src string) {
238 info := &Info{Uses: make(map[*ast.Ident]Object)}
239 mustTypecheck(src, nil, info)
243 for id, obj := range info.Uses {
244 if id.Name == "Pkg" {
250 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
252 if pkg.Name() != "types" {
253 t.Fatalf("%s: got %v; want package types", test, pkg)
262 func TestIssue22525(t *testing.T) {
263 const src = `package p; func f() { var a, b, c, d, e int }`
266 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
267 typecheck(src, &conf, nil) // do not crash
269 p:1:27: a declared and not used
270 p:1:30: b declared and not used
271 p:1:33: c declared and not used
272 p:1:36: d declared and not used
273 p:1:39: e declared and not used
276 t.Errorf("got: %swant: %s", got, want)
280 func TestIssue25627(t *testing.T) {
281 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
282 // The src strings (without prefix) are constructed such that the number of semicolons
283 // plus one corresponds to the number of fields expected in the respective struct.
284 for _, src := range []string{
285 `struct { x Missing }`,
286 `struct { Missing }`,
287 `struct { *Missing }`,
288 `struct { unsafe.Pointer }`,
291 `struct { a int; b Missing; *Missing }`,
293 f := mustParse(fset, prefix+src)
295 cfg := Config{Importer: importer.Default(), Error: func(err error) {}}
296 info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
297 _, err := cfg.Check(f.Name.Name, fset, []*ast.File{f}, info)
299 if _, ok := err.(Error); !ok {
304 ast.Inspect(f, func(n ast.Node) bool {
305 if spec, _ := n.(*ast.TypeSpec); spec != nil {
306 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Name == "T" {
307 want := strings.Count(src, ";") + 1
308 if got := tv.Type.(*Struct).NumFields(); got != want {
309 t.Errorf("%s: got %d fields; want %d", src, got, want)
318 func TestIssue28005(t *testing.T) {
319 // method names must match defining interface name for this test
320 // (see last comment in this function)
321 sources := [...]string{
322 "package p; type A interface{ A() }",
323 "package p; type B interface{ B() }",
324 "package p; type X interface{ A; B }",
327 // compute original file ASTs
328 var orig [len(sources)]*ast.File
329 for i, src := range sources {
330 orig[i] = mustParse(fset, src)
333 // run the test for all order permutations of the incoming files
334 for _, perm := range [][len(sources)]int{
342 // create file order permutation
343 files := make([]*ast.File, len(sources))
344 for i := range perm {
345 files[i] = orig[perm[i]]
348 // type-check package with given file order permutation
350 info := &Info{Defs: make(map[*ast.Ident]Object)}
351 _, err := conf.Check("", fset, files, info)
356 // look for interface object X
358 for name, def := range info.Defs {
359 if name.Name == "X" {
365 t.Fatal("object X not found")
367 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
369 // Each iface method m is embedded; and m's receiver base type name
370 // must match the method's name per the choice in the source file.
371 for i := 0; i < iface.NumMethods(); i++ {
373 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
374 if recvName != m.Name() {
375 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
381 func TestIssue28282(t *testing.T) {
382 // create type interface { error }
383 et := Universe.Lookup("error").Type()
384 it := NewInterfaceType(nil, []Type{et})
386 // verify that after completing the interface, the embedded method remains unchanged
387 want := et.Underlying().(*Interface).Method(0)
390 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
392 // verify that lookup finds the same method in both interfaces (redundant check)
393 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
395 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
397 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
399 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
403 func TestIssue29029(t *testing.T) {
404 f1 := mustParse(fset, `package p; type A interface { M() }`)
405 f2 := mustParse(fset, `package p; var B interface { A }`)
407 // printInfo prints the *Func definitions recorded in info, one *Func per line.
408 printInfo := func(info *Info) string {
409 var buf strings.Builder
410 for _, obj := range info.Defs {
411 if fn, ok := obj.(*Func); ok {
412 fmt.Fprintln(&buf, fn)
418 // The *Func (method) definitions for package p must be the same
419 // independent on whether f1 and f2 are type-checked together, or
422 // type-check together
424 info := &Info{Defs: make(map[*ast.Ident]Object)}
425 check := NewChecker(&conf, fset, NewPackage("", "p"), info)
426 if err := check.Files([]*ast.File{f1, f2}); err != nil {
429 want := printInfo(info)
431 // type-check incrementally
432 info = &Info{Defs: make(map[*ast.Ident]Object)}
433 check = NewChecker(&conf, fset, NewPackage("", "p"), info)
434 if err := check.Files([]*ast.File{f1}); err != nil {
437 if err := check.Files([]*ast.File{f2}); err != nil {
440 got := printInfo(info)
443 t.Errorf("\ngot : %swant: %s", got, want)
447 func TestIssue34151(t *testing.T) {
448 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
449 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
451 a := mustTypecheck(asrc, nil, nil)
453 conf := Config{Importer: importHelper{pkg: a}}
454 mustTypecheck(bsrc, &conf, nil)
457 type importHelper struct {
462 func (h importHelper) Import(path string) (*Package, error) {
463 if path == h.pkg.Path() {
466 if h.fallback == nil {
467 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
469 return h.fallback.Import(path)
472 // TestIssue34921 verifies that we don't update an imported type's underlying
473 // type when resolving an underlying type. Specifically, when determining the
474 // underlying type of b.T (which is the underlying type of a.T, which is int)
475 // we must not set the underlying type of a.T again since that would lead to
476 // a race condition if package b is imported elsewhere, in a package that is
477 // concurrently type-checked.
478 func TestIssue34921(t *testing.T) {
480 if r := recover(); r != nil {
485 var sources = []string{
486 `package a; type T int`,
487 `package b; import "a"; type T a.T`,
491 for _, src := range sources {
492 conf := Config{Importer: importHelper{pkg: pkg}}
493 pkg = mustTypecheck(src, &conf, nil) // pkg imported by the next package in this test
497 func TestIssue43088(t *testing.T) {
507 n1 := NewTypeName(nopos, nil, "T1", nil)
508 T1 := NewNamed(n1, nil, nil)
509 n2 := NewTypeName(nopos, nil, "T2", nil)
510 T2 := NewNamed(n2, nil, nil)
511 s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
513 s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
514 s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
517 // These calls must terminate (no endless recursion).
522 func TestIssue44515(t *testing.T) {
523 typ := Unsafe.Scope().Lookup("Pointer").Type()
525 got := TypeString(typ, nil)
526 want := "unsafe.Pointer"
528 t.Errorf("got %q; want %q", got, want)
531 qf := func(pkg *Package) string {
537 got = TypeString(typ, qf)
540 t.Errorf("got %q; want %q", got, want)
544 func TestIssue43124(t *testing.T) {
545 // TODO(rFindley) move this to testdata by enhancing support for importing.
547 testenv.MustHaveGoBuild(t) // The go command is needed for the importer to determine the locations of stdlib .a files.
549 // All involved packages have the same name (template). Error messages should
550 // disambiguate between text/template and html/template by printing the full
553 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
563 // Packages should be fully qualified when there is ambiguity within the
564 // error string itself.
565 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
577 // go.dev/issue/46905: make sure template is not the first package qualified.
578 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
580 // Packages should be fully qualified when there is ambiguity in reachable
581 // packages. In this case both a (and for that matter html/template) import
583 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
589 import "text/template"
593 // Verify that the current package name also causes disambiguation.
594 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
598 a := mustTypecheck(asrc, nil, nil)
599 imp := importHelper{pkg: a, fallback: importer.Default()}
601 withImporter := func(cfg *Config) {
605 testFiles(t, []string{"b.go"}, [][]byte{[]byte(bsrc)}, false, withImporter)
606 testFiles(t, []string{"c.go"}, [][]byte{[]byte(csrc)}, false, withImporter)
607 testFiles(t, []string{"t.go"}, [][]byte{[]byte(tsrc)}, false, withImporter)
610 func TestIssue50646(t *testing.T) {
611 anyType := Universe.Lookup("any").Type()
612 comparableType := Universe.Lookup("comparable").Type()
614 if !Comparable(anyType) {
615 t.Error("any is not a comparable type")
617 if !Comparable(comparableType) {
618 t.Error("comparable is not a comparable type")
621 if Implements(anyType, comparableType.Underlying().(*Interface)) {
622 t.Error("any implements comparable")
624 if !Implements(comparableType, anyType.(*Interface)) {
625 t.Error("comparable does not implement any")
628 if AssignableTo(anyType, comparableType) {
629 t.Error("any assignable to comparable")
631 if !AssignableTo(comparableType, anyType) {
632 t.Error("comparable not assignable to any")
636 func TestIssue55030(t *testing.T) {
637 // makeSig makes the signature func(typ...)
638 makeSig := func(typ Type) {
639 par := NewVar(nopos, nil, "", typ)
640 params := NewTuple(par)
641 NewSignatureType(nil, nil, nil, params, nil, true)
644 // makeSig must not panic for the following (example) types:
646 makeSig(NewSlice(Typ[Int]))
651 // P where P's core type is string
653 P := NewTypeName(nopos, nil, "P", nil) // [P string]
654 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
657 // P where P's core type is an (unnamed) slice
659 P := NewTypeName(nopos, nil, "P", nil) // [P []int]
660 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
663 // P where P's core type is bytestring (i.e., string or []byte)
665 t1 := NewTerm(true, Typ[String]) // ~string
666 t2 := NewTerm(false, NewSlice(Typ[Byte])) // []byte
667 u := NewUnion([]*Term{t1, t2}) // ~string | []byte
668 P := NewTypeName(nopos, nil, "P", nil) // [P ~string | []byte]
669 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
673 func TestIssue51093(t *testing.T) {
674 // Each test stands for a conversion of the form P(val)
675 // where P is a type parameter with typ as constraint.
676 // The test ensures that P(val) has the correct type P
677 // and is not a constant.
678 var tests = []struct {
687 {"complex64", "1.25"},
688 {"string", "\"foo\""},
690 // some more complex constraints
692 {"~int | ~float64 | complex128", "1"},
693 {"~uint64 | ~rune", "'X'"},
696 for _, test := range tests {
697 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
698 types := make(map[ast.Expr]TypeAndValue)
699 mustTypecheck(src, nil, &Info{Types: types})
702 for x, tv := range types {
703 if x, _ := x.(*ast.CallExpr); x != nil {
704 // there must be exactly one CallExpr which is the P(val) conversion
706 tpar, _ := tv.Type.(*TypeParam)
708 t.Fatalf("%s: got type %s, want type parameter", ExprString(x), tv.Type)
710 if name := tpar.Obj().Name(); name != "P" {
711 t.Fatalf("%s: got type parameter name %s, want P", ExprString(x), name)
713 // P(val) must not be constant
715 t.Errorf("%s: got constant value %s (%s), want no constant", ExprString(x), tv.Value, tv.Value.String())
721 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
726 func TestIssue54258(t *testing.T) {
728 tests := []struct{ main, b, want string }{
729 { //---------------------------------------------------------------
733 M0(w struct{ f string })
739 func (S) M0(struct{ f string }) {}
741 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I0 value in variable declaration: b[.]S does not implement I0 [(]wrong type for method M0[)]
742 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
743 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
745 { //---------------------------------------------------------------
755 func (S) M1(struct{ string }) {}
757 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I1 value in variable declaration: b[.]S does not implement I1 [(]wrong type for method M1[)]
758 .*have M1[(]struct{string /[*] package b [*]/ }[)]
759 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
761 { //---------------------------------------------------------------
765 M2(y struct{ f struct{ f string } })
771 func (S) M2(struct{ f struct{ f string } }) {}
773 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I2 value in variable declaration: b[.]S does not implement I2 [(]wrong type for method M2[)]
774 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
775 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
777 { //---------------------------------------------------------------
781 M3(z struct{ F struct{ f string } })
787 func (S) M3(struct{ F struct{ f string } }) {}
789 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I3 value in variable declaration: b[.]S does not implement I3 [(]wrong type for method M3[)]
790 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
791 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
793 { //---------------------------------------------------------------
797 M4(_ struct { *string })
803 func (S) M4(struct { *string }) {}
805 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I4 value in variable declaration: b[.]S does not implement I4 [(]wrong type for method M4[)]
806 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
807 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
809 { //---------------------------------------------------------------
812 type t struct{ A int }
820 type t struct{ A int }
821 func (S) M5(struct {S;t}) {}
823 `7:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I5 value in variable declaration: b[.]S does not implement I5 [(]wrong type for method M5[)]
824 .*have M5[(]struct{b[.]S; b[.]t}[)]
825 .*want M5[(]struct{b[.]S; t}[)]`},
828 fset := token.NewFileSet()
829 test := func(main, b, want string) {
830 re := regexp.MustCompile(want)
831 bpkg := mustTypecheck(b, nil, nil)
832 mast := mustParse(fset, main)
833 conf := Config{Importer: importHelper{pkg: bpkg}}
834 _, err := conf.Check(mast.Name.Name, fset, []*ast.File{mast}, nil)
836 t.Error("Expected failure, but it did not")
837 } else if got := err.Error(); !re.MatchString(got) {
838 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
839 } else if testing.Verbose() {
840 t.Logf("Saw expected\n\t%s", err.Error())
843 for _, t := range tests {
844 test(t.main, t.b, t.want)
848 func TestIssue59944(t *testing.T) {
849 testenv.MustHaveCGO(t)
851 // The typechecker should resolve methods declared on aliases of cgo types.
862 type Layout = C.struct_layout
864 func (l *Layout) Binding() {}
867 _ = (*Layout).Binding
871 // code generated by cmd/cgo for the above source.
873 // Code generated by cmd/cgo; DO NOT EDIT.
881 import _cgopackage "runtime/cgo"
883 type _ _cgopackage.Incomplete
885 func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
887 //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
888 var _Cgo_always_false bool
889 //go:linkname _Cgo_use runtime.cgoUse
890 func _Cgo_use(interface{})
891 type _Ctype_int int32
893 type _Ctype_struct_layout struct {
897 type _Ctype_void [0]byte
899 //go:linkname _cgo_runtime_cgocall runtime.cgocall
900 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
902 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
903 func _cgoCheckPointer(interface{}, interface{})
905 //go:linkname _cgoCheckResult runtime.cgoCheckResult
906 func _cgoCheckResult(interface{})
908 testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, false, func(cfg *Config) {
909 *boolFieldAddr(cfg, "go115UsesCgo") = true
913 func TestIssue61931(t *testing.T) {
917 func A(func(any), ...any) {}
921 A(B, nil // syntax error: missing ',' before newline in argument list
924 fset := token.NewFileSet()
925 f, err := parser.ParseFile(fset, pkgName(src), src, 0)
927 t.Fatal("expected syntax error")
931 conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // must not panic
934 func TestIssue61938(t *testing.T) {
941 // no error handler provided (this issue)
943 typecheck(src, &conf, nil) // must not panic
945 // with error handler (sanity check)
946 conf.Error = func(error) {}
947 typecheck(src, &conf, nil) // must not panic
950 func TestIssue63260(t *testing.T) {
960 func f[I *T, T any]() {
966 Defs: make(map[*ast.Ident]Object),
968 pkg := mustTypecheck(src, nil, &info)
970 // get type parameter T in signature of f
971 T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
972 if T.Obj().Name() != "T" {
973 t.Fatalf("got type parameter %s, want T", T)
976 // get type of variable v in body of f
978 for name, obj := range info.Defs {
979 if name.Name == "v" {
985 t.Fatal("variable v not found")
988 // type of v and T must be pointer-identical
990 t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)