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 "slices"
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 slices.Sort(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 := "\n" +
261 "p:1:27: declared and not used: a\n" +
262 "p:1:30: declared and not used: b\n" +
263 "p:1:33: declared and not used: c\n" +
264 "p:1:36: declared and not used: d\n" +
265 "p:1:39: declared and not used: e\n"
266 if got != want {
267 t.Errorf("got: %swant: %s", got, want)
268 }
269 }
270
271 func TestIssue25627(t *testing.T) {
272 const prefix = `package p; import "unsafe"; type P *struct{}; type I interface{}; type T `
273
274
275 for _, src := range []string{
276 `struct { x Missing }`,
277 `struct { Missing }`,
278 `struct { *Missing }`,
279 `struct { unsafe.Pointer }`,
280 `struct { P }`,
281 `struct { *I }`,
282 `struct { a int; b Missing; *Missing }`,
283 } {
284 f := mustParse(prefix + src)
285
286 conf := Config{Importer: defaultImporter(), Error: func(err error) {}}
287 info := &Info{Types: make(map[syntax.Expr]TypeAndValue)}
288 _, err := conf.Check(f.PkgName.Value, []*syntax.File{f}, info)
289 if err != nil {
290 if _, ok := err.(Error); !ok {
291 t.Fatal(err)
292 }
293 }
294
295 syntax.Inspect(f, func(n syntax.Node) bool {
296 if decl, _ := n.(*syntax.TypeDecl); decl != nil {
297 if tv, ok := info.Types[decl.Type]; ok && decl.Name.Value == "T" {
298 want := strings.Count(src, ";") + 1
299 if got := tv.Type.(*Struct).NumFields(); got != want {
300 t.Errorf("%s: got %d fields; want %d", src, got, want)
301 }
302 }
303 }
304 return true
305 })
306 }
307 }
308
309 func TestIssue28005(t *testing.T) {
310
311
312 sources := [...]string{
313 "package p; type A interface{ A() }",
314 "package p; type B interface{ B() }",
315 "package p; type X interface{ A; B }",
316 }
317
318
319 var orig [len(sources)]*syntax.File
320 for i, src := range sources {
321 orig[i] = mustParse(src)
322 }
323
324
325 for _, perm := range [][len(sources)]int{
326 {0, 1, 2},
327 {0, 2, 1},
328 {1, 0, 2},
329 {1, 2, 0},
330 {2, 0, 1},
331 {2, 1, 0},
332 } {
333
334 files := make([]*syntax.File, len(sources))
335 for i := range perm {
336 files[i] = orig[perm[i]]
337 }
338
339
340 var conf Config
341 info := &Info{Defs: make(map[*syntax.Name]Object)}
342 _, err := conf.Check("", files, info)
343 if err != nil {
344 t.Fatal(err)
345 }
346
347
348 var obj Object
349 for name, def := range info.Defs {
350 if name.Value == "X" {
351 obj = def
352 break
353 }
354 }
355 if obj == nil {
356 t.Fatal("object X not found")
357 }
358 iface := obj.Type().Underlying().(*Interface)
359
360
361
362 for i := 0; i < iface.NumMethods(); i++ {
363 m := iface.Method(i)
364 recvName := m.Type().(*Signature).Recv().Type().(*Named).Obj().Name()
365 if recvName != m.Name() {
366 t.Errorf("perm %v: got recv %s; want %s", perm, recvName, m.Name())
367 }
368 }
369 }
370 }
371
372 func TestIssue28282(t *testing.T) {
373
374 et := Universe.Lookup("error").Type()
375 it := NewInterfaceType(nil, []Type{et})
376
377
378
379 want := et.Underlying().(*Interface).Method(0)
380 got := it.Method(0)
381 if got != want {
382 t.Fatalf("%s.Method(0): got %q (%p); want %q (%p)", it, got, got, want, want)
383 }
384
385 obj, _, _ := LookupFieldOrMethod(et, false, nil, "Error")
386 if obj != want {
387 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", et, obj, obj, want, want)
388 }
389 obj, _, _ = LookupFieldOrMethod(it, false, nil, "Error")
390 if obj != want {
391 t.Fatalf("%s.Lookup: got %q (%p); want %q (%p)", it, obj, obj, want, want)
392 }
393 }
394
395 func TestIssue29029(t *testing.T) {
396 f1 := mustParse(`package p; type A interface { M() }`)
397 f2 := mustParse(`package p; var B interface { A }`)
398
399
400 printInfo := func(info *Info) string {
401 var buf strings.Builder
402 for _, obj := range info.Defs {
403 if fn, ok := obj.(*Func); ok {
404 fmt.Fprintln(&buf, fn)
405 }
406 }
407 return buf.String()
408 }
409
410
411
412
413
414
415 var conf Config
416 info := &Info{Defs: make(map[*syntax.Name]Object)}
417 check := NewChecker(&conf, NewPackage("", "p"), info)
418 if err := check.Files([]*syntax.File{f1, f2}); err != nil {
419 t.Fatal(err)
420 }
421 want := printInfo(info)
422
423
424 info = &Info{Defs: make(map[*syntax.Name]Object)}
425 check = NewChecker(&conf, NewPackage("", "p"), info)
426 if err := check.Files([]*syntax.File{f1}); err != nil {
427 t.Fatal(err)
428 }
429 if err := check.Files([]*syntax.File{f2}); err != nil {
430 t.Fatal(err)
431 }
432 got := printInfo(info)
433
434 if got != want {
435 t.Errorf("\ngot : %swant: %s", got, want)
436 }
437 }
438
439 func TestIssue34151(t *testing.T) {
440 const asrc = `package a; type I interface{ M() }; type T struct { F interface { I } }`
441 const bsrc = `package b; import "a"; type T struct { F interface { a.I } }; var _ = a.T(T{})`
442
443 a := mustTypecheck(asrc, nil, nil)
444
445 conf := Config{Importer: importHelper{pkg: a}}
446 mustTypecheck(bsrc, &conf, nil)
447 }
448
449 type importHelper struct {
450 pkg *Package
451 fallback Importer
452 }
453
454 func (h importHelper) Import(path string) (*Package, error) {
455 if path == h.pkg.Path() {
456 return h.pkg, nil
457 }
458 if h.fallback == nil {
459 return nil, fmt.Errorf("got package path %q; want %q", path, h.pkg.Path())
460 }
461 return h.fallback.Import(path)
462 }
463
464
465
466
467
468
469
470 func TestIssue34921(t *testing.T) {
471 defer func() {
472 if r := recover(); r != nil {
473 t.Error(r)
474 }
475 }()
476
477 var sources = []string{
478 `package a; type T int`,
479 `package b; import "a"; type T a.T`,
480 }
481
482 var pkg *Package
483 for _, src := range sources {
484 conf := Config{Importer: importHelper{pkg: pkg}}
485 pkg = mustTypecheck(src, &conf, nil)
486 }
487 }
488
489 func TestIssue43088(t *testing.T) {
490
491
492
493
494
495
496
497
498
499 n1 := NewTypeName(nopos, nil, "T1", nil)
500 T1 := NewNamed(n1, nil, nil)
501 n2 := NewTypeName(nopos, nil, "T2", nil)
502 T2 := NewNamed(n2, nil, nil)
503 s1 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
504 T1.SetUnderlying(s1)
505 s2 := NewStruct([]*Var{NewField(nopos, nil, "_", T2, false)}, nil)
506 s3 := NewStruct([]*Var{NewField(nopos, nil, "_", s2, false)}, nil)
507 T2.SetUnderlying(s3)
508
509
510 Comparable(T1)
511 Comparable(T2)
512 }
513
514 func TestIssue44515(t *testing.T) {
515 typ := Unsafe.Scope().Lookup("Pointer").Type()
516
517 got := TypeString(typ, nil)
518 want := "unsafe.Pointer"
519 if got != want {
520 t.Errorf("got %q; want %q", got, want)
521 }
522
523 qf := func(pkg *Package) string {
524 if pkg == Unsafe {
525 return "foo"
526 }
527 return ""
528 }
529 got = TypeString(typ, qf)
530 want = "foo.Pointer"
531 if got != want {
532 t.Errorf("got %q; want %q", got, want)
533 }
534 }
535
536 func TestIssue43124(t *testing.T) {
537
538
539 testenv.MustHaveGoBuild(t)
540
541
542
543
544 const (
545 asrc = `package a; import "text/template"; func F(template.Template) {}; func G(int) {}`
546 bsrc = `
547 package b
548
549 import (
550 "a"
551 "html/template"
552 )
553
554 func _() {
555 // Packages should be fully qualified when there is ambiguity within the
556 // error string itself.
557 a.F(template /* ERRORx "cannot use.*html/template.* as .*text/template" */ .Template{})
558 }
559 `
560 csrc = `
561 package c
562
563 import (
564 "a"
565 "fmt"
566 "html/template"
567 )
568
569 // go.dev/issue/46905: make sure template is not the first package qualified.
570 var _ fmt.Stringer = 1 // ERRORx "cannot use 1.*as fmt\\.Stringer"
571
572 // Packages should be fully qualified when there is ambiguity in reachable
573 // packages. In this case both a (and for that matter html/template) import
574 // text/template.
575 func _() { a.G(template /* ERRORx "cannot use .*html/template.*Template" */ .Template{}) }
576 `
577
578 tsrc = `
579 package template
580
581 import "text/template"
582
583 type T int
584
585 // Verify that the current package name also causes disambiguation.
586 var _ T = template /* ERRORx "cannot use.*text/template.* as T value" */.Template{}
587 `
588 )
589
590 a := mustTypecheck(asrc, nil, nil)
591 imp := importHelper{pkg: a, fallback: defaultImporter()}
592
593 withImporter := func(cfg *Config) {
594 cfg.Importer = imp
595 }
596
597 testFiles(t, []string{"b.go"}, [][]byte{[]byte(bsrc)}, 0, false, withImporter)
598 testFiles(t, []string{"c.go"}, [][]byte{[]byte(csrc)}, 0, false, withImporter)
599 testFiles(t, []string{"t.go"}, [][]byte{[]byte(tsrc)}, 0, false, withImporter)
600 }
601
602 func TestIssue50646(t *testing.T) {
603 anyType := Universe.Lookup("any").Type().Underlying()
604 comparableType := Universe.Lookup("comparable").Type()
605
606 if !Comparable(anyType) {
607 t.Error("any is not a comparable type")
608 }
609 if !Comparable(comparableType) {
610 t.Error("comparable is not a comparable type")
611 }
612
613 if Implements(anyType, comparableType.Underlying().(*Interface)) {
614 t.Error("any implements comparable")
615 }
616 if !Implements(comparableType, anyType.(*Interface)) {
617 t.Error("comparable does not implement any")
618 }
619
620 if AssignableTo(anyType, comparableType) {
621 t.Error("any assignable to comparable")
622 }
623 if !AssignableTo(comparableType, anyType) {
624 t.Error("comparable not assignable to any")
625 }
626 }
627
628 func TestIssue55030(t *testing.T) {
629
630
631 makeSig := func(typ Type, valid bool) {
632 if !valid {
633 defer func() {
634 r := recover()
635 if r == nil {
636 panic("NewSignatureType panic expected")
637 }
638 if _, ok := r.(string); !ok {
639 panic("NewSignatureType string panic expected")
640 }
641 }()
642 }
643 par := NewParam(nopos, nil, "", typ)
644 params := NewTuple(par)
645 NewSignatureType(nil, nil, nil, params, nil, true)
646 }
647
648
649
650 makeSig(NewSlice(Typ[Int]), true)
651
652
653 makeSig(Typ[String], true)
654
655
656 {
657 P := NewTypeName(nopos, nil, "P", nil)
658 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})), true)
659 }
660
661
662 {
663 P := NewTypeName(nopos, nil, "P", nil)
664 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})), true)
665 }
666
667
668 {
669 t1 := NewTerm(true, Typ[String])
670 t2 := NewTerm(false, NewSlice(Typ[Byte]))
671 u := NewUnion([]*Term{t1, t2})
672 P := NewTypeName(nopos, nil, "P", nil)
673 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})), true)
674 }
675
676
677
678 makeSig(Typ[Int], false)
679
680
681 {
682 P := NewTypeName(nopos, nil, "P", nil)
683 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Universe.Lookup("any").Type()})), false)
684 }
685
686
687 {
688 P := NewTypeName(nopos, nil, "P", nil)
689 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[Int]})), false)
690 }
691 }
692
693 func TestIssue51093(t *testing.T) {
694
695
696
697
698 var tests = []struct {
699 typ string
700 val string
701 }{
702 {"bool", "false"},
703 {"int", "-1"},
704 {"uint", "1.0"},
705 {"rune", "'a'"},
706 {"float64", "3.5"},
707 {"complex64", "1.25"},
708 {"string", "\"foo\""},
709
710
711 {"~byte", "1"},
712 {"~int | ~float64 | complex128", "1"},
713 {"~uint64 | ~rune", "'X'"},
714 }
715
716 for _, test := range tests {
717 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
718 types := make(map[syntax.Expr]TypeAndValue)
719 mustTypecheck(src, nil, &Info{Types: types})
720
721 var n int
722 for x, tv := range types {
723 if x, _ := x.(*syntax.CallExpr); x != nil {
724
725 n++
726 tpar, _ := tv.Type.(*TypeParam)
727 if tpar == nil {
728 t.Fatalf("%s: got type %s, want type parameter", ExprString(x), tv.Type)
729 }
730 if name := tpar.Obj().Name(); name != "P" {
731 t.Fatalf("%s: got type parameter name %s, want P", ExprString(x), name)
732 }
733
734 if tv.Value != nil {
735 t.Errorf("%s: got constant value %s (%s), want no constant", ExprString(x), tv.Value, tv.Value.String())
736 }
737 }
738 }
739
740 if n != 1 {
741 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
742 }
743 }
744 }
745
746 func TestIssue54258(t *testing.T) {
747 tests := []struct{ main, b, want string }{
748 {
749 `package main
750 import "b"
751 type I0 interface {
752 M0(w struct{ f string })
753 }
754 var _ I0 = b.S{}
755 `,
756 `package b
757 type S struct{}
758 func (S) M0(struct{ f string }) {}
759 `,
760 `6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I0 value in variable declaration: b[.]S does not implement I0 [(]wrong type for method M0[)]
761 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
762 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
763
764 {
765 `package main
766 import "b"
767 type I1 interface {
768 M1(struct{ string })
769 }
770 var _ I1 = b.S{}
771 `,
772 `package b
773 type S struct{}
774 func (S) M1(struct{ string }) {}
775 `,
776 `6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I1 value in variable declaration: b[.]S does not implement I1 [(]wrong type for method M1[)]
777 .*have M1[(]struct{string /[*] package b [*]/ }[)]
778 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
779
780 {
781 `package main
782 import "b"
783 type I2 interface {
784 M2(y struct{ f struct{ f string } })
785 }
786 var _ I2 = b.S{}
787 `,
788 `package b
789 type S struct{}
790 func (S) M2(struct{ f struct{ f string } }) {}
791 `,
792 `6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I2 value in variable declaration: b[.]S does not implement I2 [(]wrong type for method M2[)]
793 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
794 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
795
796 {
797 `package main
798 import "b"
799 type I3 interface {
800 M3(z struct{ F struct{ f string } })
801 }
802 var _ I3 = b.S{}
803 `,
804 `package b
805 type S struct{}
806 func (S) M3(struct{ F struct{ f string } }) {}
807 `,
808 `6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I3 value in variable declaration: b[.]S does not implement I3 [(]wrong type for method M3[)]
809 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
810 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
811
812 {
813 `package main
814 import "b"
815 type I4 interface {
816 M4(_ struct { *string })
817 }
818 var _ I4 = b.S{}
819 `,
820 `package b
821 type S struct{}
822 func (S) M4(struct { *string }) {}
823 `,
824 `6:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I4 value in variable declaration: b[.]S does not implement I4 [(]wrong type for method M4[)]
825 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
826 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
827
828 {
829 `package main
830 import "b"
831 type t struct{ A int }
832 type I5 interface {
833 M5(_ struct {b.S;t})
834 }
835 var _ I5 = b.S{}
836 `,
837 `package b
838 type S struct{}
839 type t struct{ A int }
840 func (S) M5(struct {S;t}) {}
841 `,
842 `7:12: cannot use b[.]S{} [(]value of struct type b[.]S[)] as I5 value in variable declaration: b[.]S does not implement I5 [(]wrong type for method M5[)]
843 .*have M5[(]struct{b[.]S; b[.]t}[)]
844 .*want M5[(]struct{b[.]S; t}[)]`},
845 }
846
847 test := func(main, b, want string) {
848 re := regexp.MustCompile(want)
849 bpkg := mustTypecheck(b, nil, nil)
850 mast := mustParse(main)
851 conf := Config{Importer: importHelper{pkg: bpkg}}
852 _, err := conf.Check(mast.PkgName.Value, []*syntax.File{mast}, nil)
853 if err == nil {
854 t.Error("Expected failure, but it did not")
855 } else if got := err.Error(); !re.MatchString(got) {
856 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
857 } else if testing.Verbose() {
858 t.Logf("Saw expected\n\t%s", err.Error())
859 }
860 }
861 for _, t := range tests {
862 test(t.main, t.b, t.want)
863 }
864 }
865
866 func TestIssue59944(t *testing.T) {
867 testenv.MustHaveCGO(t)
868
869
870 const src = `
871 package p
872
873 /*
874 struct layout {};
875 */
876 import "C"
877
878 type Layout = C.struct_layout
879
880 func (*Layout /* ERROR "cannot define new methods on non-local type Layout" */) Binding() {}
881 `
882
883
884 const cgoTypes = `
885 // Code generated by cmd/cgo; DO NOT EDIT.
886
887 package p
888
889 import "unsafe"
890
891 import "syscall"
892
893 import _cgopackage "runtime/cgo"
894
895 type _ _cgopackage.Incomplete
896 var _ syscall.Errno
897 func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
898
899 //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
900 var _Cgo_always_false bool
901 //go:linkname _Cgo_use runtime.cgoUse
902 func _Cgo_use(interface{})
903 //go:linkname _Cgo_keepalive runtime.cgoKeepAlive
904 //go:noescape
905 func _Cgo_keepalive(interface{})
906 //go:linkname _Cgo_no_callback runtime.cgoNoCallback
907 func _Cgo_no_callback(bool)
908 type _Ctype_struct_layout struct {
909 }
910
911 type _Ctype_void [0]byte
912
913 //go:linkname _cgo_runtime_cgocall runtime.cgocall
914 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
915
916 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
917 //go:noescape
918 func _cgoCheckPointer(interface{}, interface{})
919
920 //go:linkname _cgoCheckResult runtime.cgoCheckResult
921 //go:noescape
922 func _cgoCheckResult(interface{})
923 `
924 testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, 0, false, func(cfg *Config) {
925 *boolFieldAddr(cfg, "go115UsesCgo") = true
926 })
927 }
928
929 func TestIssue61931(t *testing.T) {
930 const src = `
931 package p
932
933 func A(func(any), ...any) {}
934 func B[T any](T) {}
935
936 func _() {
937 A(B, nil // syntax error: missing ',' before newline in argument list
938 }
939 `
940 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), func(error) {}, nil, 0)
941 if err == nil {
942 t.Fatal("expected syntax error")
943 }
944
945 var conf Config
946 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
947 }
948
949 func TestIssue61938(t *testing.T) {
950 const src = `
951 package p
952
953 func f[T any]() {}
954 func _() { f() }
955 `
956
957 var conf Config
958 typecheck(src, &conf, nil)
959
960
961 conf.Error = func(error) {}
962 typecheck(src, &conf, nil)
963 }
964
965 func TestIssue63260(t *testing.T) {
966 const src = `
967 package p
968
969 func _() {
970 use(f[*string])
971 }
972
973 func use(func()) {}
974
975 func f[I *T, T any]() {
976 var v T
977 _ = v
978 }`
979
980 info := Info{
981 Defs: make(map[*syntax.Name]Object),
982 }
983 pkg := mustTypecheck(src, nil, &info)
984
985
986 T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
987 if T.Obj().Name() != "T" {
988 t.Fatalf("got type parameter %s, want T", T)
989 }
990
991
992 var v Object
993 for name, obj := range info.Defs {
994 if name.Value == "v" {
995 v = obj
996 break
997 }
998 }
999 if v == nil {
1000 t.Fatal("variable v not found")
1001 }
1002
1003
1004 if v.Type() != T {
1005 t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)
1006 }
1007 }
1008
1009 func TestIssue44410(t *testing.T) {
1010 const src = `
1011 package p
1012
1013 type A = []int
1014 type S struct{ A }
1015 `
1016
1017 pkg := mustTypecheck(src, nil, nil)
1018
1019 S := pkg.Scope().Lookup("S")
1020 if S == nil {
1021 t.Fatal("object S not found")
1022 }
1023
1024 got := S.String()
1025 const want = "type p.S struct{p.A}"
1026 if got != want {
1027 t.Fatalf("got %q; want %q", got, want)
1028 }
1029 }
1030
1031 func TestIssue59831(t *testing.T) {
1032
1033
1034 const asrc = `package a; type S struct{}; func (S) m() {}`
1035 apkg := mustTypecheck(asrc, nil, nil)
1036
1037
1038
1039 const bsrc = `package b; type S struct{}; func (S) M() {}`
1040 bpkg := mustTypecheck(bsrc, nil, nil)
1041
1042 tests := []struct {
1043 imported *Package
1044 src, err string
1045 }{
1046
1047 {apkg, `package a1; import "a"; var _ interface { M() } = a.S{}`,
1048 "a.S does not implement interface{M()} (missing method M) have m() want M()"},
1049
1050 {apkg, `package a2; import "a"; var _ interface { m() } = a.S{}`,
1051 "a.S does not implement interface{m()} (unexported method m)"},
1052
1053 {nil, `package a3; type S struct{}; func (S) m(); var _ interface { M() } = S{}`,
1054 "S does not implement interface{M()} (missing method M) have m() want M()"},
1055
1056 {nil, `package a4; type S struct{}; func (S) m(); var _ interface { m() } = S{}`,
1057 ""},
1058
1059 {nil, `package a5; type S struct{}; func (S) m(); var _ interface { n() } = S{}`,
1060 "S does not implement interface{n()} (missing method n)"},
1061
1062
1063 {bpkg, `package b1; import "b"; var _ interface { m() } = b.S{}`,
1064 "b.S does not implement interface{m()} (missing method m) have M() want m()"},
1065
1066 {bpkg, `package b2; import "b"; var _ interface { M() } = b.S{}`,
1067 ""},
1068
1069 {nil, `package b3; type S struct{}; func (S) M(); var _ interface { M() } = S{}`,
1070 ""},
1071
1072 {nil, `package b4; type S struct{}; func (S) M(); var _ interface { m() } = S{}`,
1073 "S does not implement interface{m()} (missing method m) have M() want m()"},
1074
1075 {nil, `package b5; type S struct{}; func (S) M(); var _ interface { n() } = S{}`,
1076 "S does not implement interface{n()} (missing method n)"},
1077 }
1078
1079 for _, test := range tests {
1080
1081 conf := Config{Importer: importHelper{pkg: test.imported}}
1082 pkg, err := typecheck(test.src, &conf, nil)
1083 if err == nil {
1084 if test.err != "" {
1085 t.Errorf("package %s: got no error, want %q", pkg.Name(), test.err)
1086 }
1087 continue
1088 }
1089 if test.err == "" {
1090 t.Errorf("package %s: got %q, want not error", pkg.Name(), err.Error())
1091 }
1092
1093
1094 errmsg := strings.ReplaceAll(err.Error(), "\n", " ")
1095 errmsg = strings.ReplaceAll(errmsg, "\t", "")
1096
1097
1098 if !strings.Contains(errmsg, test.err) {
1099 t.Errorf("package %s: got %q, want %q", pkg.Name(), errmsg, test.err)
1100 }
1101 }
1102 }
1103
1104 func TestIssue64759(t *testing.T) {
1105 const src = `
1106 //go:build go1.18
1107 package p
1108
1109 func f[S ~[]E, E any](S) {}
1110
1111 func _() {
1112 f([]string{})
1113 }
1114 `
1115
1116
1117 conf := Config{GoVersion: "go1.17"}
1118 mustTypecheck(src, &conf, nil)
1119 }
1120
1121 func TestIssue68334(t *testing.T) {
1122 const src = `
1123 package p
1124
1125 func f(x int) {
1126 for i, j := range x {
1127 _, _ = i, j
1128 }
1129 var a, b int
1130 for a, b = range x {
1131 _, _ = a, b
1132 }
1133 }
1134 `
1135
1136 got := ""
1137 conf := Config{
1138 GoVersion: "go1.21",
1139 Error: func(err error) { got += err.Error() + "\n" },
1140 }
1141 typecheck(src, &conf, nil)
1142
1143 want := "p:5:20: cannot range over x (variable of type int): requires go1.22 or later\n" +
1144 "p:9:19: cannot range over x (variable of type int): requires go1.22 or later\n"
1145 if got != want {
1146 t.Errorf("got: %s want: %s", got, want)
1147 }
1148 }
1149
1150 func TestIssue68877(t *testing.T) {
1151 const src = `
1152 package p
1153
1154 type (
1155 S struct{}
1156 A = S
1157 T A
1158 )`
1159
1160 pkg := mustTypecheck(src, nil, nil)
1161 T := pkg.Scope().Lookup("T").(*TypeName)
1162 got := T.String()
1163 const want = "type p.T struct{}"
1164 if got != want {
1165 t.Errorf("got %s, want %s", got, want)
1166 }
1167 }
1168
1169 func TestIssue69092(t *testing.T) {
1170 const src = `
1171 package p
1172
1173 var _ = T{{x}}
1174 `
1175
1176 file := mustParse(src)
1177 conf := Config{Error: func(err error) {}}
1178 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1179 conf.Check("p", []*syntax.File{file}, &info)
1180
1181
1182 outer := file.DeclList[0].(*syntax.VarDecl).Values.(*syntax.CompositeLit)
1183 inner := outer.ElemList[0]
1184
1185
1186 tv, ok := info.Types[inner]
1187 if !ok {
1188 t.Fatal("no type found for {x}")
1189 }
1190 if tv.Type != Typ[Invalid] {
1191 t.Fatalf("unexpected type for {x}: %s", tv.Type)
1192 }
1193 }
1194
View as plain text