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.
23 func TestIssue5770(t *testing.T) {
24 _, err := typecheck("p", `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)
31 func TestIssue5849(t *testing.T) {
39 _ = uint64(64 << s + s)
40 _ = (interface{})("foo")
41 _ = (interface{})(nil)
43 types := make(map[ast.Expr]TypeAndValue)
44 mustTypecheck("p", src, nil, &Info{Types: types})
46 for x, tv := range types {
48 switch x := x.(type) {
58 want = Typ[Uint] // because of "+ s", s is of type uint
64 want = Typ[UntypedNil]
67 if want != nil && !Identical(tv.Type, want) {
68 t.Errorf("got %s; want %s", tv.Type, want)
73 func TestIssue6413(t *testing.T) {
82 types := make(map[ast.Expr]TypeAndValue)
83 mustTypecheck("p", src, nil, &Info{Types: types})
87 for x, tv := range types {
88 if _, ok := x.(*ast.CallExpr); ok {
90 t.Errorf("%s: got %s; want %s", fset.Position(x.Pos()), tv.Type, want)
97 t.Errorf("got %d CallExprs; want 2", n)
101 func TestIssue7245(t *testing.T) {
104 func (T) m() (res bool) { return }
105 type T struct{} // receiver type after method declaration
107 f := mustParse(fset, "", src)
110 defs := make(map[*ast.Ident]Object)
111 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs})
116 m := f.Decls[0].(*ast.FuncDecl)
117 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
118 res2 := defs[m.Type.Results.List[0].Names[0]].(*Var)
121 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
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) {
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
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)
143 const want = `L3 defs func p._()
144 L4 defs const w untyped int
148 L6 uses const w untyped int
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)
164 for id, obj := range defs {
166 fact := fmt.Sprintf("L%d defs %s", fset.Position(id.Pos()).Line, obj)
167 facts = append(facts, fact)
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)
176 got := strings.Join(facts, "\n")
178 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
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
188 func TestIssue13898(t *testing.T) {
189 testenv.MustHaveGoBuild(t)
198 for _, obj := range info.Uses {
203 // like src0, but also imports go/importer
214 for _, obj := range info.Uses {
219 // like src1 but with different import order
220 // (used to fail with this issue)
231 for _, obj := range info.Uses {
236 f := func(test, src string) {
237 info := &Info{Uses: make(map[*ast.Ident]Object)}
238 mustTypecheck("main", src, nil, info)
242 for id, obj := range info.Uses {
243 if id.Name == "Pkg" {
249 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
251 if pkg.Name() != "types" {
252 t.Fatalf("%s: got %v; want package types", test, pkg)
261 func TestIssue22525(t *testing.T) {
262 const src = `package p; func f() { var a, b, c, d, e int }`
265 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
266 typecheck("", src, &conf, nil) // do not crash
268 1:27: a declared and not used
269 1:30: b declared and not used
270 1:33: c declared and not used
271 1:36: d declared and not used
272 1:39: e declared and not used
275 t.Errorf("got: %swant: %s", got, want)
279 func TestIssue25627(t *testing.T) {
280 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
281 // The src strings (without prefix) are constructed such that the number of semicolons
282 // plus one corresponds to the number of fields expected in the respective struct.
283 for _, src := range []string{
284 `struct { x Missing }`,
285 `struct { Missing }`,
286 `struct { *Missing }`,
287 `struct { unsafe.Pointer }`,
290 `struct { a int; b Missing; *Missing }`,
292 f := mustParse(fset, "", prefix+src)
294 cfg := Config{Importer: importer.Default(), Error: func(err error) {}}
295 info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
296 _, err := cfg.Check(f.Name.Name, fset, []*ast.File{f}, info)
298 if _, ok := err.(Error); !ok {
303 ast.Inspect(f, func(n ast.Node) bool {
304 if spec, _ := n.(*ast.TypeSpec); spec != nil {
305 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Name == "T" {
306 want := strings.Count(src, ";") + 1
307 if got := tv.Type.(*Struct).NumFields(); got != want {
308 t.Errorf("%s: got %d fields; want %d", src, got, want)
317 func TestIssue28005(t *testing.T) {
318 // method names must match defining interface name for this test
319 // (see last comment in this function)
320 sources := [...]string{
321 "package p; type A interface{ A() }",
322 "package p; type B interface{ B() }",
323 "package p; type X interface{ A; B }",
326 // compute original file ASTs
327 var orig [len(sources)]*ast.File
328 for i, src := range sources {
329 orig[i] = mustParse(fset, "", src)
332 // run the test for all order permutations of the incoming files
333 for _, perm := range [][len(sources)]int{
341 // create file order permutation
342 files := make([]*ast.File, len(sources))
343 for i := range perm {
344 files[i] = orig[perm[i]]
347 // type-check package with given file order permutation
349 info := &Info{Defs: make(map[*ast.Ident]Object)}
350 _, err := conf.Check("", fset, files, info)
355 // look for interface object X
357 for name, def := range info.Defs {
358 if name.Name == "X" {
364 t.Fatal("object X not found")
366 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
368 // Each iface method m is embedded; and m's receiver base type name
369 // must match the method's name per the choice in the source file.
370 for i := 0; i < iface.NumMethods(); i++ {
372 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
373 if recvName != m.Name() {
374 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
380 func TestIssue28282(t *testing.T) {
381 // create type interface { error }
382 et := Universe.Lookup("error").Type()
383 it := NewInterfaceType(nil, []Type{et})
385 // verify that after completing the interface, the embedded method remains unchanged
386 want := et.Underlying().(*Interface).Method(0)
389 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
391 // verify that lookup finds the same method in both interfaces (redundant check)
392 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
394 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
396 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
398 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
402 func TestIssue29029(t *testing.T) {
403 f1 := mustParse(fset, "", `package p; type A interface { M() }`)
404 f2 := mustParse(fset, "", `package p; var B interface { A }`)
406 // printInfo prints the *Func definitions recorded in info, one *Func per line.
407 printInfo := func(info *Info) string {
408 var buf strings.Builder
409 for _, obj := range info.Defs {
410 if fn, ok := obj.(*Func); ok {
411 fmt.Fprintln(&buf, fn)
417 // The *Func (method) definitions for package p must be the same
418 // independent on whether f1 and f2 are type-checked together, or
421 // type-check together
423 info := &Info{Defs: make(map[*ast.Ident]Object)}
424 check := NewChecker(&conf, fset, NewPackage("", "p"), info)
425 if err := check.Files([]*ast.File{f1, f2}); err != nil {
428 want := printInfo(info)
430 // type-check incrementally
431 info = &Info{Defs: make(map[*ast.Ident]Object)}
432 check = NewChecker(&conf, fset, NewPackage("", "p"), info)
433 if err := check.Files([]*ast.File{f1}); err != nil {
436 if err := check.Files([]*ast.File{f2}); err != nil {
439 got := printInfo(info)
442 t.Errorf("\ngot : %swant: %s", got, want)
446 func TestIssue34151(t *testing.T) {
447 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
448 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
450 a := mustTypecheck("a", asrc, nil, nil)
452 conf := Config{Importer: importHelper{pkg: a}}
453 mustTypecheck("b", bsrc, &conf, nil)
456 type importHelper struct {
461 func (h importHelper) Import(path string) (*Package, error) {
462 if path == h.pkg.Path() {
465 if h.fallback == nil {
466 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
468 return h.fallback.Import(path)
471 // TestIssue34921 verifies that we don't update an imported type's underlying
472 // type when resolving an underlying type. Specifically, when determining the
473 // underlying type of b.T (which is the underlying type of a.T, which is int)
474 // we must not set the underlying type of a.T again since that would lead to
475 // a race condition if package b is imported elsewhere, in a package that is
476 // concurrently type-checked.
477 func TestIssue34921(t *testing.T) {
479 if r := recover(); r != nil {
484 var sources = []string{
485 `package a; type T int`,
486 `package b; import "a"; type T a.T`,
490 for _, src := range sources {
491 f := mustParse(fset, "", src)
492 conf := Config{Importer: importHelper{pkg: pkg}}
493 res, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
495 t.Errorf("%q failed to typecheck: %v", src, err)
497 pkg = res // res is imported by the next package in this test
501 func TestIssue43088(t *testing.T) {
511 n1 := NewTypeName(nopos, nil, "T1", nil)
512 T1 := NewNamed(n1, nil, nil)
513 n2 := NewTypeName(nopos, nil, "T2", nil)
514 T2 := NewNamed(n2, nil, nil)
515 s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
517 s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
518 s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
521 // These calls must terminate (no endless recursion).
526 func TestIssue44515(t *testing.T) {
527 typ := Unsafe.Scope().Lookup("Pointer").Type()
529 got := TypeString(typ, nil)
530 want := "unsafe.Pointer"
532 t.Errorf("got %q; want %q", got, want)
535 qf := func(pkg *Package) string {
541 got = TypeString(typ, qf)
544 t.Errorf("got %q; want %q", got, want)
548 func TestIssue43124(t *testing.T) {
549 // TODO(rFindley) move this to testdata by enhancing support for importing.
551 testenv.MustHaveGoBuild(t) // The go command is needed for the importer to determine the locations of stdlib .a files.
553 // All involved packages have the same name (template). Error messages should
554 // disambiguate between text/template and html/template by printing the full
557 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
567 // Packages should be fully qualified when there is ambiguity within the
568 // error string itself.
569 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
581 // Issue #46905: make sure template is not the first package qualified.
582 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
584 // Packages should be fully qualified when there is ambiguity in reachable
585 // packages. In this case both a (and for that matter html/template) import
587 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
593 import "text/template"
597 // Verify that the current package name also causes disambiguation.
598 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
602 a := mustTypecheck("a", asrc, nil, nil)
603 imp := importHelper{pkg: a, fallback: importer.Default()}
605 testFiles(t, nil, []string{"b.go"}, [][]byte{[]byte(bsrc)}, false, imp)
606 testFiles(t, nil, []string{"c.go"}, [][]byte{[]byte(csrc)}, false, imp)
607 testFiles(t, nil, []string{"t.go"}, [][]byte{[]byte(tsrc)}, false, imp)
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("p", 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", b, nil, nil)
832 mast := mustParse(fset, "main.go", 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)