]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/issues_test.go
[dev.typeparams] all: merge dev.regabi (37f138d) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / types2 / issues_test.go
1 // +build TODO_RSC_REMOVE_THIS
2
3 // UNREVIEWED
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.
7
8 // This file implements tests for various issues.
9
10 package types2_test
11
12 import (
13         "bytes"
14         "cmd/compile/internal/syntax"
15         "fmt"
16         "internal/testenv"
17         "sort"
18         "strings"
19         "testing"
20
21         . "cmd/compile/internal/types2"
22 )
23
24 func mustParse(t *testing.T, src string) *syntax.File {
25         f, err := parseSrc("", src)
26         if err != nil {
27                 t.Fatal(err)
28         }
29         return f
30 }
31 func TestIssue5770(t *testing.T) {
32         f := mustParse(t, `package p; type S struct{T}`)
33         var conf Config
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)
39         }
40 }
41
42 func TestIssue5849(t *testing.T) {
43         src := `
44 package p
45 var (
46         s uint
47         _ = uint8(8)
48         _ = uint16(16) << s
49         _ = uint32(32 << s)
50         _ = uint64(64 << s + s)
51         _ = (interface{})("foo")
52         _ = (interface{})(nil)
53 )`
54         f := mustParse(t, src)
55
56         var conf Config
57         types := make(map[syntax.Expr]TypeAndValue)
58         _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
59         if err != nil {
60                 t.Fatal(err)
61         }
62
63         for x, tv := range types {
64                 var want Type
65                 switch x := x.(type) {
66                 case *syntax.BasicLit:
67                         switch x.Value {
68                         case `8`:
69                                 want = Typ[Uint8]
70                         case `16`:
71                                 want = Typ[Uint16]
72                         case `32`:
73                                 want = Typ[Uint32]
74                         case `64`:
75                                 want = Typ[Uint] // because of "+ s", s is of type uint
76                         case `"foo"`:
77                                 want = Typ[String]
78                         }
79                 case *syntax.Name:
80                         if x.Value == "nil" {
81                                 want = Typ[UntypedNil]
82                         }
83                 }
84                 if want != nil && !Identical(tv.Type, want) {
85                         t.Errorf("got %s; want %s", tv.Type, want)
86                 }
87         }
88 }
89
90 func TestIssue6413(t *testing.T) {
91         src := `
92 package p
93 func f() int {
94         defer f()
95         go f()
96         return 0
97 }
98 `
99         f := mustParse(t, src)
100
101         var conf Config
102         types := make(map[syntax.Expr]TypeAndValue)
103         _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Types: types})
104         if err != nil {
105                 t.Fatal(err)
106         }
107
108         want := Typ[Int]
109         n := 0
110         for x, tv := range types {
111                 if _, ok := x.(*syntax.CallExpr); ok {
112                         if tv.Type != want {
113                                 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
114                         }
115                         n++
116                 }
117         }
118
119         if n != 2 {
120                 t.Errorf("got %d CallExprs; want 2", n)
121         }
122 }
123
124 func TestIssue7245(t *testing.T) {
125         src := `
126 package p
127 func (T) m() (res bool) { return }
128 type T struct{} // receiver type after method declaration
129 `
130         f := mustParse(t, src)
131
132         var conf Config
133         defs := make(map[*syntax.Name]Object)
134         _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
135         if err != nil {
136                 t.Fatal(err)
137         }
138
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)
142
143         if res1 != res2 {
144                 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
145         }
146 }
147
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) {
152         const src = `
153 package p
154 func _() {
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
159 }
160 `
161         f := mustParse(t, src)
162
163         const want = `L3 defs func p._()
164 L4 defs const w untyped int
165 L5 defs var x int
166 L5 defs var y int
167 L6 defs var z int
168 L6 uses const w untyped int
169 L6 uses var x int
170 L7 uses var x int
171 L7 uses var y int
172 L7 uses var z int`
173
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)
181         }
182
183         var facts []string
184         for id, obj := range defs {
185                 if obj != nil {
186                         fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
187                         facts = append(facts, fact)
188                 }
189         }
190         for id, obj := range uses {
191                 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
192                 facts = append(facts, fact)
193         }
194         sort.Strings(facts)
195
196         got := strings.Join(facts, "\n")
197         if got != want {
198                 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
199         }
200 }
201
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
207 // level.
208 func TestIssue13898(t *testing.T) {
209         testenv.MustHaveGoBuild(t)
210
211         const src0 = `
212 package main
213
214 import "go/types"
215
216 func main() {
217         var info types.Info
218         for _, obj := range info.Uses {
219                 _ = obj.Pkg()
220         }
221 }
222 `
223         // like src0, but also imports go/importer
224         const src1 = `
225 package main
226
227 import (
228         "go/types"
229         _ "go/importer"
230 )
231
232 func main() {
233         var info types.Info
234         for _, obj := range info.Uses {
235                 _ = obj.Pkg()
236         }
237 }
238 `
239         // like src1 but with different import order
240         // (used to fail with this issue)
241         const src2 = `
242 package main
243
244 import (
245         _ "go/importer"
246         "go/types"
247 )
248
249 func main() {
250         var info types.Info
251         for _, obj := range info.Uses {
252                 _ = obj.Pkg()
253         }
254 }
255 `
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)
261                 if err != nil {
262                         t.Fatal(err)
263                 }
264
265                 var pkg *Package
266                 count := 0
267                 for id, obj := range info.Uses {
268                         if id.Value == "Pkg" {
269                                 pkg = obj.Pkg()
270                                 count++
271                         }
272                 }
273                 if count != 1 {
274                         t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
275                 }
276                 if pkg.Name() != "types" {
277                         t.Fatalf("%s: got %v; want package types2", test, pkg)
278                 }
279         }
280
281         f("src0", src0)
282         f("src1", src1)
283         f("src2", src2)
284 }
285
286 func TestIssue22525(t *testing.T) {
287         f := mustParse(t, `package p; func f() { var a, b, c, d, e int }`)
288
289         got := "\n"
290         conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
291         conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // do not crash
292         want := `
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
298 `
299         if got != want {
300                 t.Errorf("got: %swant: %s", got, want)
301         }
302 }
303
304 func TestIssue25627(t *testing.T) {
305         t.Skip("requires syntax tree inspection")
306
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 }`,
315                 `struct { P }`,
316                 `struct { *I }`,
317                 `struct { a int; b Missing; *Missing }`,
318         } {
319                 f := mustParse(t, prefix+src)
320
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)
324                 if err != nil {
325                         if _, ok := err.(Error); !ok {
326                                 t.Fatal(err)
327                         }
328                 }
329
330                 unimplemented()
331                 /*
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)
338                                                 }
339                                         }
340                                 }
341                                 return true
342                         })
343                 */
344         }
345 }
346
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 }",
354         }
355
356         // compute original file ASTs
357         var orig [len(sources)]*syntax.File
358         for i, src := range sources {
359                 orig[i] = mustParse(t, src)
360         }
361
362         // run the test for all order permutations of the incoming files
363         for _, perm := range [][len(sources)]int{
364                 {0, 1, 2},
365                 {0, 2, 1},
366                 {1, 0, 2},
367                 {1, 2, 0},
368                 {2, 0, 1},
369                 {2, 1, 0},
370         } {
371                 // create file order permutation
372                 files := make([]*syntax.File, len(sources))
373                 for i := range perm {
374                         files[i] = orig[perm[i]]
375                 }
376
377                 // type-check package with given file order permutation
378                 var conf Config
379                 info := &Info{Defs: make(map[*syntax.Name]Object)}
380                 _, err := conf.Check("", files, info)
381                 if err != nil {
382                         t.Fatal(err)
383                 }
384
385                 // look for interface object X
386                 var obj Object
387                 for name, def := range info.Defs {
388                         if name.Value == "X" {
389                                 obj = def
390                                 break
391                         }
392                 }
393                 if obj == nil {
394                         t.Fatal("object X not found")
395                 }
396                 iface := obj.Type().Interface() // object X must be an interface
397                 if iface == nil {
398                         t.Fatalf("%s is not an interface", obj)
399                 }
400
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++ {
404                         m := iface.Method(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())
408                         }
409                 }
410         }
411 }
412
413 func TestIssue28282(t *testing.T) {
414         // create type interface { error }
415         et := Universe.Lookup("error").Type()
416         it := NewInterfaceType(nil, []Type{et})
417         it.Complete()
418         // verify that after completing the interface, the embedded method remains unchanged
419         want := et.Interface().Method(0)
420         got := it.Method(0)
421         if got != want {
422                 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
423         }
424         // verify that lookup finds the same method in both interfaces (redundant check)
425         obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
426         if obj != want {
427                 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
428         }
429         obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
430         if obj != want {
431                 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
432         }
433 }
434
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 }`)
438
439         // printInfo prints the *Func definitions recorded in info, one *Func per line.
440         printInfo := func(info *Info) string {
441                 var buf bytes.Buffer
442                 for _, obj := range info.Defs {
443                         if fn, ok := obj.(*Func); ok {
444                                 fmt.Fprintln(&buf, fn)
445                         }
446                 }
447                 return buf.String()
448         }
449
450         // The *Func (method) definitions for package p must be the same
451         // independent on whether f1 and f2 are type-checked together, or
452         // incrementally.
453
454         // type-check together
455         var conf Config
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 {
459                 t.Fatal(err)
460         }
461         want := printInfo(info)
462
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 {
467                 t.Fatal(err)
468         }
469         if err := check.Files([]*syntax.File{f2}); err != nil {
470                 t.Fatal(err)
471         }
472         got := printInfo(info)
473
474         if got != want {
475                 t.Errorf("\ngot : %swant: %s", got, want)
476         }
477 }
478
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{})`
482
483         a, err := pkgFor("a", asrc, nil)
484         if err != nil {
485                 t.Fatalf("package %s failed to typecheck: %v", a.Name(), err)
486         }
487
488         bast := mustParse(t, bsrc)
489         conf := Config{Importer: importHelper{a}}
490         b, err := conf.Check(bast.PkgName.Value, []*syntax.File{bast}, nil)
491         if err != nil {
492                 t.Errorf("package %s failed to typecheck: %v", b.Name(), err)
493         }
494 }
495
496 type importHelper struct {
497         pkg *Package
498 }
499
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())
503         }
504         return h.pkg, nil
505 }
506
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) {
514         defer func() {
515                 if r := recover(); r != nil {
516                         t.Error(r)
517                 }
518         }()
519
520         var sources = []string{
521                 `package a; type T int`,
522                 `package b; import "a"; type T a.T`,
523         }
524
525         var pkg *Package
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)
530                 if err != nil {
531                         t.Errorf("%q failed to typecheck: %v", src, err)
532                 }
533                 pkg = res // res is imported by the next package in this test
534         }
535 }
536
537 func TestIssue43088(t *testing.T) {
538         // type T1 struct {
539         //         x T2
540         // }
541         //
542         // type T2 struct {
543         //         x struct {
544         //                 x T2
545         //         }
546         // }
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)
552         T1.SetUnderlying(s1)
553         s2 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", T2, false)}, nil)
554         s3 := NewStruct([]*Var{NewField(syntax.Pos{}, nil, "x", s2, false)}, nil)
555         T2.SetUnderlying(s3)
556
557         // These calls must terminate (no endless recursion).
558         Comparable(T1)
559         Comparable(T2)
560 }