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 if recover() == nil {
635 panic("NewSignatureType panic expected")
636 }
637 }()
638 }
639 par := NewParam(nopos, nil, "", typ)
640 params := NewTuple(par)
641 NewSignatureType(nil, nil, nil, params, nil, true)
642 }
643
644
645
646 makeSig(NewSlice(Typ[Int]), true)
647
648
649 makeSig(Typ[String], true)
650
651
652 {
653 P := NewTypeName(nopos, nil, "P", nil)
654 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[String]})), true)
655 }
656
657
658 {
659 P := NewTypeName(nopos, nil, "P", nil)
660 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{NewSlice(Typ[Int])})), true)
661 }
662
663
664 {
665 t1 := NewTerm(true, Typ[String])
666 t2 := NewTerm(false, NewSlice(Typ[Byte]))
667 u := NewUnion([]*Term{t1, t2})
668 P := NewTypeName(nopos, nil, "P", nil)
669 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{u})), true)
670 }
671
672
673
674 makeSig(Typ[Int], false)
675
676
677 {
678 P := NewTypeName(nopos, nil, "P", nil)
679 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Universe.Lookup("any").Type()})), false)
680 }
681
682
683 {
684 P := NewTypeName(nopos, nil, "P", nil)
685 makeSig(NewTypeParam(P, NewInterfaceType(nil, []Type{Typ[Int]})), false)
686 }
687 }
688
689 func TestIssue51093(t *testing.T) {
690
691
692
693
694 var tests = []struct {
695 typ string
696 val string
697 }{
698 {"bool", "false"},
699 {"int", "-1"},
700 {"uint", "1.0"},
701 {"rune", "'a'"},
702 {"float64", "3.5"},
703 {"complex64", "1.25"},
704 {"string", "\"foo\""},
705
706
707 {"~byte", "1"},
708 {"~int | ~float64 | complex128", "1"},
709 {"~uint64 | ~rune", "'X'"},
710 }
711
712 for _, test := range tests {
713 src := fmt.Sprintf("package p; func _[P %s]() { _ = P(%s) }", test.typ, test.val)
714 types := make(map[syntax.Expr]TypeAndValue)
715 mustTypecheck(src, nil, &Info{Types: types})
716
717 var n int
718 for x, tv := range types {
719 if x, _ := x.(*syntax.CallExpr); x != nil {
720
721 n++
722 tpar, _ := tv.Type.(*TypeParam)
723 if tpar == nil {
724 t.Fatalf("%s: got type %s, want type parameter", ExprString(x), tv.Type)
725 }
726 if name := tpar.Obj().Name(); name != "P" {
727 t.Fatalf("%s: got type parameter name %s, want P", ExprString(x), name)
728 }
729
730 if tv.Value != nil {
731 t.Errorf("%s: got constant value %s (%s), want no constant", ExprString(x), tv.Value, tv.Value.String())
732 }
733 }
734 }
735
736 if n != 1 {
737 t.Fatalf("%s: got %d CallExpr nodes; want 1", src, 1)
738 }
739 }
740 }
741
742 func TestIssue54258(t *testing.T) {
743 tests := []struct{ main, b, want string }{
744 {
745 `package main
746 import "b"
747 type I0 interface {
748 M0(w struct{ f string })
749 }
750 var _ I0 = b.S{}
751 `,
752 `package b
753 type S struct{}
754 func (S) M0(struct{ f string }) {}
755 `,
756 `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[)]
757 .*have M0[(]struct{f string /[*] package b [*]/ }[)]
758 .*want M0[(]struct{f string /[*] package main [*]/ }[)]`},
759
760 {
761 `package main
762 import "b"
763 type I1 interface {
764 M1(struct{ string })
765 }
766 var _ I1 = b.S{}
767 `,
768 `package b
769 type S struct{}
770 func (S) M1(struct{ string }) {}
771 `,
772 `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[)]
773 .*have M1[(]struct{string /[*] package b [*]/ }[)]
774 .*want M1[(]struct{string /[*] package main [*]/ }[)]`},
775
776 {
777 `package main
778 import "b"
779 type I2 interface {
780 M2(y struct{ f struct{ f string } })
781 }
782 var _ I2 = b.S{}
783 `,
784 `package b
785 type S struct{}
786 func (S) M2(struct{ f struct{ f string } }) {}
787 `,
788 `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[)]
789 .*have M2[(]struct{f struct{f string} /[*] package b [*]/ }[)]
790 .*want M2[(]struct{f struct{f string} /[*] package main [*]/ }[)]`},
791
792 {
793 `package main
794 import "b"
795 type I3 interface {
796 M3(z struct{ F struct{ f string } })
797 }
798 var _ I3 = b.S{}
799 `,
800 `package b
801 type S struct{}
802 func (S) M3(struct{ F struct{ f string } }) {}
803 `,
804 `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[)]
805 .*have M3[(]struct{F struct{f string /[*] package b [*]/ }}[)]
806 .*want M3[(]struct{F struct{f string /[*] package main [*]/ }}[)]`},
807
808 {
809 `package main
810 import "b"
811 type I4 interface {
812 M4(_ struct { *string })
813 }
814 var _ I4 = b.S{}
815 `,
816 `package b
817 type S struct{}
818 func (S) M4(struct { *string }) {}
819 `,
820 `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[)]
821 .*have M4[(]struct{[*]string /[*] package b [*]/ }[)]
822 .*want M4[(]struct{[*]string /[*] package main [*]/ }[)]`},
823
824 {
825 `package main
826 import "b"
827 type t struct{ A int }
828 type I5 interface {
829 M5(_ struct {b.S;t})
830 }
831 var _ I5 = b.S{}
832 `,
833 `package b
834 type S struct{}
835 type t struct{ A int }
836 func (S) M5(struct {S;t}) {}
837 `,
838 `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[)]
839 .*have M5[(]struct{b[.]S; b[.]t}[)]
840 .*want M5[(]struct{b[.]S; t}[)]`},
841 }
842
843 test := func(main, b, want string) {
844 re := regexp.MustCompile(want)
845 bpkg := mustTypecheck(b, nil, nil)
846 mast := mustParse(main)
847 conf := Config{Importer: importHelper{pkg: bpkg}}
848 _, err := conf.Check(mast.PkgName.Value, []*syntax.File{mast}, nil)
849 if err == nil {
850 t.Error("Expected failure, but it did not")
851 } else if got := err.Error(); !re.MatchString(got) {
852 t.Errorf("Wanted match for\n\t%s\n but got\n\t%s", want, got)
853 } else if testing.Verbose() {
854 t.Logf("Saw expected\n\t%s", err.Error())
855 }
856 }
857 for _, t := range tests {
858 test(t.main, t.b, t.want)
859 }
860 }
861
862 func TestIssue59944(t *testing.T) {
863 testenv.MustHaveCGO(t)
864
865
866 const src = `// -gotypesalias=1
867
868 package p
869
870 /*
871 struct layout {};
872 */
873 import "C"
874
875 type Layout = C.struct_layout
876
877 func (*Layout /* ERROR "cannot define new methods on non-local type Layout" */) Binding() {}
878 `
879
880
881 const cgoTypes = `
882 // Code generated by cmd/cgo; DO NOT EDIT.
883
884 package p
885
886 import "unsafe"
887
888 import "syscall"
889
890 import _cgopackage "runtime/cgo"
891
892 type _ _cgopackage.Incomplete
893 var _ syscall.Errno
894 func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
895
896 //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
897 var _Cgo_always_false bool
898 //go:linkname _Cgo_use runtime.cgoUse
899 func _Cgo_use(interface{})
900 //go:linkname _Cgo_keepalive runtime.cgoKeepAlive
901 //go:noescape
902 func _Cgo_keepalive(interface{})
903 //go:linkname _Cgo_no_callback runtime.cgoNoCallback
904 func _Cgo_no_callback(bool)
905 type _Ctype_struct_layout struct {
906 }
907
908 type _Ctype_void [0]byte
909
910 //go:linkname _cgo_runtime_cgocall runtime.cgocall
911 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
912
913 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
914 //go:noescape
915 func _cgoCheckPointer(interface{}, interface{})
916
917 //go:linkname _cgoCheckResult runtime.cgoCheckResult
918 //go:noescape
919 func _cgoCheckResult(interface{})
920 `
921 testFiles(t, []string{"p.go", "_cgo_gotypes.go"}, [][]byte{[]byte(src), []byte(cgoTypes)}, 0, false, func(cfg *Config) {
922 *boolFieldAddr(cfg, "go115UsesCgo") = true
923 })
924 }
925
926 func TestIssue61931(t *testing.T) {
927 const src = `
928 package p
929
930 func A(func(any), ...any) {}
931 func B[T any](T) {}
932
933 func _() {
934 A(B, nil // syntax error: missing ',' before newline in argument list
935 }
936 `
937 f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), func(error) {}, nil, 0)
938 if err == nil {
939 t.Fatal("expected syntax error")
940 }
941
942 var conf Config
943 conf.Check(f.PkgName.Value, []*syntax.File{f}, nil)
944 }
945
946 func TestIssue61938(t *testing.T) {
947 const src = `
948 package p
949
950 func f[T any]() {}
951 func _() { f() }
952 `
953
954 var conf Config
955 typecheck(src, &conf, nil)
956
957
958 conf.Error = func(error) {}
959 typecheck(src, &conf, nil)
960 }
961
962 func TestIssue63260(t *testing.T) {
963 const src = `
964 package p
965
966 func _() {
967 use(f[*string])
968 }
969
970 func use(func()) {}
971
972 func f[I *T, T any]() {
973 var v T
974 _ = v
975 }`
976
977 info := Info{
978 Defs: make(map[*syntax.Name]Object),
979 }
980 pkg := mustTypecheck(src, nil, &info)
981
982
983 T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
984 if T.Obj().Name() != "T" {
985 t.Fatalf("got type parameter %s, want T", T)
986 }
987
988
989 var v Object
990 for name, obj := range info.Defs {
991 if name.Value == "v" {
992 v = obj
993 break
994 }
995 }
996 if v == nil {
997 t.Fatal("variable v not found")
998 }
999
1000
1001 if v.Type() != T {
1002 t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)
1003 }
1004 }
1005
1006 func TestIssue44410(t *testing.T) {
1007 const src = `
1008 package p
1009
1010 type A = []int
1011 type S struct{ A }
1012 `
1013
1014 conf := Config{EnableAlias: true}
1015 pkg := mustTypecheck(src, &conf, nil)
1016
1017 S := pkg.Scope().Lookup("S")
1018 if S == nil {
1019 t.Fatal("object S not found")
1020 }
1021
1022 got := S.String()
1023 const want = "type p.S struct{p.A}"
1024 if got != want {
1025 t.Fatalf("got %q; want %q", got, want)
1026 }
1027 }
1028
1029 func TestIssue59831(t *testing.T) {
1030
1031
1032 const asrc = `package a; type S struct{}; func (S) m() {}`
1033 apkg := mustTypecheck(asrc, nil, nil)
1034
1035
1036
1037 const bsrc = `package b; type S struct{}; func (S) M() {}`
1038 bpkg := mustTypecheck(bsrc, nil, nil)
1039
1040 tests := []struct {
1041 imported *Package
1042 src, err string
1043 }{
1044
1045 {apkg, `package a1; import "a"; var _ interface { M() } = a.S{}`,
1046 "a.S does not implement interface{M()} (missing method M) have m() want M()"},
1047
1048 {apkg, `package a2; import "a"; var _ interface { m() } = a.S{}`,
1049 "a.S does not implement interface{m()} (unexported method m)"},
1050
1051 {nil, `package a3; type S struct{}; func (S) m(); var _ interface { M() } = S{}`,
1052 "S does not implement interface{M()} (missing method M) have m() want M()"},
1053
1054 {nil, `package a4; type S struct{}; func (S) m(); var _ interface { m() } = S{}`,
1055 ""},
1056
1057 {nil, `package a5; type S struct{}; func (S) m(); var _ interface { n() } = S{}`,
1058 "S does not implement interface{n()} (missing method n)"},
1059
1060
1061 {bpkg, `package b1; import "b"; var _ interface { m() } = b.S{}`,
1062 "b.S does not implement interface{m()} (missing method m) have M() want m()"},
1063
1064 {bpkg, `package b2; import "b"; var _ interface { M() } = b.S{}`,
1065 ""},
1066
1067 {nil, `package b3; type S struct{}; func (S) M(); var _ interface { M() } = S{}`,
1068 ""},
1069
1070 {nil, `package b4; type S struct{}; func (S) M(); var _ interface { m() } = S{}`,
1071 "S does not implement interface{m()} (missing method m) have M() want m()"},
1072
1073 {nil, `package b5; type S struct{}; func (S) M(); var _ interface { n() } = S{}`,
1074 "S does not implement interface{n()} (missing method n)"},
1075 }
1076
1077 for _, test := range tests {
1078
1079 conf := Config{Importer: importHelper{pkg: test.imported}}
1080 pkg, err := typecheck(test.src, &conf, nil)
1081 if err == nil {
1082 if test.err != "" {
1083 t.Errorf("package %s: got no error, want %q", pkg.Name(), test.err)
1084 }
1085 continue
1086 }
1087 if test.err == "" {
1088 t.Errorf("package %s: got %q, want not error", pkg.Name(), err.Error())
1089 }
1090
1091
1092 errmsg := strings.ReplaceAll(err.Error(), "\n", " ")
1093 errmsg = strings.ReplaceAll(errmsg, "\t", "")
1094
1095
1096 if !strings.Contains(errmsg, test.err) {
1097 t.Errorf("package %s: got %q, want %q", pkg.Name(), errmsg, test.err)
1098 }
1099 }
1100 }
1101
1102 func TestIssue64759(t *testing.T) {
1103 const src = `
1104 //go:build go1.18
1105 package p
1106
1107 func f[S ~[]E, E any](S) {}
1108
1109 func _() {
1110 f([]string{})
1111 }
1112 `
1113
1114
1115 conf := Config{GoVersion: "go1.17"}
1116 mustTypecheck(src, &conf, nil)
1117 }
1118
1119 func TestIssue68334(t *testing.T) {
1120 const src = `
1121 package p
1122
1123 func f(x int) {
1124 for i, j := range x {
1125 _, _ = i, j
1126 }
1127 var a, b int
1128 for a, b = range x {
1129 _, _ = a, b
1130 }
1131 }
1132 `
1133
1134 got := ""
1135 conf := Config{
1136 GoVersion: "go1.21",
1137 Error: func(err error) { got += err.Error() + "\n" },
1138 }
1139 typecheck(src, &conf, nil)
1140
1141 want := "p:5:20: cannot range over x (variable of type int): requires go1.22 or later\n" +
1142 "p:9:19: cannot range over x (variable of type int): requires go1.22 or later\n"
1143 if got != want {
1144 t.Errorf("got: %s want: %s", got, want)
1145 }
1146 }
1147
1148 func TestIssue68877(t *testing.T) {
1149 const src = `
1150 package p
1151
1152 type (
1153 S struct{}
1154 A = S
1155 T A
1156 )`
1157
1158 conf := Config{EnableAlias: true}
1159 pkg := mustTypecheck(src, &conf, nil)
1160 T := pkg.Scope().Lookup("T").(*TypeName)
1161 got := T.String()
1162 const want = "type p.T struct{}"
1163 if got != want {
1164 t.Errorf("got %s, want %s", got, want)
1165 }
1166 }
1167
1168 func TestIssue69092(t *testing.T) {
1169 const src = `
1170 package p
1171
1172 var _ = T{{x}}
1173 `
1174
1175 file := mustParse(src)
1176 conf := Config{Error: func(err error) {}}
1177 info := Info{Types: make(map[syntax.Expr]TypeAndValue)}
1178 conf.Check("p", []*syntax.File{file}, &info)
1179
1180
1181 outer := file.DeclList[0].(*syntax.VarDecl).Values.(*syntax.CompositeLit)
1182 inner := outer.ElemList[0]
1183
1184
1185 tv, ok := info.Types[inner]
1186 if !ok {
1187 t.Fatal("no type found for {x}")
1188 }
1189 if tv.Type != Typ[Invalid] {
1190 t.Fatalf("unexpected type for {x}: %s", tv.Type)
1191 }
1192 }
1193
View as plain text