2 // Copyright 2013 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
6 // This file implements tests for various issues.
12 "cmd/compile/internal/syntax"
19 . "cmd/compile/internal/types2"
22 func mustParse(t *testing.T, src string) *syntax.File {
23 f, err := parseSrc("", src)
29 func TestIssue5770(t *testing.T) {
30 f := mustParse(t, `package p; type S struct{T}`)
32 // conf := Config{Importer: importer.Default()}
33 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
34 want := "undeclared name: T"
35 if err == nil || !strings.Contains(err.Error(), want) {
36 t.Errorf("got: %v; want: %s", err, want)
40 func TestIssue5849(t *testing.T) {
48 _ = uint64(64 << s + s)
49 _ = (interface{})("foo")
50 _ = (interface{})(nil)
52 f := mustParse(t, src)
55 types := make(map[syntax.Expr]TypeAndValue)
56 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
61 for x, tv := range types {
63 switch x := x.(type) {
64 case *syntax.BasicLit:
73 want = Typ[Uint] // because of "+ s", s is of type uint
79 want = NewInterfaceType(nil, nil) // interface{}
82 if want != nil && !Identical(tv.Type, want) {
83 t.Errorf("got %s; want %s", tv.Type, want)
88 func TestIssue6413(t *testing.T) {
97 f := mustParse(t, src)
100 types := make(map[syntax.Expr]TypeAndValue)
101 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
108 for x, tv := range types {
109 if _, ok := x.(*syntax.CallExpr); ok {
111 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
118 t.Errorf("got %d CallExprs; want 2", n)
122 func TestIssue7245(t *testing.T) {
125 func (T) m() (res bool) { return }
126 type T struct{} // receiver type after method declaration
128 f := mustParse(t, src)
131 defs := make(map[*syntax.Name]Object)
132 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
137 m := f.DeclList[0].(*syntax.FuncDecl)
138 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
139 res2 := defs[m.Type.ResultList[0].Name].(*Var)
142 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
146 // This tests that uses of existing vars on the LHS of an assignment
147 // are Uses, not Defs; and also that the (illegal) use of a non-var on
148 // the LHS of an assignment is a Use nonetheless.
149 func TestIssue7827(t *testing.T) {
153 const w = 1 // defs w
154 x, y := 2, 3 // defs x, y
155 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
156 _, _, _ = x, y, z // uses x, y, z
159 f := mustParse(t, src)
161 const want = `L3 defs func p._()
162 L4 defs const w untyped int
166 L6 uses const w untyped int
172 // don't abort at the first error
173 conf := Config{Error: func(err error) { t.Log(err) }}
174 defs := make(map[*syntax.Name]Object)
175 uses := make(map[*syntax.Name]Object)
176 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs, Uses: uses})
177 if s := fmt.Sprint(err); !strings.HasSuffix(s, "cannot assign to w") {
178 t.Errorf("Check: unexpected error: %s", s)
182 for id, obj := range defs {
184 fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
185 facts = append(facts, fact)
188 for id, obj := range uses {
189 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
190 facts = append(facts, fact)
194 got := strings.Join(facts, "\n")
196 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
200 // This tests that the package associated with the types.Object.Pkg method
201 // is the type's package independent of the order in which the imports are
202 // listed in the sources src1, src2 below.
203 // The actual issue is in go/internal/gcimporter which has a corresponding
204 // test; we leave this test here to verify correct behavior at the go/types
206 func TestIssue13898(t *testing.T) {
207 testenv.MustHaveGoBuild(t)
216 for _, obj := range info.Uses {
221 // like src0, but also imports go/importer
232 for _, obj := range info.Uses {
237 // like src1 but with different import order
238 // (used to fail with this issue)
249 for _, obj := range info.Uses {
254 f := func(test, src string) {
255 f := mustParse(t, src)
256 conf := Config{Importer: defaultImporter()}
257 info := Info{Uses: make(map[*syntax.Name]Object)}
258 _, err := conf.Check("main", []*syntax.File{f}, &info)
265 for id, obj := range info.Uses {
266 if id.Value == "Pkg" {
272 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
274 if pkg.Name() != "types" {
275 t.Fatalf("%s: got %v; want package types2", test, pkg)
284 func TestIssue22525(t *testing.T) {
285 f := mustParse(t, `package p; func f() { var a, b, c, d, e int }`)
288 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
289 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
291 :1:27: a declared but not used
292 :1:30: b declared but not used
293 :1:33: c declared but not used
294 :1:36: d declared but not used
295 :1:39: e declared but not used
298 t.Errorf("got: %swant: %s", got, want)
302 func TestIssue25627(t *testing.T) {
303 t.Skip("requires syntax tree inspection")
305 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
306 // The src strings (without prefix) are constructed such that the number of semicolons
307 // plus one corresponds to the number of fields expected in the respective struct.
308 for _, src := range []string{
309 `struct { x Missing }`,
310 `struct { Missing }`,
311 `struct { *Missing }`,
312 `struct { unsafe.Pointer }`,
315 `struct { a int; b Missing; *Missing }`,
317 f := mustParse(t, prefix+src)
319 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
320 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
321 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
323 if _, ok := err.(Error); !ok {
330 ast.Inspect(f, func(n syntax.Node) bool {
331 if spec, _ := n.(*syntax.TypeDecl); spec != nil {
332 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Value == "T" {
333 want := strings.Count(src, ";") + 1
334 if got := tv.Type.(*Struct).NumFields(); got != want {
335 t.Errorf("%s: got %d fields; want %d", src, got, want)
345 func TestIssue28005(t *testing.T) {
346 // method names must match defining interface name for this test
347 // (see last comment in this function)
348 sources := [...]string{
349 "package p; type A interface{ A() }",
350 "package p; type B interface{ B() }",
351 "package p; type X interface{ A; B }",
354 // compute original file ASTs
355 var orig [len(sources)]*syntax.File
356 for i, src := range sources {
357 orig[i] = mustParse(t, src)
360 // run the test for all order permutations of the incoming files
361 for _, perm := range [][len(sources)]int{
369 // create file order permutation
370 files := make([]*syntax.File, len(sources))
371 for i := range perm {
372 files[i] = orig[perm[i]]
375 // type-check package with given file order permutation
377 info := &Info{Defs: make(map[*syntax.Name]Object)}
378 _, err := conf.Check("", files, info)
383 // look for interface object X
385 for name, def := range info.Defs {
386 if name.Value == "X" {
392 t.Fatal("object X not found")
394 iface := obj.Type().Underlying().(*Interface) // object X must be an interface
396 t.Fatalf("%s is not an interface", obj)
399 // Each iface method m is embedded; and m's receiver base type name
400 // must match the method's name per the choice in the source file.
401 for i := 0; i < iface.NumMethods(); i++ {
403 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
404 if recvName != m.Name() {
405 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
411 func TestIssue28282(t *testing.T) {
412 // create type interface { error }
413 et := Universe.Lookup("error").Type()
414 it := NewInterfaceType(nil, []Type{et})
416 // verify that after completing the interface, the embedded method remains unchanged
417 want := et.Underlying().(*Interface).Method(0)
420 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
422 // verify that lookup finds the same method in both interfaces (redundant check)
423 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
425 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
427 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
429 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
433 func TestIssue29029(t *testing.T) {
434 f1 := mustParse(t, `package p; type A interface { M() }`)
435 f2 := mustParse(t, `package p; var B interface { A }`)
437 // printInfo prints the *Func definitions recorded in info, one *Func per line.
438 printInfo := func(info *Info) string {
440 for _, obj := range info.Defs {
441 if fn, ok := obj.(*Func); ok {
442 fmt.Fprintln(&buf, fn)
448 // The *Func (method) definitions for package p must be the same
449 // independent on whether f1 and f2 are type-checked together, or
452 // type-check together
454 info := &Info{Defs: make(map[*syntax.Name]Object)}
455 check := NewChecker(&conf, NewPackage("", "p"), info)
456 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
459 want := printInfo(info)
461 // type-check incrementally
462 info = &Info{Defs: make(map[*syntax.Name]Object)}
463 check = NewChecker(&conf, NewPackage("", "p"), info)
464 if err := check.Files([]*syntax.File{f1}); err != nil {
467 if err := check.Files([]*syntax.File{f2}); err != nil {
470 got := printInfo(info)
473 t.Errorf("\ngot : %swant: %s", got, want)
477 func TestIssue34151(t *testing.T) {
478 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
479 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
481 a, err := pkgFor("a", asrc, nil)
483 t.Fatalf("package %s failed to typecheck: %v", a.Name(), err)
486 bast := mustParse(t, bsrc)
487 conf := Config{Importer: importHelper{a}}
488 b, err := conf.Check(bast.PkgName.Value, []*syntax.File{bast}, nil)
490 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
494 type importHelper struct {
498 func (h importHelper) Import(path string) (*Package, error) {
499 if path != h.pkg.Path() {
500 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
505 // TestIssue34921 verifies that we don't update an imported type's underlying
506 // type when resolving an underlying type. Specifically, when determining the
507 // underlying type of b.T (which is the underlying type of a.T, which is int)
508 // we must not set the underlying type of a.T again since that would lead to
509 // a race condition if package b is imported elsewhere, in a package that is
510 // concurrently type-checked.
511 func TestIssue34921(t *testing.T) {
513 if r := recover(); r != nil {
518 var sources = []string{
519 `package a; type T int`,
520 `package b; import "a"; type T a.T`,
524 for _, src := range sources {
525 f := mustParse(t, src)
526 conf := Config{Importer: importHelper{pkg}}
527 res, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
529 t.Errorf("%q failed to typecheck: %v", src, err)
531 pkg = res // res is imported by the next package in this test
535 func TestIssue43088(t *testing.T) {
545 n1 := NewTypeName(syntax.Pos{}, nil, "T1", nil)
546 T1 := NewNamed(n1, nil, nil)
547 n2 := NewTypeName(syntax.Pos{}, nil, "T2", nil)
548 T2 := NewNamed(n2, nil, nil)
549 s1 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", T2, false)}, nil)
551 s2 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", T2, false)}, nil)
552 s3 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", s2, false)}, nil)
555 // These calls must terminate (no endless recursion).