1
2
3
4
5
6
7 package types2_test
8
9 import (
10 "cmd/compile/internal/syntax"
11 "fmt"
12 "internal/testenv"
13 "regexp"
14 "sort"
15 "strings"
16 "testing"
17
18 . "cmd/compile/internal/types2"
19 )
20
21 func TestIssue5770(t *testing.T) {
22 _, err := typecheck(`package p; type S struct{T}`, nil, nil)
23 const want = "undefined: T"
24 if err == nil || !strings.Contains(err.Error(), want) {
25 t.Errorf("got: %v; want: %s", err, want)
26 }
27 }
28
29 func TestIssue5849(t *testing.T) {
30 src := `
31 package p
32 var (
33 s uint
34 _ = uint8(8)
35 _ = uint16(16) << s
36 _ = uint32(32 << s)
37 _ = uint64(64 << s + s)
38 _ = (interface{})("foo")
39 _ = (interface{})(nil)
40 )`
41 types := make(map[syntax.Expr]TypeAndValue)
42 mustTypecheck(src, nil, &Info{Types: types})
43
44 for x, tv := range types {
45 var want Type
46 switch x := x.(type) {
47 case *syntax.BasicLit:
48 switch x.Value {
49 case `8`:
50 want = Typ[Uint8]
51 case `16`:
52 want = Typ[Uint16]
53 case `32`:
54 want = Typ[Uint32]
55 case `64`:
56 want = Typ[Uint]
57 case `"foo"`:
58 want = Typ[String]
59 }
60 case *syntax.Name:
61 if x.Value == "nil" {
62 want = NewInterfaceType(nil, nil)
63 }
64 }
65 if want != nil && !Identical(tv.Type, want) {
66 t.Errorf("got %s; want %s", tv.Type, want)
67 }
68 }
69 }
70
71 func TestIssue6413(t *testing.T) {
72 src := `
73 package p
74 func f() int {
75 defer f()
76 go f()
77 return 0
78 }
79 `
80 types := make(map[syntax.Expr]TypeAndValue)
81 mustTypecheck(src, nil, &Info{Types: types})
82
83 want := Typ[Int]
84 n := 0
85 for x, tv := range types {
86 if _, ok := x.(*syntax.CallExpr); ok {
87 if tv.Type != want {
88 t.Errorf("%s: got %s; want %s", x.Pos(), tv.Type, want)
89 }
90 n++
91 }
92 }
93
94 if n != 2 {
95 t.Errorf("got %d CallExprs; want 2", n)
96 }
97 }
98
99 func TestIssue7245(t *testing.T) {
100 src := `
101 package p
102 func (T) m() (res bool) { return }
103 type T struct{} // receiver type after method declaration
104 `
105 f := mustParse(src)
106
107 var conf Config
108 defs := make(map[*syntax.Name]Object)
109 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, &Info{Defs: defs})
110 if err != nil {
111 t.Fatal(err)
112 }
113
114 m := f.DeclList[0].(*syntax.FuncDecl)
115 res1 := defs[m.Name].(*Func).Type().(*Signature).Results().At(0)
116 res2 := defs[m.Type.ResultList[0].Name].(*Var)
117
118 if res1 != res2 {
119 t.Errorf("got %s (%p) != %s (%p)", res1, res2, res1, res2)
120 }
121 }
122
123
124
125
126 func TestIssue7827(t *testing.T) {
127 const src = `
128 package p
129 func _() {
130 const w = 1 // defs w
131 x, y := 2, 3 // defs x, y
132 w, x, z := 4, 5, 6 // uses w, x, defs z; error: cannot assign to w
133 _, _, _ = x, y, z // uses x, y, z
134 }
135 `
136 const want = `L3 defs func p._()
137 L4 defs const w untyped int
138 L5 defs var x int
139 L5 defs var y int
140 L6 defs var z int
141 L6 uses const w untyped int
142 L6 uses var x int
143 L7 uses var x int
144 L7 uses var y int
145 L7 uses var z int`
146
147
148 conf := Config{Error: func(err error) { t.Log(err) }}
149 defs := make(map[*syntax.Name]Object)
150 uses := make(map[*syntax.Name]Object)
151 _, err := typecheck(src, &conf, &Info{Defs: defs, Uses: uses})
152 if s := err.Error(); !strings.HasSuffix(s, "cannot assign to w") {
153 t.Errorf("Check: unexpected error: %s", s)
154 }
155
156 var facts []string
157 for id, obj := range defs {
158 if obj != nil {
159 fact := fmt.Sprintf("L%d defs %s", id.Pos().Line(), obj)
160 facts = append(facts, fact)
161 }
162 }
163 for id, obj := range uses {
164 fact := fmt.Sprintf("L%d uses %s", id.Pos().Line(), obj)
165 facts = append(facts, fact)
166 }
167 sort.Strings(facts)
168
169 got := strings.Join(facts, "\n")
170 if got != want {
171 t.Errorf("Unexpected defs/uses\ngot:\n%s\nwant:\n%s", got, want)
172 }
173 }
174
175
176
177
178
179
180
181 func TestIssue13898(t *testing.T) {
182 testenv.MustHaveGoBuild(t)
183
184 const src0 = `
185 package main
186
187 import "go/types"
188
189 func main() {
190 var info types.Info
191 for _, obj := range info.Uses {
192 _ = obj.Pkg()
193 }
194 }
195 `
196
197 const src1 = `
198 package main
199
200 import (
201 "go/types"
202 _ "go/importer"
203 )
204
205 func main() {
206 var info types.Info
207 for _, obj := range info.Uses {
208 _ = obj.Pkg()
209 }
210 }
211 `
212
213
214 const src2 = `
215 package main
216
217 import (
218 _ "go/importer"
219 "go/types"
220 )
221
222 func main() {
223 var info types.Info
224 for _, obj := range info.Uses {
225 _ = obj.Pkg()
226 }
227 }
228 `
229 f := func(test, src string) {
230 info := &Info{Uses: make(map[*syntax.Name]Object)}
231 mustTypecheck(src, nil, info)
232
233 var pkg *Package
234 count := 0
235 for id, obj := range info.Uses {
236 if id.Value == "Pkg" {
237 pkg = obj.Pkg()
238 count++
239 }
240 }
241 if count != 1 {
242 t.Fatalf("%s: got %d entries named Pkg; want 1", test, count)
243 }
244 if pkg.Name() != "types" {
245 t.Fatalf("%s: got %v; want package types2", test, pkg)
246 }
247 }
248
249 f("src0", src0)
250 f("src1", src1)
251 f("src2", src2)
252 }
253
254 func TestIssue22525(t *testing.T) {
255 const src = `package p; func f() { var a, b, c, d, e int }`
256
257 got := "\n"
258 conf := Config{Error: func(err error) { got += err.Error() + "\n" }}
259 typecheck(src, &conf, nil)
260 want := `
261 p:1:27: a declared and not used
262 p:1:30: b declared and not used
263 p:1:33: c declared and not used
264 p:1:36: d declared and not used
265 p:1:39: e declared and not used
266 `
267 if got != want {
268 t.Errorf("got: %swant: %s", got, want)
269 }
270 }
271
272 func TestIssue25627(t *testing.T) {
273 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
274
275
276 for _, src := range []string{
277 `struct { x Missing }`,
278 `struct { Missing }`,
279 `struct { *Missing }`,
280 `struct { unsafe.Pointer }`,
281 `struct { P }`,
282 `struct { *I }`,
283 `struct { a int; b Missing; *Missing }`,
284 } {
285 f := mustParse(prefix + src)
286
287 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
288 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
289 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
290 if err != nil {
291 if _, ok := err.(Error); !ok {
292 t.Fatal(err)
293 }
294 }
295
296 syntax.Inspect(f, func(n syntax.Node) bool {
297 if decl, _ := n.(*syntax.TypeDecl); decl != nil {
298 if tv, ok := info.Types[decl.Type]; ok && decl.Name.Value == "T" {
299 want := strings.Count(src, ";") + 1
300 if got := tv.Type.(*Struct).NumFields(); got != want {
301 t.Errorf("%s: got %d fields; want %d", src, got, want)
302 }
303 }
304 }
305 return true
306 })
307 }
308 }
309
310 func TestIssue28005(t *testing.T) {
311
312
313 sources := [...]string{
314 "package p; type A interface{ A() }",
315 "package p; type B interface{ B() }",
316 "package p; type X interface{ A; B }",
317 }
318
319
320 var orig [len(sources)]*syntax.File
321 for i, src := range sources {
322 orig[i] = mustParse(src)
323 }
324
325
326 for _, perm := range [][len(sources)]int{
327 {0, 1, 2},
328 {0, 2, 1},
329 {1, 0, 2},
330 {1, 2, 0},
331 {2, 0, 1},
332 {2, 1, 0},
333 } {
334
335 files := make([]*syntax.File, len(sources))
336 for i := range perm {
337 files[i] = orig[perm[i]]
338 }
339
340
341 var conf Config
342 info := &Info{Defs: make(map[*syntax.Name]Object)}
343 _, err := conf.Check("", files, info)
344 if err != nil {
345 t.Fatal(err)
346 }
347
348
349 var obj Object
350 for name, def := range info.Defs {
351 if name.Value == "X" {
352 obj = def
353 break
354 }
355 }
356 if obj == nil {
357 t.Fatal("object X not found")
358 }
359 iface := obj.Type().Underlying().(*Interface)
360
361
362
363 for i := 0; i < iface.NumMethods(); i++ {
364 m := iface.Method(i)
365 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
366 if recvName != m.Name() {
367 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
368 }
369 }
370 }
371 }
372
373 func TestIssue28282(t *testing.T) {
374
375 et := Universe.Lookup("error").Type()
376 it := NewInterfaceType(nil, []Type{et})
377
378
379
380 want := et.Underlying().(*Interface).Method(0)
381 got := it.Method(0)
382 if got != want {
383 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
384 }
385
386 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
387 if obj != want {
388 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
389 }
390 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
391 if obj != want {
392 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
393 }
394 }
395
396 func TestIssue29029(t *testing.T) {
397 f1 := mustParse(`package p; type A interface { M() }`)
398 f2 := mustParse(`package p; var B interface { A }`)
399
400
401 printInfo := func(info *Info) string {
402 var buf strings.Builder
403 for _, obj := range info.Defs {
404 if fn, ok := obj.(*Func); ok {
405 fmt.Fprintln(&buf, fn)
406 }
407 }
408 return buf.String()
409 }
410
411
412
413
414
415
416 var conf Config
417 info := &Info{Defs: make(map[*syntax.Name]Object)}
418 check := NewChecker(&conf, NewPackage("", "p"), info)
419 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
420 t.Fatal(err)
421 }
422 want := printInfo(info)
423
424
425 info = &Info{Defs: make(map[*syntax.Name]Object)}
426 check = NewChecker(&conf, NewPackage("", "p"), info)
427 if err := check.Files([]*syntax.File{f1}); err != nil {
428 t.Fatal(err)
429 }
430 if err := check.Files([]*syntax.File{f2}); err != nil {
431 t.Fatal(err)
432 }
433 got := printInfo(info)
434
435 if got != want {
436 t.Errorf("\ngot : %swant: %s", got, want)
437 }
438 }
439
440 func TestIssue34151(t *testing.T) {
441 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
442 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
443
444 a := mustTypecheck(asrc, nil, nil)
445
446 conf := Config{Importer: importHelper{pkg: a}}
447 mustTypecheck(bsrc, &conf, nil)
448 }
449
450 type importHelper struct {
451 pkg *Package
452 fallback Importer
453 }
454
455 func (h importHelper) Import(path string) (*Package, error) {
456 if path == h.pkg.Path() {
457 return h.pkg, nil
458 }
459 if h.fallback == nil {
460 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
461 }
462 return h.fallback.Import(path)
463 }
464
465
466
467
468
469
470
471 func TestIssue34921(t *testing.T) {
472 defer func() {
473 if r := recover(); r != nil {
474 t.Error(r)
475 }
476 }()
477
478 var sources = []string{
479 `package a; type T int`,
480 `package b; import "a"; type T a.T`,
481 }
482
483 var pkg *Package
484 for _, src := range sources {
485 conf := Config{Importer: importHelper{pkg: pkg}}
486 pkg = mustTypecheck(src, &conf, nil)
487 }
488 }
489
490 func TestIssue43088(t *testing.T) {
491
492
493
494
495
496
497
498
499
500 n1 := NewTypeName(nopos, nil, "T1", nil)
501 T1 := NewNamed(n1, nil, nil)
502 n2 := NewTypeName(nopos, nil, "T2", nil)
503 T2 := NewNamed(n2, nil, nil)
504 s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
505 T1.SetUnderlying(s1)
506 s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
507 s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
508 T2.SetUnderlying(s3)
509
510
511 Comparable(T1)
512 Comparable(T2)
513 }
514
515 func TestIssue44515(t *testing.T) {
516 typ := Unsafe.Scope().Lookup("Pointer").Type()
517
518 got := TypeString(typ, nil)
519 want := "unsafe.Pointer"
520 if got != want {
521 t.Errorf("got %q; want %q", got, want)
522 }
523
524 qf := func(pkg *Package) string {
525 if pkg == Unsafe {
526 return "foo"
527 }
528 return ""
529 }
530 got = TypeString(typ, qf)
531 want = "foo.Pointer"
532 if got != want {
533 t.Errorf("got %q; want %q", got, want)
534 }
535 }
536
537 func TestIssue43124(t *testing.T) {
538
539
540 testenv.MustHaveGoBuild(t)
541
542
543
544
545 const (
546 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
547 bsrc = `
548 package b
549
550 import (
551 "a"
552 "html/template"
553 )
554
555 func _() {
556 // Packages should be fully qualified when there is ambiguity within the
557 // error string itself.
558 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
559 }
560 `
561 csrc = `
562 package c
563
564 import (
565 "a"
566 "fmt"
567 "html/template"
568 )
569
570 // go.dev/issue/46905: make sure template is not the first package qualified.
571 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
572
573 // Packages should be fully qualified when there is ambiguity in reachable
574 // packages. In this case both a (and for that matter html/template) import
575 // text/template.
576 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
577 `
578
579 tsrc = `
580 package template
581
582 import "text/template"
583
584 type T int
585
586 // Verify that the current package name also causes disambiguation.
587 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
588 `
589 )
590
591 a := mustTypecheck(asrc, nil, nil)
592 imp := importHelper{pkg: a, fallback: defaultImporter()}
593
594 withImporter := func(cfg *Config) {
595 cfg.Importer = imp
596 }
597
598 testFiles(t, []string{"b.go"}, [][]byte{[]byte(bsrc)}, 0, false, withImporter)
599 testFiles(t, []string{"c.go"}, [][]byte{[]byte(csrc)}, 0, false, withImporter)
600 testFiles(t, []string{"t.go"}, [][]byte{[]byte(tsrc)}, 0, false, withImporter)
601 }
602
603 func TestIssue50646(t *testing.T) {
604 anyType := Universe.Lookup("any").Type()
605 comparableType := Universe.Lookup("comparable").Type()
606
607 if !Comparable(anyType) {
608 t.Error("any is not a comparable type")
609 }
610 if !Comparable(comparableType) {
611 t.Error("comparable is not a comparable type")
612 }
613
614 if Implements(anyType, comparableType.Underlying().(*Interface)) {
615 t.Error("any implements comparable")
616 }
617 if !Implements(comparableType, anyType.(*Interface)) {
618 t.Error("comparable does not implement any")
619 }
620
621 if AssignableTo(anyType, comparableType) {
622 t.Error("any assignable to comparable")
623 }
624 if !AssignableTo(comparableType, anyType) {
625 t.Error("comparable not assignable to any")
626 }
627 }
628
629 func TestIssue55030(t *testing.T) {
630
631 makeSig := func(typ Type) {
632 par := NewVar(nopos, nil, "", typ)
633 params := NewTuple(par)
634 NewSignatureType(nil, nil, nil, params, nil, true)
635 }
636
637
638
639 makeSig(NewSlice(Typ[Int]))
640
641
642 makeSig(Typ[String])
643
644
645 {
646 P := NewTypeName(nopos, nil, "P", nil)
647 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})))
648 }
649
650
651 {
652 P := NewTypeName(nopos, nil, "P", nil)
653 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})))
654 }
655
656
657 {
658 t1 := NewTerm(true, Typ[String])
659 t2 := NewTerm(false, NewSlice(Typ[Byte]))
660 u := NewUnion([]*Term{t1, t2})
661 P := NewTypeName(nopos, nil, "P", nil)
662 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})))
663 }
664 }
665
666 func TestIssue51093(t *testing.T) {
667
668
669
670
671 var tests = []struct {
672 typ string
673 val string
674 }{
675 {"bool", "false"},
676 {"int", "-1"},
677 {"uint", "1.0"},
678 {"rune", "'a'"},
679 {"float64", "3.5"},
680 {"complex64", "1.25"},
681 {"string", "\"foo\""},
682
683
684 {"~byte", "1"},
685 {"~int | ~float64 | complex128", "1"},
686 {"~uint64 | ~rune", "'X'"},
687 }
688
689 for _, test := range tests {
690 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
691 types := make(map[syntax.Expr]TypeAndValue)
692 mustTypecheck(src, nil, &Info{Types: types})
693
694 var n int
695 for x, tv := range types {
696 if x, _ := x.(*syntax.CallExpr); x != nil {
697
698 n++
699 tpar, _ := tv.Type.(*TypeParam)
700 if tpar == nil {
701 t.Fatalf("%s: got type %s, want type parameter", syntax.String(x), tv.Type)
702 }
703 if name := tpar.Obj().Name(); name != "P" {
704 t.Fatalf("%s: got type parameter name %s, want P", syntax.String(x), name)
705 }
706
707 if tv.Value != nil {
708 t.Errorf("%s: got constant value %s (%s), want no constant", syntax.String(x), tv.Value, tv.Value.String())
709 }
710 }
711 }
712
713 if n != 1 {
714 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
715 }
716 }
717 }
718
719 func TestIssue54258(t *testing.T) {
720 tests := []struct{ main, b, want string }{
721 {
722 `package main
723 import "b"
724 type I0 interface {
725 M0(w struct{ f string })
726 }
727 var _ I0 = b.S{}
728 `,
729 `package b
730 type S struct{}
731 func (S) M0(struct{ f string }) {}
732 `,
733 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I0 value in variable declaration: b[.]S does not implement I0 [(]wrong type for method M0[)]
734 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
735 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
736
737 {
738 `package main
739 import "b"
740 type I1 interface {
741 M1(struct{ string })
742 }
743 var _ I1 = b.S{}
744 `,
745 `package b
746 type S struct{}
747 func (S) M1(struct{ string }) {}
748 `,
749 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I1 value in variable declaration: b[.]S does not implement I1 [(]wrong type for method M1[)]
750 .*have M1[(]struct{string /[*] package b [*]/ }[)]
751 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
752
753 {
754 `package main
755 import "b"
756 type I2 interface {
757 M2(y struct{ f struct{ f string } })
758 }
759 var _ I2 = b.S{}
760 `,
761 `package b
762 type S struct{}
763 func (S) M2(struct{ f struct{ f string } }) {}
764 `,
765 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I2 value in variable declaration: b[.]S does not implement I2 [(]wrong type for method M2[)]
766 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
767 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
768
769 {
770 `package main
771 import "b"
772 type I3 interface {
773 M3(z struct{ F struct{ f string } })
774 }
775 var _ I3 = b.S{}
776 `,
777 `package b
778 type S struct{}
779 func (S) M3(struct{ F struct{ f string } }) {}
780 `,
781 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I3 value in variable declaration: b[.]S does not implement I3 [(]wrong type for method M3[)]
782 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
783 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
784
785 {
786 `package main
787 import "b"
788 type I4 interface {
789 M4(_ struct { *string })
790 }
791 var _ I4 = b.S{}
792 `,
793 `package b
794 type S struct{}
795 func (S) M4(struct { *string }) {}
796 `,
797 `6:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I4 value in variable declaration: b[.]S does not implement I4 [(]wrong type for method M4[)]
798 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
799 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
800
801 {
802 `package main
803 import "b"
804 type t struct{ A int }
805 type I5 interface {
806 M5(_ struct {b.S;t})
807 }
808 var _ I5 = b.S{}
809 `,
810 `package b
811 type S struct{}
812 type t struct{ A int }
813 func (S) M5(struct {S;t}) {}
814 `,
815 `7:12: cannot use b[.]S{} [(]value of type b[.]S[)] as I5 value in variable declaration: b[.]S does not implement I5 [(]wrong type for method M5[)]
816 .*have M5[(]struct{b[.]S; b[.]t}[)]
817 .*want M5[(]struct{b[.]S; t}[)]`},
818 }
819
820 test := func(main, b, want string) {
821 re := regexp.MustCompile(want)
822 bpkg := mustTypecheck(b, nil, nil)
823 mast := mustParse(main)
824 conf := Config{Importer: importHelper{pkg: bpkg}}
825 _, err := conf.Check(mast.PkgName.Value, []*syntax.File{mast}, nil)
826 if err == nil {
827 t.Error("Expected failure, but it did not")
828 } else if got := err.Error(); !re.MatchString(got) {
829 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
830 } else if testing.Verbose() {
831 t.Logf("Saw expected\n\t%s", err.Error())
832 }
833 }
834 for _, t := range tests {
835 test(t.main, t.b, t.want)
836 }
837 }
838
839 func TestIssue59944(t *testing.T) {
840 testenv.MustHaveCGO(t)
841
842
843 const src = `
844 package p
845
846 /*
847 struct layout {
848 int field;
849 };
850 */
851 import "C"
852
853 type Layout = C.struct_layout
854
855 func (l *Layout) Binding() {}
856
857 func _() {
858 _ = (*Layout).Binding
859 }
860 `
861
862
863 const cgoTypes = `
864 // Code generated by cmd/cgo; DO NOT EDIT.
865
866 package p
867
868 import "unsafe"
869
870 import "syscall"
871
872 import _cgopackage "runtime/cgo"
873
874 type _ _cgopackage.Incomplete
875 var _ syscall.Errno
876 func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
877
878 //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
879 var _Cgo_always_false bool
880 //go:linkname _Cgo_use runtime.cgoUse
881 func _Cgo_use(interface{})
882 type _Ctype_int int32
883
884 type _Ctype_struct_layout struct {
885 field _Ctype_int
886 }
887
888 type _Ctype_void [0]byte
889
890 //go:linkname _cgo_runtime_cgocall runtime.cgocall
891 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
892
893 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
894 func _cgoCheckPointer(interface{}, interface{})
895
896 //go:linkname _cgoCheckResult runtime.cgoCheckResult
897 func _cgoCheckResult(interface{})
898 `
899 testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, 0, false, func(cfg *Config) {
900 *boolFieldAddr(cfg, "go115UsesCgo") = true
901 })
902 }
903
904 func TestIssue61931(t *testing.T) {
905 const src = `
906 package p
907
908 func A(func(any), ...any) {}
909 func B[T any](T) {}
910
911 func _() {
912 A(B, nil // syntax error: missing ',' before newline in argument list
913 }
914 `
915 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), func(error) {}, nil, 0)
916 if err == nil {
917 t.Fatal("expected syntax error")
918 }
919
920 var conf Config
921 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
922 }
923
924 func TestIssue61938(t *testing.T) {
925 const src = `
926 package p
927
928 func f[T any]() {}
929 func _() { f() }
930 `
931
932 var conf Config
933 typecheck(src, &conf, nil)
934
935
936 conf.Error = func(error) {}
937 typecheck(src, &conf, nil)
938 }
939
940 func TestIssue63260(t *testing.T) {
941 const src = `
942 package p
943
944 func _() {
945 use(f[*string])
946 }
947
948 func use(func()) {}
949
950 func f[I *T, T any]() {
951 var v T
952 _ = v
953 }`
954
955 info := Info{
956 Defs: make(map[*syntax.Name]Object),
957 }
958 pkg := mustTypecheck(src, nil, &info)
959
960
961 T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
962 if T.Obj().Name() != "T" {
963 t.Fatalf("got type parameter %s, want T", T)
964 }
965
966
967 var v Object
968 for name, obj := range info.Defs {
969 if name.Value == "v" {
970 v = obj
971 break
972 }
973 }
974 if v == nil {
975 t.Fatal("variable v not found")
976 }
977
978
979 if v.Type() != T {
980 t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)
981 }
982 }
983
984 func TestIssue44410(t *testing.T) {
985 const src = `
986 package p
987
988 type A = []int
989 type S struct{ A }
990 `
991
992 t.Setenv("GODEBUG", "gotypesalias=1")
993 pkg := mustTypecheck(src, nil, nil)
994
995 S := pkg.Scope().Lookup("S")
996 if S == nil {
997 t.Fatal("object S not found")
998 }
999
1000 got := S.String()
1001 const want = "type p.S struct{p.A}"
1002 if got != want {
1003 t.Fatalf("got %q; want %q", got, want)
1004 }
1005 }
1006
1007 func TestIssue59831(t *testing.T) {
1008
1009
1010 const asrc = `package a; type S struct{}; func (S) m() {}`
1011 apkg := mustTypecheck(asrc, nil, nil)
1012
1013
1014
1015 const bsrc = `package b; type S struct{}; func (S) M() {}`
1016 bpkg := mustTypecheck(bsrc, nil, nil)
1017
1018 tests := []struct {
1019 imported *Package
1020 src, err string
1021 }{
1022
1023 {apkg, `package a1; import "a"; var _ interface { M() } = a.S{}`,
1024 "a.S does not implement interface{M()} (missing method M) have m() want M()"},
1025
1026 {apkg, `package a2; import "a"; var _ interface { m() } = a.S{}`,
1027 "a.S does not implement interface{m()} (unexported method m)"},
1028
1029 {nil, `package a3; type S struct{}; func (S) m(); var _ interface { M() } = S{}`,
1030 "S does not implement interface{M()} (missing method M) have m() want M()"},
1031
1032 {nil, `package a4; type S struct{}; func (S) m(); var _ interface { m() } = S{}`,
1033 ""},
1034
1035 {nil, `package a5; type S struct{}; func (S) m(); var _ interface { n() } = S{}`,
1036 "S does not implement interface{n()} (missing method n)"},
1037
1038
1039 {bpkg, `package b1; import "b"; var _ interface { m() } = b.S{}`,
1040 "b.S does not implement interface{m()} (missing method m) have M() want m()"},
1041
1042 {bpkg, `package b2; import "b"; var _ interface { M() } = b.S{}`,
1043 ""},
1044
1045 {nil, `package b3; type S struct{}; func (S) M(); var _ interface { M() } = S{}`,
1046 ""},
1047
1048 {nil, `package b4; type S struct{}; func (S) M(); var _ interface { m() } = S{}`,
1049 "S does not implement interface{m()} (missing method m) have M() want m()"},
1050
1051 {nil, `package b5; type S struct{}; func (S) M(); var _ interface { n() } = S{}`,
1052 "S does not implement interface{n()} (missing method n)"},
1053 }
1054
1055 for _, test := range tests {
1056
1057 conf := Config{Importer: importHelper{pkg: test.imported}}
1058 pkg, err := typecheck(test.src, &conf, nil)
1059 if err == nil {
1060 if test.err != "" {
1061 t.Errorf("package %s: got no error, want %q", pkg.Name(), test.err)
1062 }
1063 continue
1064 }
1065 if test.err == "" {
1066 t.Errorf("package %s: got %q, want not error", pkg.Name(), err.Error())
1067 }
1068
1069
1070 errmsg := strings.ReplaceAll(err.Error(), "\n", " ")
1071 errmsg = strings.ReplaceAll(errmsg, "\t", "")
1072
1073
1074 if !strings.Contains(errmsg, test.err) {
1075 t.Errorf("package %s: got %q, want %q", pkg.Name(), errmsg, test.err)
1076 }
1077 }
1078 }
1079
1080 func TestIssue64759(t *testing.T) {
1081 const src = `
1082 //go:build go1.18
1083 package p
1084
1085 func f[S ~[]E, E any](S) {}
1086
1087 func _() {
1088 f([]string{})
1089 }
1090 `
1091
1092
1093 conf := Config{GoVersion: "go1.17"}
1094 mustTypecheck(src, &conf, nil)
1095 }
1096
View as plain text