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.
24 func mustParse(t *testing.T, src string) *ast.File {
25 f, err := parser.ParseFile(fset, "", src, 0)
31 func TestIssue5770(t *testing.T) {
32 f := mustParse(t, `package p; type S struct{T}`)
33 conf := Config{Importer: importer.Default()}
34 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // do not crash
35 want := "undeclared name: T"
36 if err == nil || !strings.Contains(err.Error(), want) {
37 t.Errorf("got: %v; want: %s", err, want)
41 func TestIssue5849(t *testing.T) {
49 _ = uint64(64 << s + s)
50 _ = (interface{})("foo")
51 _ = (interface{})(nil)
53 f := mustParse(t, src)
56 types := make(map[ast.Expr]TypeAndValue)
57 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Types: types})
62 for x, tv := range types {
64 switch x := x.(type) {
74 want = Typ[Uint] // because of "+ s", s is of type uint
80 want = Typ[UntypedNil]
83 if want != nil && !Identical(tv.Type, want) {
84 t.Errorf("got %s; want %s", tv.Type, want)
89 func TestIssue6413(t *testing.T) {
98 f := mustParse(t, src)
101 types := make(map[ast.Expr]TypeAndValue)
102 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Types: types})
109 for x, tv := range types {
110 if _, ok := x.(*ast.CallExpr); ok {
112 t.Errorf("%s: got %s; want %s", fset.Position(x.Pos()), tv.Type, want)
119 t.Errorf("got %d CallExprs; want 2", n)
123 func TestIssue7245(t *testing.T) {
126 func (T) m() (res bool) { return }
127 type T struct{} // receiver type after method declaration
129 f := mustParse(t, src)
132 defs := make(map[*ast.Ident]Object)
133 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs})
138 m := f.Decls[0].(*ast.FuncDecl)
139 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
140 res2 := defs[m.Type.Results.List[0].Names[0]].(*Var)
143 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
147 // This tests that uses of existing vars on the LHS of an assignment
148 // are Uses, not Defs; and also that the (illegal) use of a non-var on
149 // the LHS of an assignment is a Use nonetheless.
150 func TestIssue7827(t *testing.T) {
154 const w = 1 // defs w
155 x, y := 2, 3 // defs x, y
156 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
157 _, _, _ = x, y, z // uses x, y, z
160 f := mustParse(t, src)
162 const want = `L3 defs func p._()
163 L4 defs const w untyped int
167 L6 uses const w untyped int
173 // don't abort at the first error
174 conf := Config{Error: func(err error) { t.Log(err) }}
175 defs := make(map[*ast.Ident]Object)
176 uses := make(map[*ast.Ident]Object)
177 _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, &Info{Defs: defs, Uses: uses})
178 if s := fmt.Sprint(err); !strings.HasSuffix(s, "cannot assign to w") {
179 t.Errorf("Check: unexpected error: %s", s)
183 for id, obj := range defs {
185 fact := fmt.Sprintf("L%d defs %s", fset.Position(id.Pos()).Line, obj)
186 facts = append(facts, fact)
189 for id, obj := range uses {
190 fact := fmt.Sprintf("L%d uses %s", fset.Position(id.Pos()).Line, obj)
191 facts = append(facts, fact)
195 got := strings.Join(facts, "\n")
197 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
201 // This tests that the package associated with the types.Object.Pkg method
202 // is the type's package independent of the order in which the imports are
203 // listed in the sources src1, src2 below.
204 // The actual issue is in go/internal/gcimporter which has a corresponding
205 // test; we leave this test here to verify correct behavior at the go/types
207 func TestIssue13898(t *testing.T) {
208 testenv.MustHaveGoBuild(t)
217 for _, obj := range info.Uses {
222 // like src0, but also imports go/importer
233 for _, obj := range info.Uses {
238 // like src1 but with different import order
239 // (used to fail with this issue)
250 for _, obj := range info.Uses {
255 f := func(test, src string) {
256 f := mustParse(t, src)
257 cfg := Config{Importer: importer.Default()}
258 info := Info{Uses: make(map[*ast.Ident]Object)}
259 _, err := cfg.Check("main", fset, []*ast.File{f}, &info)
266 for id, obj := range info.Uses {
267 if id.Name == "Pkg" {
273 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
275 if pkg.Name() != "types" {
276 t.Fatalf("%s: got %v; want package types", test, pkg)
285 func TestIssue22525(t *testing.T) {
286 f := mustParse(t, `package p; func f() { var a, b, c, d, e int }`)
289 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
290 conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) // do not crash
292 1:27: a declared but not used
293 1:30: b declared but not used
294 1:33: c declared but not used
295 1:36: d declared but not used
296 1:39: e declared but not used
299 t.Errorf("got: %swant: %s", got, want)
303 func TestIssue25627(t *testing.T) {
304 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
305 // The src strings (without prefix) are constructed such that the number of semicolons
306 // plus one corresponds to the number of fields expected in the respective struct.
307 for _, src := range []string{
308 `struct { x Missing }`,
309 `struct { Missing }`,
310 `struct { *Missing }`,
311 `struct { unsafe.Pointer }`,
314 `struct { a int; b Missing; *Missing }`,
316 f := mustParse(t, prefix+src)
318 cfg := Config{Importer: importer.Default(), Error: func(err error) {}}
319 info := &Info{Types: make(map[ast.Expr]TypeAndValue)}
320 _, err := cfg.Check(f.Name.Name, fset, []*ast.File{f}, info)
322 if _, ok := err.(Error); !ok {
327 ast.Inspect(f, func(n ast.Node) bool {
328 if spec, _ := n.(*ast.TypeSpec); spec != nil {
329 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Name == "T" {
330 want := strings.Count(src, ";") + 1
331 if got := tv.Type.(*Struct).NumFields(); got != want {
332 t.Errorf("%s: got %d fields; want %d", src, got, want)
341 func TestIssue28005(t *testing.T) {
342 // method names must match defining interface name for this test
343 // (see last comment in this function)
344 sources := [...]string{
345 "package p; type A interface{ A() }",
346 "package p; type B interface{ B() }",
347 "package p; type X interface{ A; B }",
350 // compute original file ASTs
351 var orig [len(sources)]*ast.File
352 for i, src := range sources {
353 orig[i] = mustParse(t, src)
356 // run the test for all order permutations of the incoming files
357 for _, perm := range [][len(sources)]int{
365 // create file order permutation
366 files := make([]*ast.File, len(sources))
367 for i := range perm {
368 files[i] = orig[perm[i]]
371 // type-check package with given file order permutation
373 info := &Info{Defs: make(map[*ast.Ident]Object)}
374 _, err := conf.Check("", fset, files, info)
379 // look for interface object X
381 for name, def := range info.Defs {
382 if name.Name == "X" {
388 t.Fatal("interface not found")
390 iface := obj.Type().Underlying().(*Interface) // I must be an interface
392 // Each iface method m is embedded; and m's receiver base type name
393 // must match the method's name per the choice in the source file.
394 for i := 0; i < iface.NumMethods(); i++ {
396 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
397 if recvName != m.Name() {
398 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
404 func TestIssue28282(t *testing.T) {
405 // create type interface { error }
406 et := Universe.Lookup("error").Type()
407 it := NewInterfaceType(nil, []Type{et})
409 // verify that after completing the interface, the embedded method remains unchanged
410 want := et.Underlying().(*Interface).Method(0)
413 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
415 // verify that lookup finds the same method in both interfaces (redundant check)
416 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
418 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
420 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
422 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
426 func TestIssue29029(t *testing.T) {
427 f1 := mustParse(t, `package p; type A interface { M() }`)
428 f2 := mustParse(t, `package p; var B interface { A }`)
430 // printInfo prints the *Func definitions recorded in info, one *Func per line.
431 printInfo := func(info *Info) string {
433 for _, obj := range info.Defs {
434 if fn, ok := obj.(*Func); ok {
435 fmt.Fprintln(&buf, fn)
441 // The *Func (method) definitions for package p must be the same
442 // independent on whether f1 and f2 are type-checked together, or
445 // type-check together
447 info := &Info{Defs: make(map[*ast.Ident]Object)}
448 check := NewChecker(&conf, fset, NewPackage("", "p"), info)
449 if err := check.Files([]*ast.File{f1, f2}); err != nil {
452 want := printInfo(info)
454 // type-check incrementally
455 info = &Info{Defs: make(map[*ast.Ident]Object)}
456 check = NewChecker(&conf, fset, NewPackage("", "p"), info)
457 if err := check.Files([]*ast.File{f1}); err != nil {
460 if err := check.Files([]*ast.File{f2}); err != nil {
463 got := printInfo(info)
466 t.Errorf("\ngot : %swant: %s", got, want)
470 func TestIssue34151(t *testing.T) {
471 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
472 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
474 a, err := pkgFor("a", asrc, nil)
476 t.Fatalf("package %s failed to typecheck: %v", a.Name(), err)
479 bast := mustParse(t, bsrc)
480 conf := Config{Importer: importHelper{a}}
481 b, err := conf.Check(bast.Name.Name, fset, []*ast.File{bast}, nil)
483 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
487 type importHelper struct {
491 func (h importHelper) Import(path string) (*Package, error) {
492 if path != h.pkg.Path() {
493 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
498 // TestIssue34921 verifies that we don't update an imported type's underlying
499 // type when resolving an underlying type. Specifically, when determining the
500 // underlying type of b.T (which is the underlying type of a.T, which is int)
501 // we must not set the underlying type of a.T again since that would lead to
502 // a race condition if package b is imported elsewhere, in a package that is
503 // concurrently type-checked.
504 func TestIssue34921(t *testing.T) {
506 if r := recover(); r != nil {
511 var sources = []string{
512 `package a; type T int`,
513 `package b; import "a"; type T a.T`,
517 for _, src := range sources {
518 f := mustParse(t, src)
519 conf := Config{Importer: importHelper{pkg}}
520 res, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
522 t.Errorf("%q failed to typecheck: %v", src, err)
524 pkg = res // res is imported by the next package in this test
528 func TestIssue43088(t *testing.T) {
538 n1 := NewTypeName(token.NoPos, nil, "T1", nil)
539 T1 := NewNamed(n1, nil, nil)
540 n2 := NewTypeName(token.NoPos, nil, "T2", nil)
541 T2 := NewNamed(n2, nil, nil)
542 s1 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", T2, false)}, nil)
544 s2 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", T2, false)}, nil)
545 s3 := NewStruct([]*Var{NewField(token.NoPos, nil, "_", s2, false)}, nil)
548 // These calls must terminate (no endless recursion).