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 f := mustParse(fset, "", `package p; type S struct{T}`)
25 conf := Config{Importer: importer.Default()}
26 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // do not crash
27 const want = "undefined: T"
28 if err == nil || !strings.Contains(err.Error(), want) {
29 t.Errorf("got: %v; want: %s", err, want)
33 func TestIssue5849(t *testing.T) {
41 _ = uint64(64 << s + s)
42 _ = (interface{})("foo")
43 _ = (interface{})(nil)
45 types := make(map[ast.Expr]TypeAndValue)
46 mustTypecheck("p", src, &Info{Types: types})
48 for x, tv := range types {
50 switch x := x.(type) {
60 want = Typ[Uint] // because of "+ s", s is of type uint
66 want = Typ[UntypedNil]
69 if want != nil && !Identical(tv.Type, want) {
70 t.Errorf("got %s; want %s", tv.Type, want)
75 func TestIssue6413(t *testing.T) {
84 types := make(map[ast.Expr]TypeAndValue)
85 mustTypecheck("p", src, &Info{Types: types})
89 for x, tv := range types {
90 if _, ok := x.(*ast.CallExpr); ok {
92 t.Errorf("%s: got %s; want %s", fset.Position(x.Pos()), tv.Type, want)
99 t.Errorf("got %d CallExprs; want 2", n)
103 func TestIssue7245(t *testing.T) {
106 func (T) m() (res bool) { return }
107 type T struct{} // receiver type after method declaration
109 f := mustParse(fset, "", src)
112 defs := make(map[*ast.Ident]Object)
113 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs})
118 m := f.Decls[0].(*ast.FuncDecl)
119 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
120 res2 := defs[m.Type.Results.List[0].Names[0]].(*Var)
123 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
127 // This tests that uses of existing vars on the LHS of an assignment
128 // are Uses, not Defs; and also that the (illegal) use of a non-var on
129 // the LHS of an assignment is a Use nonetheless.
130 func TestIssue7827(t *testing.T) {
134 const w = 1 // defs w
135 x, y := 2, 3 // defs x, y
136 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
137 _, _, _ = x, y, z // uses x, y, z
140 f := mustParse(fset, "", src)
142 const want = `L3 defs func p._()
143 L4 defs const w untyped int
147 L6 uses const w untyped int
153 // don't abort at the first error
154 conf := Config{Error: func(err error) { t.Log(err) }}
155 defs := make(map[*ast.Ident]Object)
156 uses := make(map[*ast.Ident]Object)
157 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs, Uses: uses})
158 if s := fmt.Sprint(err); !strings.HasSuffix(s, "cannot assign to w") {
159 t.Errorf("Check: unexpected error: %s", s)
163 for id, obj := range defs {
165 fact := fmt.Sprintf("L%d defs %s", fset.Position(id.Pos()).Line, obj)
166 facts = append(facts, fact)
169 for id, obj := range uses {
170 fact := fmt.Sprintf("L%d uses %s", fset.Position(id.Pos()).Line, obj)
171 facts = append(facts, fact)
175 got := strings.Join(facts, "\n")
177 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
181 // This tests that the package associated with the types.Object.Pkg method
182 // is the type's package independent of the order in which the imports are
183 // listed in the sources src1, src2 below.
184 // The actual issue is in go/internal/gcimporter which has a corresponding
185 // test; we leave this test here to verify correct behavior at the go/types
187 func TestIssue13898(t *testing.T) {
188 testenv.MustHaveGoBuild(t)
197 for _, obj := range info.Uses {
202 // like src0, but also imports go/importer
213 for _, obj := range info.Uses {
218 // like src1 but with different import order
219 // (used to fail with this issue)
230 for _, obj := range info.Uses {
235 f := func(test, src string) {
236 f := mustParse(fset, "", src)
237 cfg := Config{Importer: importer.Default()}
238 info := Info{Uses: make(map[*ast.Ident]Object)}
239 _, err := cfg.Check("main", fset, []*ast.File{f}, &info)
246 for id, obj := range info.Uses {
247 if id.Name == "Pkg" {
253 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
255 if pkg.Name() != "types" {
256 t.Fatalf("%s: got %v; want package types", test, pkg)
265 func TestIssue22525(t *testing.T) {
266 f := mustParse(fset, "", `package p; func f() { var a, b, c, d, e int }`)
269 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
270 conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // do not crash
272 1:27: a declared and not used
273 1:30: b declared and not used
274 1:33: c declared and not used
275 1:36: d declared and not used
276 1:39: e declared and not used
279 t.Errorf("got: %swant: %s", got, want)
283 func TestIssue25627(t *testing.T) {
284 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
285 // The src strings (without prefix) are constructed such that the number of semicolons
286 // plus one corresponds to the number of fields expected in the respective struct.
287 for _, src := range []string{
288 `struct { x Missing }`,
289 `struct { Missing }`,
290 `struct { *Missing }`,
291 `struct { unsafe.Pointer }`,
294 `struct { a int; b Missing; *Missing }`,
296 f := mustParse(fset, "", prefix+src)
298 cfg := Config{Importer: importer.Default(), Error: func(err error) {}}
299 info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
300 _, err := cfg.Check(f.Name.Name, fset, []*ast.File{f}, info)
302 if _, ok := err.(Error); !ok {
307 ast.Inspect(f, func(n ast.Node) bool {
308 if spec, _ := n.(*ast.TypeSpec); spec != nil {
309 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Name == "T" {
310 want := strings.Count(src, ";") + 1
311 if got := tv.Type.(*Struct).NumFields(); got != want {
312 t.Errorf("%s: got %d fields; want %d", src, got, want)
321 func TestIssue28005(t *testing.T) {
322 // method names must match defining interface name for this test
323 // (see last comment in this function)
324 sources := [...]string{
325 "package p; type A interface{ A() }",
326 "package p; type B interface{ B() }",
327 "package p; type X interface{ A; B }",
330 // compute original file ASTs
331 var orig [len(sources)]*ast.File
332 for i, src := range sources {
333 orig[i] = mustParse(fset, "", src)
336 // run the test for all order permutations of the incoming files
337 for _, perm := range [][len(sources)]int{
345 // create file order permutation
346 files := make([]*ast.File, len(sources))
347 for i := range perm {
348 files[i] = orig[perm[i]]
351 // type-check package with given file order permutation
353 info := &Info{Defs: make(map[*ast.Ident]Object)}
354 _, err := conf.Check("", fset, files, info)
359 // look for interface object X
361 for name, def := range info.Defs {
362 if name.Name == "X" {
368 t.Fatal("object X not found")
370 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
372 // Each iface method m is embedded; and m's receiver base type name
373 // must match the method's name per the choice in the source file.
374 for i := 0; i < iface.NumMethods(); i++ {
376 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
377 if recvName != m.Name() {
378 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
384 func TestIssue28282(t *testing.T) {
385 // create type interface { error }
386 et := Universe.Lookup("error").Type()
387 it := NewInterfaceType(nil, []Type{et})
389 // verify that after completing the interface, the embedded method remains unchanged
390 want := et.Underlying().(*Interface).Method(0)
393 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
395 // verify that lookup finds the same method in both interfaces (redundant check)
396 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
398 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
400 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
402 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
406 func TestIssue29029(t *testing.T) {
407 f1 := mustParse(fset, "", `package p; type A interface { M() }`)
408 f2 := mustParse(fset, "", `package p; var B interface { A }`)
410 // printInfo prints the *Func definitions recorded in info, one *Func per line.
411 printInfo := func(info *Info) string {
412 var buf strings.Builder
413 for _, obj := range info.Defs {
414 if fn, ok := obj.(*Func); ok {
415 fmt.Fprintln(&buf, fn)
421 // The *Func (method) definitions for package p must be the same
422 // independent on whether f1 and f2 are type-checked together, or
425 // type-check together
427 info := &Info{Defs: make(map[*ast.Ident]Object)}
428 check := NewChecker(&conf, fset, NewPackage("", "p"), info)
429 if err := check.Files([]*ast.File{f1, f2}); err != nil {
432 want := printInfo(info)
434 // type-check incrementally
435 info = &Info{Defs: make(map[*ast.Ident]Object)}
436 check = NewChecker(&conf, fset, NewPackage("", "p"), info)
437 if err := check.Files([]*ast.File{f1}); err != nil {
440 if err := check.Files([]*ast.File{f2}); err != nil {
443 got := printInfo(info)
446 t.Errorf("\ngot : %swant: %s", got, want)
450 func TestIssue34151(t *testing.T) {
451 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
452 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
454 a := mustTypecheck("a", asrc, nil)
456 bast := mustParse(fset, "", bsrc)
457 conf := Config{Importer: importHelper{pkg: a}}
458 b, err := conf.Check(bast.Name.Name, fset, []*ast.File{bast}, nil)
460 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
464 type importHelper struct {
469 func (h importHelper) Import(path string) (*Package, error) {
470 if path == h.pkg.Path() {
473 if h.fallback == nil {
474 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
476 return h.fallback.Import(path)
479 // TestIssue34921 verifies that we don't update an imported type's underlying
480 // type when resolving an underlying type. Specifically, when determining the
481 // underlying type of b.T (which is the underlying type of a.T, which is int)
482 // we must not set the underlying type of a.T again since that would lead to
483 // a race condition if package b is imported elsewhere, in a package that is
484 // concurrently type-checked.
485 func TestIssue34921(t *testing.T) {
487 if r := recover(); r != nil {
492 var sources = []string{
493 `package a; type T int`,
494 `package b; import "a"; type T a.T`,
498 for _, src := range sources {
499 f := mustParse(fset, "", src)
500 conf := Config{Importer: importHelper{pkg: pkg}}
501 res, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
503 t.Errorf("%q failed to typecheck: %v", src, err)
505 pkg = res // res is imported by the next package in this test
509 func TestIssue43088(t *testing.T) {
519 n1 := NewTypeName(token.NoPos, nil, "T1", nil)
520 T1 := NewNamed(n1, nil, nil)
521 n2 := NewTypeName(token.NoPos, nil, "T2", nil)
522 T2 := NewNamed(n2, nil, nil)
523 s1 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", T2, false)}, nil)
525 s2 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", T2, false)}, nil)
526 s3 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", s2, false)}, nil)
529 // These calls must terminate (no endless recursion).
534 func TestIssue44515(t *testing.T) {
535 typ := Unsafe.Scope().Lookup("Pointer").Type()
537 got := TypeString(typ, nil)
538 want := "unsafe.Pointer"
540 t.Errorf("got %q; want %q", got, want)
543 qf := func(pkg *Package) string {
549 got = TypeString(typ, qf)
552 t.Errorf("got %q; want %q", got, want)
556 func TestIssue43124(t *testing.T) {
557 // TODO(rFindley) move this to testdata by enhancing support for importing.
559 testenv.MustHaveGoBuild(t) // The go command is needed for the importer to determine the locations of stdlib .a files.
561 // All involved packages have the same name (template). Error messages should
562 // disambiguate between text/template and html/template by printing the full
565 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
575 // Packages should be fully qualified when there is ambiguity within the
576 // error string itself.
577 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
589 // Issue #46905: make sure template is not the first package qualified.
590 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
592 // Packages should be fully qualified when there is ambiguity in reachable
593 // packages. In this case both a (and for that matter html/template) import
595 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
601 import "text/template"
605 // Verify that the current package name also causes disambiguation.
606 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
610 a := mustTypecheck("a", asrc, nil)
611 imp := importHelper{pkg: a, fallback: importer.Default()}
613 testFiles(t, nil, []string{"b.go"}, [][]byte{[]byte(bsrc)}, false, imp)
614 testFiles(t, nil, []string{"c.go"}, [][]byte{[]byte(csrc)}, false, imp)
615 testFiles(t, nil, []string{"t.go"}, [][]byte{[]byte(tsrc)}, false, imp)
618 func TestIssue50646(t *testing.T) {
619 anyType := Universe.Lookup("any").Type()
620 comparableType := Universe.Lookup("comparable").Type()
622 if !Comparable(anyType) {
623 t.Error("any is not a comparable type")
625 if !Comparable(comparableType) {
626 t.Error("comparable is not a comparable type")
629 if Implements(anyType, comparableType.Underlying().(*Interface)) {
630 t.Error("any implements comparable")
632 if !Implements(comparableType, anyType.(*Interface)) {
633 t.Error("comparable does not implement any")
636 if AssignableTo(anyType, comparableType) {
637 t.Error("any assignable to comparable")
639 if !AssignableTo(comparableType, anyType) {
640 t.Error("comparable not assignable to any")
644 func TestIssue55030(t *testing.T) {
645 // makeSig makes the signature func(typ...)
646 makeSig := func(typ Type) {
647 par := NewVar(token.NoPos, nil, "", typ)
648 params := NewTuple(par)
649 NewSignatureType(nil, nil, nil, params, nil, true)
652 // makeSig must not panic for the following (example) types:
654 makeSig(NewSlice(Typ[Int]))
659 // P where P's core type is string
661 P := NewTypeName(token.NoPos, nil, "P", nil) // [P string]
662 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
665 // P where P's core type is an (unnamed) slice
667 P := NewTypeName(token.NoPos, nil, "P", nil) // [P []int]
668 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
671 // P where P's core type is bytestring (i.e., string or []byte)
673 t1 := NewTerm(true, Typ[String]) // ~string
674 t2 := NewTerm(false, NewSlice(Typ[Byte])) // []byte
675 u := NewUnion([]*Term{t1, t2}) // ~string | []byte
676 P := NewTypeName(token.NoPos, nil, "P", nil) // [P ~string | []byte]
677 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
681 func TestIssue51093(t *testing.T) {
682 // Each test stands for a conversion of the form P(val)
683 // where P is a type parameter with typ as constraint.
684 // The test ensures that P(val) has the correct type P
685 // and is not a constant.
686 var tests = []struct {
695 {"complex64", "1.25"},
696 {"string", "\"foo\""},
698 // some more complex constraints
700 {"~int | ~float64 | complex128", "1"},
701 {"~uint64 | ~rune", "'X'"},
704 for _, test := range tests {
705 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
706 types := make(map[ast.Expr]TypeAndValue)
707 mustTypecheck("p", src, &Info{Types: types})
710 for x, tv := range types {
711 if x, _ := x.(*ast.CallExpr); x != nil {
712 // there must be exactly one CallExpr which is the P(val) conversion
714 tpar, _ := tv.Type.(*TypeParam)
716 t.Fatalf("%s: got type %s, want type parameter", ExprString(x), tv.Type)
718 if name := tpar.Obj().Name(); name != "P" {
719 t.Fatalf("%s: got type parameter name %s, want P", ExprString(x), name)
721 // P(val) must not be constant
723 t.Errorf("%s: got constant value %s (%s), want no constant", ExprString(x), tv.Value, tv.Value.String())
729 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
734 func TestIssue54258(t *testing.T) {
736 tests := []struct{ main, b, want string }{
737 { //---------------------------------------------------------------
741 M0(w struct{ f string })
747 func (S) M0(struct{ f string }) {}
749 `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[)]
750 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
751 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
753 { //---------------------------------------------------------------
763 func (S) M1(struct{ string }) {}
765 `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[)]
766 .*have M1[(]struct{string /[*] package b [*]/ }[)]
767 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
769 { //---------------------------------------------------------------
773 M2(y struct{ f struct{ f string } })
779 func (S) M2(struct{ f struct{ f string } }) {}
781 `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[)]
782 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
783 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
785 { //---------------------------------------------------------------
789 M3(z struct{ F struct{ f string } })
795 func (S) M3(struct{ F struct{ f string } }) {}
797 `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[)]
798 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
799 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
801 { //---------------------------------------------------------------
805 M4(_ struct { *string })
811 func (S) M4(struct { *string }) {}
813 `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[)]
814 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
815 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
817 { //---------------------------------------------------------------
820 type t struct{ A int }
828 type t struct{ A int }
829 func (S) M5(struct {S;t}) {}
831 `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[)]
832 .*have M5[(]struct{b[.]S; b[.]t}[)]
833 .*want M5[(]struct{b[.]S; t}[)]`},
836 fset := token.NewFileSet()
837 test := func(main, b, want string) {
838 re := regexp.MustCompile(want)
839 bpkg := mustTypecheck("b", b, nil)
840 mast := mustParse(fset, "main.go", main)
841 conf := Config{Importer: importHelper{pkg: bpkg}}
842 _, err := conf.Check(mast.Name.Name, fset, []*ast.File{mast}, nil)
844 t.Error("Expected failure, but it did not")
845 } else if got := err.Error(); !re.MatchString(got) {
846 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
847 } else if testing.Verbose() {
848 t.Logf("Saw expected\n\t%s", err.Error())
851 for _, t := range tests {
852 test(t.main, t.b, t.want)