File: typeparams_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (138 lines) | stat: -rw-r--r-- 3,487 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.18
// +build go1.18

package typeparams_test

import (
	"bytes"
	"go/ast"
	"go/build"
	"go/importer"
	"go/parser"
	"go/token"
	"go/types"
	"testing"
)

// TestAPIConsistency verifies that exported APIs match at Go 1.17 and Go
// 1.18+.
//
// It relies on the convention that the names of type aliases in the typeparams
// package match the names of the types they are aliasing.
//
// This test could be made more precise.
func TestAPIConsistency(t *testing.T) {
	api118 := getAPI(buildPackage(t, true))
	api117 := getAPI(buildPackage(t, false))

	for name, api := range api117 {
		if api != api118[name] {
			t.Errorf("%q: got %s at 1.17, but %s at 1.18+", name, api, api118[name])
		}
		delete(api118, name)
	}
	for name, api := range api118 {
		if api != api117[name] {
			t.Errorf("%q: got %s at 1.18+, but %s at 1.17", name, api, api117[name])
		}
	}
}

func getAPI(pkg *types.Package) map[string]string {
	api := make(map[string]string)
	for _, name := range pkg.Scope().Names() {
		if !token.IsExported(name) {
			continue
		}
		api[name] = name
		obj := pkg.Scope().Lookup(name)
		if f, ok := obj.(*types.Func); ok {
			api[name] = formatSignature(f.Type().(*types.Signature))
		}
		typ := pkg.Scope().Lookup(name).Type()
		// Consider method sets of pointer and non-pointer receivers.
		msets := map[string]*types.MethodSet{
			name:       types.NewMethodSet(typ),
			"*" + name: types.NewMethodSet(types.NewPointer(typ)),
		}
		for name, mset := range msets {
			for i := 0; i < mset.Len(); i++ {
				f := mset.At(i).Obj().(*types.Func)
				mname := f.Name()
				if token.IsExported(mname) {
					api[name+"."+mname] = formatSignature(f.Type().(*types.Signature))
				}
			}
		}
	}
	return api
}

func formatSignature(sig *types.Signature) string {
	var b bytes.Buffer
	b.WriteString("func")
	writeTuple(&b, sig.Params())
	writeTuple(&b, sig.Results())
	return b.String()
}

func writeTuple(buf *bytes.Buffer, t *types.Tuple) {
	buf.WriteRune('(')

	// The API at Go 1.18 uses aliases for types in go/types. These types are
	// _actually_ in the go/types package, and therefore would be formatted as
	// e.g. *types.TypeParam, which would not match *typeparams.TypeParam --
	// go/types does not track aliases. As we use the same name for all aliases,
	// we can make the formatted signatures match by dropping the package
	// qualifier.
	qf := func(*types.Package) string { return "" }

	for i := 0; i < t.Len(); i++ {
		if i > 0 {
			buf.WriteString(", ")
		}
		buf.WriteString(types.TypeString(t.At(i).Type(), qf))
	}
	buf.WriteRune(')')
}

func buildPackage(t *testing.T, go118 bool) *types.Package {
	ctxt := build.Default
	if !go118 {
		for i, tag := range ctxt.ReleaseTags {
			if tag == "go1.18" {
				ctxt.ReleaseTags = ctxt.ReleaseTags[:i]
				break
			}
		}
	}
	bpkg, err := ctxt.ImportDir(".", 0)
	if err != nil {
		t.Fatal(err)
	}
	return typeCheck(t, bpkg.GoFiles)
}

func typeCheck(t *testing.T, filenames []string) *types.Package {
	fset := token.NewFileSet()
	var files []*ast.File
	for _, name := range filenames {
		f, err := parser.ParseFile(fset, name, nil, 0)
		if err != nil {
			t.Fatal(err)
		}
		files = append(files, f)
	}
	conf := types.Config{
		Importer: importer.Default(),
	}
	pkg, err := conf.Check("", fset, files, nil)
	if err != nil {
		t.Fatal(err)
	}
	return pkg
}