1 // +build TODO_RSC_REMOVE_THIS
4 // Copyright 2013 The Go Authors. All rights reserved.
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file.
8 // This file implements tests for various issues.
14 "cmd/compile/internal/syntax"
21 . "cmd/compile/internal/types2"
24 func mustParse(t *testing.T, src string) *syntax.File {
25 f, err := parseSrc("", src)
31 func TestIssue5770(t *testing.T) {
32 f := mustParse(t, `package p; type S struct{T}`)
34 // conf := Config{Importer: importer.Default()}
35 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
36 want := "undeclared name: T"
37 if err == nil || !strings.Contains(err.Error(), want) {
38 t.Errorf("got: %v; want: %s", err, want)
42 func TestIssue5849(t *testing.T) {
50 _ = uint64(64 << s + s)
51 _ = (interface{})("foo")
52 _ = (interface{})(nil)
54 f := mustParse(t, src)
57 types := make(map[syntax.Expr]TypeAndValue)
58 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
63 for x, tv := range types {
65 switch x := x.(type) {
66 case *syntax.BasicLit:
75 want = Typ[Uint] // because of "+ s", s is of type uint
81 want = Typ[UntypedNil]
84 if want != nil && !Identical(tv.Type, want) {
85 t.Errorf("got %s; want %s", tv.Type, want)
90 func TestIssue6413(t *testing.T) {
99 f := mustParse(t, src)
102 types := make(map[syntax.Expr]TypeAndValue)
103 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
110 for x, tv := range types {
111 if _, ok := x.(*syntax.CallExpr); ok {
113 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
120 t.Errorf("got %d CallExprs; want 2", n)
124 func TestIssue7245(t *testing.T) {
127 func (T) m() (res bool) { return }
128 type T struct{} // receiver type after method declaration
130 f := mustParse(t, src)
133 defs := make(map[*syntax.Name]Object)
134 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
139 m := f.DeclList[0].(*syntax.FuncDecl)
140 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
141 res2 := defs[m.Type.ResultList[0].Name].(*Var)
144 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
148 // This tests that uses of existing vars on the LHS of an assignment
149 // are Uses, not Defs; and also that the (illegal) use of a non-var on
150 // the LHS of an assignment is a Use nonetheless.
151 func TestIssue7827(t *testing.T) {
155 const w = 1 // defs w
156 x, y := 2, 3 // defs x, y
157 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
158 _, _, _ = x, y, z // uses x, y, z
161 f := mustParse(t, src)
163 const want = `L3 defs func p._()
164 L4 defs const w untyped int
168 L6 uses const w untyped int
174 // don't abort at the first error
175 conf := Config{Error: func(err error) { t.Log(err) }}
176 defs := make(map[*syntax.Name]Object)
177 uses := make(map[*syntax.Name]Object)
178 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs, Uses: uses})
179 if s := fmt.Sprint(err); !strings.HasSuffix(s, "cannot assign to w") {
180 t.Errorf("Check: unexpected error: %s", s)
184 for id, obj := range defs {
186 fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
187 facts = append(facts, fact)
190 for id, obj := range uses {
191 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
192 facts = append(facts, fact)
196 got := strings.Join(facts, "\n")
198 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
202 // This tests that the package associated with the types.Object.Pkg method
203 // is the type's package independent of the order in which the imports are
204 // listed in the sources src1, src2 below.
205 // The actual issue is in go/internal/gcimporter which has a corresponding
206 // test; we leave this test here to verify correct behavior at the go/types
208 func TestIssue13898(t *testing.T) {
209 testenv.MustHaveGoBuild(t)
218 for _, obj := range info.Uses {
223 // like src0, but also imports go/importer
234 for _, obj := range info.Uses {
239 // like src1 but with different import order
240 // (used to fail with this issue)
251 for _, obj := range info.Uses {
256 f := func(test, src string) {
257 f := mustParse(t, src)
258 conf := Config{Importer: defaultImporter()}
259 info := Info{Uses: make(map[*syntax.Name]Object)}
260 _, err := conf.Check("main", []*syntax.File{f}, &info)
267 for id, obj := range info.Uses {
268 if id.Value == "Pkg" {
274 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
276 if pkg.Name() != "types" {
277 t.Fatalf("%s: got %v; want package types2", test, pkg)
286 func TestIssue22525(t *testing.T) {
287 f := mustParse(t, `package p; func f() { var a, b, c, d, e int }`)
290 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
291 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
293 :1:27: a declared but not used
294 :1:30: b declared but not used
295 :1:33: c declared but not used
296 :1:36: d declared but not used
297 :1:39: e declared but not used
300 t.Errorf("got: %swant: %s", got, want)
304 func TestIssue25627(t *testing.T) {
305 t.Skip("requires syntax tree inspection")
307 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
308 // The src strings (without prefix) are constructed such that the number of semicolons
309 // plus one corresponds to the number of fields expected in the respective struct.
310 for _, src := range []string{
311 `struct { x Missing }`,
312 `struct { Missing }`,
313 `struct { *Missing }`,
314 `struct { unsafe.Pointer }`,
317 `struct { a int; b Missing; *Missing }`,
319 f := mustParse(t, prefix+src)
321 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
322 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
323 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
325 if _, ok := err.(Error); !ok {
332 ast.Inspect(f, func(n syntax.Node) bool {
333 if spec, _ := n.(*syntax.TypeDecl); spec != nil {
334 if tv, ok := info.Types[spec.Type]; ok && spec.Name.Value == "T" {
335 want := strings.Count(src, ";") + 1
336 if got := tv.Type.(*Struct).NumFields(); got != want {
337 t.Errorf("%s: got %d fields; want %d", src, got, want)
347 func TestIssue28005(t *testing.T) {
348 // method names must match defining interface name for this test
349 // (see last comment in this function)
350 sources := [...]string{
351 "package p; type A interface{ A() }",
352 "package p; type B interface{ B() }",
353 "package p; type X interface{ A; B }",
356 // compute original file ASTs
357 var orig [len(sources)]*syntax.File
358 for i, src := range sources {
359 orig[i] = mustParse(t, src)
362 // run the test for all order permutations of the incoming files
363 for _, perm := range [][len(sources)]int{
371 // create file order permutation
372 files := make([]*syntax.File, len(sources))
373 for i := range perm {
374 files[i] = orig[perm[i]]
377 // type-check package with given file order permutation
379 info := &Info{Defs: make(map[*syntax.Name]Object)}
380 _, err := conf.Check("", files, info)
385 // look for interface object X
387 for name, def := range info.Defs {
388 if name.Value == "X" {
394 t.Fatal("object X not found")
396 iface := obj.Type().Interface() // object X must be an interface
398 t.Fatalf("%s is not an interface", obj)
401 // Each iface method m is embedded; and m's receiver base type name
402 // must match the method's name per the choice in the source file.
403 for i := 0; i < iface.NumMethods(); i++ {
405 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
406 if recvName != m.Name() {
407 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
413 func TestIssue28282(t *testing.T) {
414 // create type interface { error }
415 et := Universe.Lookup("error").Type()
416 it := NewInterfaceType(nil, []Type{et})
418 // verify that after completing the interface, the embedded method remains unchanged
419 want := et.Interface().Method(0)
422 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
424 // verify that lookup finds the same method in both interfaces (redundant check)
425 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
427 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
429 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
431 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
435 func TestIssue29029(t *testing.T) {
436 f1 := mustParse(t, `package p; type A interface { M() }`)
437 f2 := mustParse(t, `package p; var B interface { A }`)
439 // printInfo prints the *Func definitions recorded in info, one *Func per line.
440 printInfo := func(info *Info) string {
442 for _, obj := range info.Defs {
443 if fn, ok := obj.(*Func); ok {
444 fmt.Fprintln(&buf, fn)
450 // The *Func (method) definitions for package p must be the same
451 // independent on whether f1 and f2 are type-checked together, or
454 // type-check together
456 info := &Info{Defs: make(map[*syntax.Name]Object)}
457 check := NewChecker(&conf, NewPackage("", "p"), info)
458 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
461 want := printInfo(info)
463 // type-check incrementally
464 info = &Info{Defs: make(map[*syntax.Name]Object)}
465 check = NewChecker(&conf, NewPackage("", "p"), info)
466 if err := check.Files([]*syntax.File{f1}); err != nil {
469 if err := check.Files([]*syntax.File{f2}); err != nil {
472 got := printInfo(info)
475 t.Errorf("\ngot : %swant: %s", got, want)
479 func TestIssue34151(t *testing.T) {
480 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
481 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
483 a, err := pkgFor("a", asrc, nil)
485 t.Fatalf("package %s failed to typecheck: %v", a.Name(), err)
488 bast := mustParse(t, bsrc)
489 conf := Config{Importer: importHelper{a}}
490 b, err := conf.Check(bast.PkgName.Value, []*syntax.File{bast}, nil)
492 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
496 type importHelper struct {
500 func (h importHelper) Import(path string) (*Package, error) {
501 if path != h.pkg.Path() {
502 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
507 // TestIssue34921 verifies that we don't update an imported type's underlying
508 // type when resolving an underlying type. Specifically, when determining the
509 // underlying type of b.T (which is the underlying type of a.T, which is int)
510 // we must not set the underlying type of a.T again since that would lead to
511 // a race condition if package b is imported elsewhere, in a package that is
512 // concurrently type-checked.
513 func TestIssue34921(t *testing.T) {
515 if r := recover(); r != nil {
520 var sources = []string{
521 `package a; type T int`,
522 `package b; import "a"; type T a.T`,
526 for _, src := range sources {
527 f := mustParse(t, src)
528 conf := Config{Importer: importHelper{pkg}}
529 res, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
531 t.Errorf("%q failed to typecheck: %v", src, err)
533 pkg = res // res is imported by the next package in this test
537 func TestIssue43088(t *testing.T) {
547 n1 := NewTypeName(syntax.Pos{}, nil, "T1", nil)
548 T1 := NewNamed(n1, nil, nil)
549 n2 := NewTypeName(syntax.Pos{}, nil, "T2", nil)
550 T2 := NewNamed(n2, nil, nil)
551 s1 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", T2, false)}, nil)
553 s2 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", T2, false)}, nil)
554 s3 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", s2, false)}, nil)
557 // These calls must terminate (no endless recursion).