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.
11 "cmd/compile/internal/syntax"
18 . "cmd/compile/internal/types2"
21 func mustParse(t *testing.T, src string) *syntax.File {
22 f, err := parseSrc("", src)
28 func TestIssue5770(t *testing.T) {
29 f := mustParse(t, `package p; type S struct{T}`)
31 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
32 want := "undeclared name: T"
33 if err == nil || !strings.Contains(err.Error(), want) {
34 t.Errorf("got: %v; want: %s", err, want)
38 func TestIssue5849(t *testing.T) {
46 _ = uint64(64 << s + s)
47 _ = (interface{})("foo")
48 _ = (interface{})(nil)
50 f := mustParse(t, src)
53 types := make(map[syntax.Expr]TypeAndValue)
54 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
59 for x, tv := range types {
61 switch x := x.(type) {
62 case *syntax.BasicLit:
71 want = Typ[Uint] // because of "+ s", s is of type uint
77 want = NewInterfaceType(nil, nil) // interface{} (for now, go/types types this as "untyped nil")
80 if want != nil && !Identical(tv.Type, want) {
81 t.Errorf("got %s; want %s", tv.Type, want)
86 func TestIssue6413(t *testing.T) {
95 f := mustParse(t, src)
98 types := make(map[syntax.Expr]TypeAndValue)
99 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
106 for x, tv := range types {
107 if _, ok := x.(*syntax.CallExpr); ok {
109 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
116 t.Errorf("got %d CallExprs; want 2", n)
120 func TestIssue7245(t *testing.T) {
123 func (T) m() (res bool) { return }
124 type T struct{} // receiver type after method declaration
126 f := mustParse(t, src)
129 defs := make(map[*syntax.Name]Object)
130 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
135 m := f.DeclList[0].(*syntax.FuncDecl)
136 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
137 res2 := defs[m.Type.ResultList[0].Name].(*Var)
140 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
144 // This tests that uses of existing vars on the LHS of an assignment
145 // are Uses, not Defs; and also that the (illegal) use of a non-var on
146 // the LHS of an assignment is a Use nonetheless.
147 func TestIssue7827(t *testing.T) {
151 const w = 1 // defs w
152 x, y := 2, 3 // defs x, y
153 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
154 _, _, _ = x, y, z // uses x, y, z
157 f := mustParse(t, src)
159 const want = `L3 defs func p._()
160 L4 defs const w untyped int
164 L6 uses const w untyped int
170 // don't abort at the first error
171 conf := Config{Error: func(err error) { t.Log(err) }}
172 defs := make(map[*syntax.Name]Object)
173 uses := make(map[*syntax.Name]Object)
174 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs, Uses: uses})
175 if s := fmt.Sprint(err); !strings.HasSuffix(s, "cannot assign to w") {
176 t.Errorf("Check: unexpected error: %s", s)
180 for id, obj := range defs {
182 fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
183 facts = append(facts, fact)
186 for id, obj := range uses {
187 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
188 facts = append(facts, fact)
192 got := strings.Join(facts, "\n")
194 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
198 // This tests that the package associated with the types2.Object.Pkg method
199 // is the type's package independent of the order in which the imports are
200 // listed in the sources src1, src2 below.
201 // The actual issue is in go/internal/gcimporter which has a corresponding
202 // test; we leave this test here to verify correct behavior at the go/types
204 func TestIssue13898(t *testing.T) {
205 testenv.MustHaveGoBuild(t)
214 for _, obj := range info.Uses {
219 // like src0, but also imports go/importer
230 for _, obj := range info.Uses {
235 // like src1 but with different import order
236 // (used to fail with this issue)
247 for _, obj := range info.Uses {
252 f := func(test, src string) {
253 f := mustParse(t, src)
254 conf := Config{Importer: defaultImporter()}
255 info := Info{Uses: make(map[*syntax.Name]Object)}
256 _, err := conf.Check("main", []*syntax.File{f}, &info)
263 for id, obj := range info.Uses {
264 if id.Value == "Pkg" {
270 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
272 if pkg.Name() != "types" {
273 t.Fatalf("%s: got %v; want package types2", test, pkg)
282 func TestIssue22525(t *testing.T) {
283 f := mustParse(t, `package p; func f() { var a, b, c, d, e int }`)
286 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
287 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
289 :1:27: a declared but not used
290 :1:30: b declared but not used
291 :1:33: c declared but not used
292 :1:36: d declared but not used
293 :1:39: e declared but not used
296 t.Errorf("got: %swant: %s", got, want)
300 func TestIssue25627(t *testing.T) {
301 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
302 // The src strings (without prefix) are constructed such that the number of semicolons
303 // plus one corresponds to the number of fields expected in the respective struct.
304 for _, src := range []string{
305 `struct { x Missing }`,
306 `struct { Missing }`,
307 `struct { *Missing }`,
308 `struct { unsafe.Pointer }`,
311 `struct { a int; b Missing; *Missing }`,
313 f := mustParse(t, prefix+src)
315 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
316 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
317 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
319 if _, ok := err.(Error); !ok {
324 syntax.Walk(f, func(n syntax.Node) bool {
325 if decl, _ := n.(*syntax.TypeDecl); decl != nil {
326 if tv, ok := info.Types[decl.Type]; ok && decl.Name.Value == "T" {
327 want := strings.Count(src, ";") + 1
328 if got := tv.Type.(*Struct).NumFields(); got != want {
329 t.Errorf("%s: got %d fields; want %d", src, got, want)
338 func TestIssue28005(t *testing.T) {
339 // method names must match defining interface name for this test
340 // (see last comment in this function)
341 sources := [...]string{
342 "package p; type A interface{ A() }",
343 "package p; type B interface{ B() }",
344 "package p; type X interface{ A; B }",
347 // compute original file ASTs
348 var orig [len(sources)]*syntax.File
349 for i, src := range sources {
350 orig[i] = mustParse(t, src)
353 // run the test for all order permutations of the incoming files
354 for _, perm := range [][len(sources)]int{
362 // create file order permutation
363 files := make([]*syntax.File, len(sources))
364 for i := range perm {
365 files[i] = orig[perm[i]]
368 // type-check package with given file order permutation
370 info := &Info{Defs: make(map[*syntax.Name]Object)}
371 _, err := conf.Check("", files, info)
376 // look for interface object X
378 for name, def := range info.Defs {
379 if name.Value == "X" {
385 t.Fatal("object X not found")
387 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
389 // Each iface method m is embedded; and m's receiver base type name
390 // must match the method's name per the choice in the source file.
391 for i := 0; i < iface.NumMethods(); i++ {
393 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
394 if recvName != m.Name() {
395 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
401 func TestIssue28282(t *testing.T) {
402 // create type interface { error }
403 et := Universe.Lookup("error").Type()
404 it := NewInterfaceType(nil, []Type{et})
406 // verify that after completing the interface, the embedded method remains unchanged
407 want := et.Underlying().(*Interface).Method(0)
410 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
412 // verify that lookup finds the same method in both interfaces (redundant check)
413 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
415 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
417 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
419 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
423 func TestIssue29029(t *testing.T) {
424 f1 := mustParse(t, `package p; type A interface { M() }`)
425 f2 := mustParse(t, `package p; var B interface { A }`)
427 // printInfo prints the *Func definitions recorded in info, one *Func per line.
428 printInfo := func(info *Info) string {
430 for _, obj := range info.Defs {
431 if fn, ok := obj.(*Func); ok {
432 fmt.Fprintln(&buf, fn)
438 // The *Func (method) definitions for package p must be the same
439 // independent on whether f1 and f2 are type-checked together, or
442 // type-check together
444 info := &Info{Defs: make(map[*syntax.Name]Object)}
445 check := NewChecker(&conf, NewPackage("", "p"), info)
446 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
449 want := printInfo(info)
451 // type-check incrementally
452 info = &Info{Defs: make(map[*syntax.Name]Object)}
453 check = NewChecker(&conf, NewPackage("", "p"), info)
454 if err := check.Files([]*syntax.File{f1}); err != nil {
457 if err := check.Files([]*syntax.File{f2}); err != nil {
460 got := printInfo(info)
463 t.Errorf("\ngot : %swant: %s", got, want)
467 func TestIssue34151(t *testing.T) {
468 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
469 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
471 a, err := pkgFor("a", asrc, nil)
473 t.Fatalf("package %s failed to typecheck: %v", a.Name(), err)
476 bast := mustParse(t, bsrc)
477 conf := Config{Importer: importHelper{pkg: a}}
478 b, err := conf.Check(bast.PkgName.Value, []*syntax.File{bast}, nil)
480 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
484 type importHelper struct {
489 func (h importHelper) Import(path string) (*Package, error) {
490 if path == h.pkg.Path() {
493 if h.fallback == nil {
494 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
496 return h.fallback.Import(path)
499 // TestIssue34921 verifies that we don't update an imported type's underlying
500 // type when resolving an underlying type. Specifically, when determining the
501 // underlying type of b.T (which is the underlying type of a.T, which is int)
502 // we must not set the underlying type of a.T again since that would lead to
503 // a race condition if package b is imported elsewhere, in a package that is
504 // concurrently type-checked.
505 func TestIssue34921(t *testing.T) {
507 if r := recover(); r != nil {
512 var sources = []string{
513 `package a; type T int`,
514 `package b; import "a"; type T a.T`,
518 for _, src := range sources {
519 f := mustParse(t, src)
520 conf := Config{Importer: importHelper{pkg: pkg}}
521 res, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
523 t.Errorf("%q failed to typecheck: %v", src, err)
525 pkg = res // res is imported by the next package in this test
529 func TestIssue43088(t *testing.T) {
539 n1 := NewTypeName(syntax.Pos{}, nil, "T1", nil)
540 T1 := NewNamed(n1, nil, nil)
541 n2 := NewTypeName(syntax.Pos{}, nil, "T2", nil)
542 T2 := NewNamed(n2, nil, nil)
543 s1 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", T2, false)}, nil)
545 s2 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", T2, false)}, nil)
546 s3 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "_", s2, false)}, nil)
549 // These calls must terminate (no endless recursion).
554 func TestIssue44515(t *testing.T) {
555 typ := Unsafe.Scope().Lookup("Pointer").Type()
557 got := TypeString(typ, nil)
558 want := "unsafe.Pointer"
560 t.Errorf("got %q; want %q", got, want)
563 qf := func(pkg *Package) string {
569 got = TypeString(typ, qf)
572 t.Errorf("got %q; want %q", got, want)
576 func TestIssue43124(t *testing.T) {
577 // All involved packages have the same name (template). Error messages should
578 // disambiguate between text/template and html/template by printing the full
581 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
582 bsrc = `package b; import ("a"; "html/template"); func _() { a.F(template.Template{}) }`
583 csrc = `package c; import ("a"; "html/template"); func _() { a.G(template.Template{}) }`
586 a, err := pkgFor("a", asrc, nil)
588 t.Fatalf("package a failed to typecheck: %v", err)
590 conf := Config{Importer: importHelper{pkg: a, fallback: defaultImporter()}}
592 // Packages should be fully qualified when there is ambiguity within the
593 // error string itself.
594 bast := mustParse(t, bsrc)
595 _, err = conf.Check(bast.PkgName.Value, []*syntax.File{bast}, nil)
597 t.Fatal("package b had no errors")
599 if !strings.Contains(err.Error(), "text/template") || !strings.Contains(err.Error(), "html/template") {
600 t.Errorf("type checking error for b does not disambiguate package template: %q", err)
603 // ...and also when there is any ambiguity in reachable packages.
604 cast := mustParse(t, csrc)
605 _, err = conf.Check(cast.PkgName.Value, []*syntax.File{cast}, nil)
607 t.Fatal("package c had no errors")
609 if !strings.Contains(err.Error(), "html/template") {
610 t.Errorf("type checking error for c does not disambiguate package template: %q", err)