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.
10 "cmd/compile/internal/syntax"
18 . "cmd/compile/internal/types2"
21 func TestIssue5770(t *testing.T) {
22 _, err := typecheck(`package p; type S struct{T}`, nil, nil)
23 const want = "undefined: T"
24 if err == nil || !strings.Contains(err.Error(), want) {
25 t.Errorf("got: %v; want: %s", err, want)
29 func TestIssue5849(t *testing.T) {
37 _ = uint64(64 << s + s)
38 _ = (interface{})("foo")
39 _ = (interface{})(nil)
41 types := make(map[syntax.Expr]TypeAndValue)
42 mustTypecheck(src, nil, &Info{Types: types})
44 for x, tv := range types {
46 switch x := x.(type) {
47 case *syntax.BasicLit:
56 want = Typ[Uint] // because of "+ s", s is of type uint
62 want = NewInterfaceType(nil, nil) // interface{} (for now, go/types types this as "untyped nil")
65 if want != nil && !Identical(tv.Type, want) {
66 t.Errorf("got %s; want %s", tv.Type, want)
71 func TestIssue6413(t *testing.T) {
80 types := make(map[syntax.Expr]TypeAndValue)
81 mustTypecheck(src, nil, &Info{Types: types})
85 for x, tv := range types {
86 if _, ok := x.(*syntax.CallExpr); ok {
88 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
95 t.Errorf("got %d CallExprs; want 2", n)
99 func TestIssue7245(t *testing.T) {
102 func (T) m() (res bool) { return }
103 type T struct{} // receiver type after method declaration
108 defs := make(map[*syntax.Name]Object)
109 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
114 m := f.DeclList[0].(*syntax.FuncDecl)
115 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
116 res2 := defs[m.Type.ResultList[0].Name].(*Var)
119 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
123 // This tests that uses of existing vars on the LHS of an assignment
124 // are Uses, not Defs; and also that the (illegal) use of a non-var on
125 // the LHS of an assignment is a Use nonetheless.
126 func TestIssue7827(t *testing.T) {
130 const w = 1 // defs w
131 x, y := 2, 3 // defs x, y
132 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
133 _, _, _ = x, y, z // uses x, y, z
136 const want = `L3 defs func p._()
137 L4 defs const w untyped int
141 L6 uses const w untyped int
147 // don't abort at the first error
148 conf := Config{Error: func(err error) { t.Log(err) }}
149 defs := make(map[*syntax.Name]Object)
150 uses := make(map[*syntax.Name]Object)
151 _, err := typecheck(src, &conf, &Info{Defs: defs, Uses: uses})
152 if s := err.Error(); !strings.HasSuffix(s, "cannot assign to w") {
153 t.Errorf("Check: unexpected error: %s", s)
157 for id, obj := range defs {
159 fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
160 facts = append(facts, fact)
163 for id, obj := range uses {
164 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
165 facts = append(facts, fact)
169 got := strings.Join(facts, "\n")
171 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
175 // This tests that the package associated with the types2.Object.Pkg method
176 // is the type's package independent of the order in which the imports are
177 // listed in the sources src1, src2 below.
178 // The actual issue is in go/internal/gcimporter which has a corresponding
179 // test; we leave this test here to verify correct behavior at the go/types
181 func TestIssue13898(t *testing.T) {
182 testenv.MustHaveGoBuild(t)
191 for _, obj := range info.Uses {
196 // like src0, but also imports go/importer
207 for _, obj := range info.Uses {
212 // like src1 but with different import order
213 // (used to fail with this issue)
224 for _, obj := range info.Uses {
229 f := func(test, src string) {
230 info := &Info{Uses: make(map[*syntax.Name]Object)}
231 mustTypecheck(src, nil, info)
235 for id, obj := range info.Uses {
236 if id.Value == "Pkg" {
242 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
244 if pkg.Name() != "types" {
245 t.Fatalf("%s: got %v; want package types2", test, pkg)
254 func TestIssue22525(t *testing.T) {
255 const src = `package p; func f() { var a, b, c, d, e int }`
258 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
259 typecheck(src, &conf, nil) // do not crash
261 p:1:27: a declared and not used
262 p:1:30: b declared and not used
263 p:1:33: c declared and not used
264 p:1:36: d declared and not used
265 p:1:39: e declared and not used
268 t.Errorf("got: %swant: %s", got, want)
272 func TestIssue25627(t *testing.T) {
273 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
274 // The src strings (without prefix) are constructed such that the number of semicolons
275 // plus one corresponds to the number of fields expected in the respective struct.
276 for _, src := range []string{
277 `struct { x Missing }`,
278 `struct { Missing }`,
279 `struct { *Missing }`,
280 `struct { unsafe.Pointer }`,
283 `struct { a int; b Missing; *Missing }`,
285 f := mustParse(prefix + src)
287 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
288 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
289 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
291 if _, ok := err.(Error); !ok {
296 syntax.Inspect(f, func(n syntax.Node) bool {
297 if decl, _ := n.(*syntax.TypeDecl); decl != nil {
298 if tv, ok := info.Types[decl.Type]; ok && decl.Name.Value == "T" {
299 want := strings.Count(src, ";") + 1
300 if got := tv.Type.(*Struct).NumFields(); got != want {
301 t.Errorf("%s: got %d fields; want %d", src, got, want)
310 func TestIssue28005(t *testing.T) {
311 // method names must match defining interface name for this test
312 // (see last comment in this function)
313 sources := [...]string{
314 "package p; type A interface{ A() }",
315 "package p; type B interface{ B() }",
316 "package p; type X interface{ A; B }",
319 // compute original file ASTs
320 var orig [len(sources)]*syntax.File
321 for i, src := range sources {
322 orig[i] = mustParse(src)
325 // run the test for all order permutations of the incoming files
326 for _, perm := range [][len(sources)]int{
334 // create file order permutation
335 files := make([]*syntax.File, len(sources))
336 for i := range perm {
337 files[i] = orig[perm[i]]
340 // type-check package with given file order permutation
342 info := &Info{Defs: make(map[*syntax.Name]Object)}
343 _, err := conf.Check("", files, info)
348 // look for interface object X
350 for name, def := range info.Defs {
351 if name.Value == "X" {
357 t.Fatal("object X not found")
359 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
361 // Each iface method m is embedded; and m's receiver base type name
362 // must match the method's name per the choice in the source file.
363 for i := 0; i < iface.NumMethods(); i++ {
365 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
366 if recvName != m.Name() {
367 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
373 func TestIssue28282(t *testing.T) {
374 // create type interface { error }
375 et := Universe.Lookup("error").Type()
376 it := NewInterfaceType(nil, []Type{et})
377 // verify that after completing the interface, the embedded method remains unchanged
378 // (interfaces are "completed" lazily now, so the completion happens implicitly when
379 // accessing Method(0))
380 want := et.Underlying().(*Interface).Method(0)
383 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
385 // verify that lookup finds the same method in both interfaces (redundant check)
386 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
388 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
390 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
392 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
396 func TestIssue29029(t *testing.T) {
397 f1 := mustParse(`package p; type A interface { M() }`)
398 f2 := mustParse(`package p; var B interface { A }`)
400 // printInfo prints the *Func definitions recorded in info, one *Func per line.
401 printInfo := func(info *Info) string {
402 var buf strings.Builder
403 for _, obj := range info.Defs {
404 if fn, ok := obj.(*Func); ok {
405 fmt.Fprintln(&buf, fn)
411 // The *Func (method) definitions for package p must be the same
412 // independent on whether f1 and f2 are type-checked together, or
415 // type-check together
417 info := &Info{Defs: make(map[*syntax.Name]Object)}
418 check := NewChecker(&conf, NewPackage("", "p"), info)
419 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
422 want := printInfo(info)
424 // type-check incrementally
425 info = &Info{Defs: make(map[*syntax.Name]Object)}
426 check = NewChecker(&conf, NewPackage("", "p"), info)
427 if err := check.Files([]*syntax.File{f1}); err != nil {
430 if err := check.Files([]*syntax.File{f2}); err != nil {
433 got := printInfo(info)
436 t.Errorf("\ngot : %swant: %s", got, want)
440 func TestIssue34151(t *testing.T) {
441 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
442 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
444 a := mustTypecheck(asrc, nil, nil)
446 conf := Config{Importer: importHelper{pkg: a}}
447 mustTypecheck(bsrc, &conf, nil)
450 type importHelper struct {
455 func (h importHelper) Import(path string) (*Package, error) {
456 if path == h.pkg.Path() {
459 if h.fallback == nil {
460 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
462 return h.fallback.Import(path)
465 // TestIssue34921 verifies that we don't update an imported type's underlying
466 // type when resolving an underlying type. Specifically, when determining the
467 // underlying type of b.T (which is the underlying type of a.T, which is int)
468 // we must not set the underlying type of a.T again since that would lead to
469 // a race condition if package b is imported elsewhere, in a package that is
470 // concurrently type-checked.
471 func TestIssue34921(t *testing.T) {
473 if r := recover(); r != nil {
478 var sources = []string{
479 `package a; type T int`,
480 `package b; import "a"; type T a.T`,
484 for _, src := range sources {
485 conf := Config{Importer: importHelper{pkg: pkg}}
486 pkg = mustTypecheck(src, &conf, nil) // pkg imported by the next package in this test
490 func TestIssue43088(t *testing.T) {
500 n1 := NewTypeName(nopos, nil, "T1", nil)
501 T1 := NewNamed(n1, nil, nil)
502 n2 := NewTypeName(nopos, nil, "T2", nil)
503 T2 := NewNamed(n2, nil, nil)
504 s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
506 s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
507 s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
510 // These calls must terminate (no endless recursion).
515 func TestIssue44515(t *testing.T) {
516 typ := Unsafe.Scope().Lookup("Pointer").Type()
518 got := TypeString(typ, nil)
519 want := "unsafe.Pointer"
521 t.Errorf("got %q; want %q", got, want)
524 qf := func(pkg *Package) string {
530 got = TypeString(typ, qf)
533 t.Errorf("got %q; want %q", got, want)
537 func TestIssue43124(t *testing.T) {
538 // TODO(rFindley) move this to testdata by enhancing support for importing.
540 testenv.MustHaveGoBuild(t) // The go command is needed for the importer to determine the locations of stdlib .a files.
542 // All involved packages have the same name (template). Error messages should
543 // disambiguate between text/template and html/template by printing the full
546 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
556 // Packages should be fully qualified when there is ambiguity within the
557 // error string itself.
558 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
570 // go.dev/issue/46905: make sure template is not the first package qualified.
571 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
573 // Packages should be fully qualified when there is ambiguity in reachable
574 // packages. In this case both a (and for that matter html/template) import
576 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
582 import "text/template"
586 // Verify that the current package name also causes disambiguation.
587 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
591 a := mustTypecheck(asrc, nil, nil)
592 imp := importHelper{pkg: a, fallback: defaultImporter()}
594 withImporter := func(cfg *Config) {
598 testFiles(t, []string{"b.go"}, [][]byte{[]byte(bsrc)}, 0, false, withImporter)
599 testFiles(t, []string{"c.go"}, [][]byte{[]byte(csrc)}, 0, false, withImporter)
600 testFiles(t, []string{"t.go"}, [][]byte{[]byte(tsrc)}, 0, false, withImporter)
603 func TestIssue50646(t *testing.T) {
604 anyType := Universe.Lookup("any").Type()
605 comparableType := Universe.Lookup("comparable").Type()
607 if !Comparable(anyType) {
608 t.Error("any is not a comparable type")
610 if !Comparable(comparableType) {
611 t.Error("comparable is not a comparable type")
614 if Implements(anyType, comparableType.Underlying().(*Interface)) {
615 t.Error("any implements comparable")
617 if !Implements(comparableType, anyType.(*Interface)) {
618 t.Error("comparable does not implement any")
621 if AssignableTo(anyType, comparableType) {
622 t.Error("any assignable to comparable")
624 if !AssignableTo(comparableType, anyType) {
625 t.Error("comparable not assignable to any")
629 func TestIssue55030(t *testing.T) {
630 // makeSig makes the signature func(typ...)
631 makeSig := func(typ Type) {
632 par := NewVar(nopos, nil, "", typ)
633 params := NewTuple(par)
634 NewSignatureType(nil, nil, nil, params, nil, true)
637 // makeSig must not panic for the following (example) types:
639 makeSig(NewSlice(Typ[Int]))
644 // P where P's core type is string
646 P := NewTypeName(nopos, nil, "P", nil) // [P string]
647 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
650 // P where P's core type is an (unnamed) slice
652 P := NewTypeName(nopos, nil, "P", nil) // [P []int]
653 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
656 // P where P's core type is bytestring (i.e., string or []byte)
658 t1 := NewTerm(true, Typ[String]) // ~string
659 t2 := NewTerm(false, NewSlice(Typ[Byte])) // []byte
660 u := NewUnion([]*Term{t1, t2}) // ~string | []byte
661 P := NewTypeName(nopos, nil, "P", nil) // [P ~string | []byte]
662 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
666 func TestIssue51093(t *testing.T) {
667 // Each test stands for a conversion of the form P(val)
668 // where P is a type parameter with typ as constraint.
669 // The test ensures that P(val) has the correct type P
670 // and is not a constant.
671 var tests = []struct {
680 {"complex64", "1.25"},
681 {"string", "\"foo\""},
683 // some more complex constraints
685 {"~int | ~float64 | complex128", "1"},
686 {"~uint64 | ~rune", "'X'"},
689 for _, test := range tests {
690 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
691 types := make(map[syntax.Expr]TypeAndValue)
692 mustTypecheck(src, nil, &Info{Types: types})
695 for x, tv := range types {
696 if x, _ := x.(*syntax.CallExpr); x != nil {
697 // there must be exactly one CallExpr which is the P(val) conversion
699 tpar, _ := tv.Type.(*TypeParam)
701 t.Fatalf("%s: got type %s, want type parameter", syntax.String(x), tv.Type)
703 if name := tpar.Obj().Name(); name != "P" {
704 t.Fatalf("%s: got type parameter name %s, want P", syntax.String(x), name)
706 // P(val) must not be constant
708 t.Errorf("%s: got constant value %s (%s), want no constant", syntax.String(x), tv.Value, tv.Value.String())
714 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
719 func TestIssue54258(t *testing.T) {
720 tests := []struct{ main, b, want string }{
721 { //---------------------------------------------------------------
725 M0(w struct{ f string })
731 func (S) M0(struct{ f string }) {}
733 `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[)]
734 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
735 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
737 { //---------------------------------------------------------------
747 func (S) M1(struct{ string }) {}
749 `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[)]
750 .*have M1[(]struct{string /[*] package b [*]/ }[)]
751 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
753 { //---------------------------------------------------------------
757 M2(y struct{ f struct{ f string } })
763 func (S) M2(struct{ f struct{ f string } }) {}
765 `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[)]
766 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
767 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
769 { //---------------------------------------------------------------
773 M3(z struct{ F struct{ f string } })
779 func (S) M3(struct{ F struct{ f string } }) {}
781 `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[)]
782 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
783 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
785 { //---------------------------------------------------------------
789 M4(_ struct { *string })
795 func (S) M4(struct { *string }) {}
797 `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[)]
798 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
799 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
801 { //---------------------------------------------------------------
804 type t struct{ A int }
812 type t struct{ A int }
813 func (S) M5(struct {S;t}) {}
815 `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[)]
816 .*have M5[(]struct{b[.]S; b[.]t}[)]
817 .*want M5[(]struct{b[.]S; t}[)]`},
820 test := func(main, b, want string) {
821 re := regexp.MustCompile(want)
822 bpkg := mustTypecheck(b, nil, nil)
823 mast := mustParse(main)
824 conf := Config{Importer: importHelper{pkg: bpkg}}
825 _, err := conf.Check(mast.PkgName.Value, []*syntax.File{mast}, nil)
827 t.Error("Expected failure, but it did not")
828 } else if got := err.Error(); !re.MatchString(got) {
829 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
830 } else if testing.Verbose() {
831 t.Logf("Saw expected\n\t%s", err.Error())
834 for _, t := range tests {
835 test(t.main, t.b, t.want)
839 func TestIssue59944(t *testing.T) {
840 testenv.MustHaveCGO(t)
842 // The typechecker should resolve methods declared on aliases of cgo types.
853 type Layout = C.struct_layout
855 func (l *Layout) Binding() {}
858 _ = (*Layout).Binding
862 // code generated by cmd/cgo for the above source.
864 // Code generated by cmd/cgo; DO NOT EDIT.
872 import _cgopackage "runtime/cgo"
874 type _ _cgopackage.Incomplete
876 func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
878 //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
879 var _Cgo_always_false bool
880 //go:linkname _Cgo_use runtime.cgoUse
881 func _Cgo_use(interface{})
882 type _Ctype_int int32
884 type _Ctype_struct_layout struct {
888 type _Ctype_void [0]byte
890 //go:linkname _cgo_runtime_cgocall runtime.cgocall
891 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
893 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
894 func _cgoCheckPointer(interface{}, interface{})
896 //go:linkname _cgoCheckResult runtime.cgoCheckResult
897 func _cgoCheckResult(interface{})
899 testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, 0, false, func(cfg *Config) {
900 *boolFieldAddr(cfg, "go115UsesCgo") = true
904 func TestIssue61931(t *testing.T) {
908 func A(func(any), ...any) {}
912 A(B, nil // syntax error: missing ',' before newline in argument list
915 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), func(error) {}, nil, 0)
917 t.Fatal("expected syntax error")
921 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // must not panic
924 func TestIssue61938(t *testing.T) {
931 // no error handler provided (this issue)
933 typecheck(src, &conf, nil) // must not panic
935 // with error handler (sanity check)
936 conf.Error = func(error) {}
937 typecheck(src, &conf, nil) // must not panic
940 func TestIssue63260(t *testing.T) {
950 func f[I *T, T any]() {
956 Defs: make(map[*syntax.Name]Object),
958 pkg := mustTypecheck(src, nil, &info)
960 // get type parameter T in signature of f
961 T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
962 if T.Obj().Name() != "T" {
963 t.Fatalf("got type parameter %s, want T", T)
966 // get type of variable v in body of f
968 for name, obj := range info.Defs {
969 if name.Value == "v" {
975 t.Fatal("variable v not found")
978 // type of v and T must be pointer-identical
980 t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)