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("p", `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("p", 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("p", 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
105 f := mustParse("", src)
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("p", 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("main", 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 :1:27: a declared and not used
262 :1:30: b declared and not used
263 :1:33: c declared and not used
264 :1:36: d declared and not used
265 :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("a", asrc, nil, nil)
446 conf := Config{Importer: importHelper{pkg: a}}
447 mustTypecheck("b", 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 f := mustParse("", src)
486 conf := Config{Importer: importHelper{pkg: pkg}}
487 res, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
489 t.Errorf("%q failed to typecheck: %v", src, err)
491 pkg = res // res is imported by the next package in this test
495 func TestIssue43088(t *testing.T) {
505 n1 := NewTypeName(syntax.Pos{}, nil, "T1", nil)
506 T1 := NewNamed(n1, nil, nil)
507 n2 := NewTypeName(syntax.Pos{}, nil, "T2", nil)
508 T2 := NewNamed(n2, nil, nil)
509 s1 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", T2, false)}, nil)
511 s2 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", T2, false)}, nil)
512 s3 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", s2, false)}, nil)
515 // These calls must terminate (no endless recursion).
520 func TestIssue44515(t *testing.T) {
521 typ := Unsafe.Scope().Lookup("Pointer").Type()
523 got := TypeString(typ, nil)
524 want := "unsafe.Pointer"
526 t.Errorf("got %q; want %q", got, want)
529 qf := func(pkg *Package) string {
535 got = TypeString(typ, qf)
538 t.Errorf("got %q; want %q", got, want)
542 func TestIssue43124(t *testing.T) {
543 testenv.MustHaveGoBuild(t)
545 // All involved packages have the same name (template). Error messages should
546 // disambiguate between text/template and html/template by printing the full
549 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
550 bsrc = `package b; import ("a"; "html/template"); func _() { a.F(template.Template{}) }`
551 csrc = `package c; import ("a"; "html/template"); func _() { a.G(template.Template{}) }`
554 a := mustTypecheck("a", asrc, nil, nil)
555 conf := Config{Importer: importHelper{pkg: a, fallback: defaultImporter()}}
557 // Packages should be fully qualified when there is ambiguity within the
558 // error string itself.
559 _, err := typecheck("b", bsrc, &conf, nil)
561 t.Fatal("package b had no errors")
563 if !strings.Contains(err.Error(), "text/template") || !strings.Contains(err.Error(), "html/template") {
564 t.Errorf("type checking error for b does not disambiguate package template: %q", err)
567 // ...and also when there is any ambiguity in reachable packages.
568 _, err = typecheck("c", csrc, &conf, nil)
570 t.Fatal("package c had no errors")
572 if !strings.Contains(err.Error(), "html/template") {
573 t.Errorf("type checking error for c does not disambiguate package template: %q", err)
577 func TestIssue50646(t *testing.T) {
578 anyType := Universe.Lookup("any").Type()
579 comparableType := Universe.Lookup("comparable").Type()
581 if !Comparable(anyType) {
582 t.Error("any is not a comparable type")
584 if !Comparable(comparableType) {
585 t.Error("comparable is not a comparable type")
588 if Implements(anyType, comparableType.Underlying().(*Interface)) {
589 t.Error("any implements comparable")
591 if !Implements(comparableType, anyType.(*Interface)) {
592 t.Error("comparable does not implement any")
595 if AssignableTo(anyType, comparableType) {
596 t.Error("any assignable to comparable")
598 if !AssignableTo(comparableType, anyType) {
599 t.Error("comparable not assignable to any")
603 func TestIssue55030(t *testing.T) {
604 // makeSig makes the signature func(typ...)
605 makeSig := func(typ Type) {
606 par := NewVar(nopos, nil, "", typ)
607 params := NewTuple(par)
608 NewSignatureType(nil, nil, nil, params, nil, true)
611 // makeSig must not panic for the following (example) types:
613 makeSig(NewSlice(Typ[Int]))
618 // P where P's core type is string
620 P := NewTypeName(nopos, nil, "P", nil) // [P string]
621 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
624 // P where P's core type is an (unnamed) slice
626 P := NewTypeName(nopos, nil, "P", nil) // [P []int]
627 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
630 // P where P's core type is bytestring (i.e., string or []byte)
632 t1 := NewTerm(true, Typ[String]) // ~string
633 t2 := NewTerm(false, NewSlice(Typ[Byte])) // []byte
634 u := NewUnion([]*Term{t1, t2}) // ~string | []byte
635 P := NewTypeName(nopos, nil, "P", nil) // [P ~string | []byte]
636 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
640 func TestIssue51093(t *testing.T) {
641 // Each test stands for a conversion of the form P(val)
642 // where P is a type parameter with typ as constraint.
643 // The test ensures that P(val) has the correct type P
644 // and is not a constant.
645 var tests = []struct {
654 {"complex64", "1.25"},
655 {"string", "\"foo\""},
657 // some more complex constraints
659 {"~int | ~float64 | complex128", "1"},
660 {"~uint64 | ~rune", "'X'"},
663 for _, test := range tests {
664 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
665 types := make(map[syntax.Expr]TypeAndValue)
666 mustTypecheck("p", src, nil, &Info{Types: types})
669 for x, tv := range types {
670 if x, _ := x.(*syntax.CallExpr); x != nil {
671 // there must be exactly one CallExpr which is the P(val) conversion
673 tpar, _ := tv.Type.(*TypeParam)
675 t.Fatalf("%s: got type %s, want type parameter", syntax.String(x), tv.Type)
677 if name := tpar.Obj().Name(); name != "P" {
678 t.Fatalf("%s: got type parameter name %s, want P", syntax.String(x), name)
680 // P(val) must not be constant
682 t.Errorf("%s: got constant value %s (%s), want no constant", syntax.String(x), tv.Value, tv.Value.String())
688 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
693 func TestIssue54258(t *testing.T) {
694 tests := []struct{ main, b, want string }{
695 { //---------------------------------------------------------------
699 M0(w struct{ f string })
705 func (S) M0(struct{ f string }) {}
707 `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[)]
708 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
709 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
711 { //---------------------------------------------------------------
721 func (S) M1(struct{ string }) {}
723 `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[)]
724 .*have M1[(]struct{string /[*] package b [*]/ }[)]
725 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
727 { //---------------------------------------------------------------
731 M2(y struct{ f struct{ f string } })
737 func (S) M2(struct{ f struct{ f string } }) {}
739 `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[)]
740 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
741 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
743 { //---------------------------------------------------------------
747 M3(z struct{ F struct{ f string } })
753 func (S) M3(struct{ F struct{ f string } }) {}
755 `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[)]
756 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
757 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
759 { //---------------------------------------------------------------
763 M4(_ struct { *string })
769 func (S) M4(struct { *string }) {}
771 `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[)]
772 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
773 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
775 { //---------------------------------------------------------------
778 type t struct{ A int }
786 type t struct{ A int }
787 func (S) M5(struct {S;t}) {}
789 `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[)]
790 .*have M5[(]struct{b[.]S; b[.]t}[)]
791 .*want M5[(]struct{b[.]S; t}[)]`},
794 test := func(main, b, want string) {
795 re := regexp.MustCompile(want)
796 bpkg := mustTypecheck("b", b, nil, nil)
797 mast := mustParse("main.go", main)
798 conf := Config{Importer: importHelper{pkg: bpkg}}
799 _, err := conf.Check(mast.PkgName.Value, []*syntax.File{mast}, nil)
801 t.Error("Expected failure, but it did not")
802 } else if got := err.Error(); !re.MatchString(got) {
803 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
804 } else if testing.Verbose() {
805 t.Logf("Saw expected\n\t%s", err.Error())
808 for _, t := range tests {
809 test(t.main, t.b, t.want)