1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements a custom generator to create various go/types
6 // source files from the corresponding types2 files.
25 var filesToWrite = flag.String("write", "", `go/types files to generate, or "all" for all files`)
28 srcDir = "/src/cmd/compile/internal/types2/"
29 dstDir = "/src/go/types/"
32 // TestGenerate verifies that generated files in go/types match their types2
33 // counterpart. If -write is set, this test actually writes the expected
34 // content to go/types; otherwise, it just compares with the existing content.
35 func TestGenerate(t *testing.T) {
36 // If filesToWrite is set, write the generated content to disk.
37 // In the special case of "all", write all files in filemap.
38 write := *filesToWrite != ""
39 var files []string // files to process
40 if *filesToWrite != "" && *filesToWrite != "all" {
41 files = strings.Split(*filesToWrite, ",")
43 for file := range filemap {
44 files = append(files, file)
48 for _, filename := range files {
49 generate(t, filename, write)
53 func generate(t *testing.T, filename string, write bool) {
55 srcFilename := filepath.FromSlash(runtime.GOROOT() + srcDir + filename)
56 file, err := parser.ParseFile(fset, srcFilename, nil, parser.ParseComments)
62 file.Name.Name = strings.ReplaceAll(file.Name.Name, "types2", "types")
64 // rewrite AST as needed
65 if action := filemap[filename]; action != nil {
71 buf.WriteString("// Code generated by \"go test -run=Generate -write=all\"; DO NOT EDIT.\n\n")
72 if err := format.Node(&buf, fset, file); err != nil {
75 generatedContent := buf.Bytes()
77 dstFilename := filepath.FromSlash(runtime.GOROOT() + dstDir + filename)
78 onDiskContent, err := os.ReadFile(dstFilename)
80 t.Fatalf("reading %q: %v", filename, err)
83 if d := diff.Diff(filename+" (on disk)", onDiskContent, filename+" (generated)", generatedContent); d != nil {
85 t.Logf("applying change:\n%s", d)
86 if err := os.WriteFile(dstFilename, generatedContent, 0o644); err != nil {
87 t.Fatalf("writing %q: %v", filename, err)
90 t.Errorf("generated file content does not match:\n%s", string(d))
95 type action func(in *ast.File)
97 var filemap = map[string]action{
101 "const.go": func(f *ast.File) { fixTokenPos(f) },
103 "context_test.go": nil,
104 "gccgosizes.go": nil,
105 "hilbert_test.go": func(f *ast.File) { renameImportPath(f, `"cmd/compile/internal/types2"`, `"go/types"`) },
106 "infer.go": func(f *ast.File) {
110 // "initorder.go": fixErrErrorfCall, // disabled for now due to unresolved error_ use implications for gopls
111 "instantiate.go": func(f *ast.File) { fixTokenPos(f); fixCheckErrorfCall(f) },
112 "instantiate_test.go": func(f *ast.File) { renameImportPath(f, `"cmd/compile/internal/types2"`, `"go/types"`) },
113 "lookup.go": func(f *ast.File) { fixTokenPos(f) },
116 "named.go": func(f *ast.File) { fixTokenPos(f); fixTraceSel(f) },
117 "object.go": func(f *ast.File) { fixTokenPos(f); renameIdent(f, "NewTypeNameLazy", "_NewTypeNameLazy") },
118 "object_test.go": func(f *ast.File) { renameImportPath(f, `"cmd/compile/internal/types2"`, `"go/types"`) },
122 "predicates.go": nil,
123 "scope.go": func(f *ast.File) {
125 renameIdent(f, "Squash", "squash")
126 renameIdent(f, "InsertLazy", "_InsertLazy")
129 "sizes.go": func(f *ast.File) { renameIdent(f, "IsSyncAtomicAlign64", "_IsSyncAtomicAlign64") },
131 "subst.go": func(f *ast.File) { fixTokenPos(f); fixTraceSel(f) },
133 "termlist_test.go": nil,
137 "typeterm_test.go": nil,
140 "unify.go": fixSprintf,
141 "universe.go": fixGlobalTypVarDecl,
142 "util_test.go": fixTokenPos,
146 // TODO(gri) We should be able to make these rewriters more configurable/composable.
147 // For now this is a good starting point.
149 // renameIdent renames an identifier.
150 // Note: This doesn't change the use of the identifier in comments.
151 func renameIdent(f *ast.File, from, to string) {
152 ast.Inspect(f, func(n ast.Node) bool {
153 switch n := n.(type) {
164 // renameImportPath renames an import path.
165 func renameImportPath(f *ast.File, from, to string) {
166 ast.Inspect(f, func(n ast.Node) bool {
167 switch n := n.(type) {
168 case *ast.ImportSpec:
169 if n.Path.Kind == token.STRING && n.Path.Value == from {
178 // fixTokenPos changes imports of "cmd/compile/internal/syntax" to "go/token",
179 // uses of syntax.Pos to token.Pos, and calls to x.IsKnown() to x.IsValid().
180 func fixTokenPos(f *ast.File) {
181 ast.Inspect(f, func(n ast.Node) bool {
182 switch n := n.(type) {
183 case *ast.ImportSpec:
184 // rewrite import path "cmd/compile/internal/syntax" to "go/token"
185 if n.Path.Kind == token.STRING && n.Path.Value == `"cmd/compile/internal/syntax"` {
186 n.Path.Value = `"go/token"`
189 case *ast.SelectorExpr:
190 // rewrite syntax.Pos to token.Pos
191 if x, _ := n.X.(*ast.Ident); x != nil && x.Name == "syntax" && n.Sel.Name == "Pos" {
196 // rewrite x.IsKnown() to x.IsValid()
197 if fun, _ := n.Fun.(*ast.SelectorExpr); fun != nil && fun.Sel.Name == "IsKnown" && len(n.Args) == 0 {
198 fun.Sel.Name = "IsValid"
206 // fixInferSig updates the Checker.infer signature to use a positioner instead of a token.Position
207 // as first argument, renames the argument from "pos" to "posn", and updates a few internal uses of
208 // "pos" to "posn" and "posn.Pos()" respectively.
209 func fixInferSig(f *ast.File) {
210 ast.Inspect(f, func(n ast.Node) bool {
211 switch n := n.(type) {
213 if n.Name.Name == "infer" || n.Name.Name == "infer1" || n.Name.Name == "infer2" {
214 // rewrite (pos token.Pos, ...) to (posn positioner, ...)
215 par := n.Type.Params.List[0]
216 if len(par.Names) == 1 && par.Names[0].Name == "pos" {
217 par.Names[0] = newIdent(par.Names[0].Pos(), "posn")
218 par.Type = newIdent(par.Type.Pos(), "positioner")
223 if selx, _ := n.Fun.(*ast.SelectorExpr); selx != nil {
224 switch selx.Sel.Name {
225 case "renameTParams":
226 // rewrite check.renameTParams(pos, ... ) to check.renameTParams(posn.Pos(), ... )
227 if ident, _ := n.Args[0].(*ast.Ident); ident != nil && ident.Name == "pos" {
228 pos := n.Args[0].Pos()
229 fun := &ast.SelectorExpr{X: newIdent(pos, "posn"), Sel: newIdent(pos, "Pos")}
230 arg := &ast.CallExpr{Fun: fun, Lparen: pos, Args: nil, Ellipsis: token.NoPos, Rparen: pos}
234 case "errorf", "infer1", "infer2":
235 // rewrite check.errorf(pos, ...) to check.errorf(posn, ...)
236 // rewrite check.infer1(pos, ...) to check.infer1(posn, ...)
237 // rewrite check.infer2(pos, ...) to check.infer2(posn, ...)
238 if ident, _ := n.Args[0].(*ast.Ident); ident != nil && ident.Name == "pos" {
239 pos := n.Args[0].Pos()
240 arg := newIdent(pos, "posn")
251 // fixErrErrorfCall updates calls of the form err.errorf(obj, ...) to err.errorf(obj.Pos(), ...).
252 func fixErrErrorfCall(f *ast.File) {
253 ast.Inspect(f, func(n ast.Node) bool {
254 switch n := n.(type) {
256 if selx, _ := n.Fun.(*ast.SelectorExpr); selx != nil {
257 if ident, _ := selx.X.(*ast.Ident); ident != nil && ident.Name == "err" {
258 switch selx.Sel.Name {
260 // rewrite err.errorf(obj, ... ) to err.errorf(obj.Pos(), ... )
261 if ident, _ := n.Args[0].(*ast.Ident); ident != nil && ident.Name == "obj" {
262 pos := n.Args[0].Pos()
263 fun := &ast.SelectorExpr{X: ident, Sel: newIdent(pos, "Pos")}
264 arg := &ast.CallExpr{Fun: fun, Lparen: pos, Args: nil, Ellipsis: token.NoPos, Rparen: pos}
276 // fixCheckErrorfCall updates calls of the form check.errorf(pos, ...) to check.errorf(atPos(pos), ...).
277 func fixCheckErrorfCall(f *ast.File) {
278 ast.Inspect(f, func(n ast.Node) bool {
279 switch n := n.(type) {
281 if selx, _ := n.Fun.(*ast.SelectorExpr); selx != nil {
282 if ident, _ := selx.X.(*ast.Ident); ident != nil && ident.Name == "check" {
283 switch selx.Sel.Name {
285 // rewrite check.errorf(pos, ... ) to check.errorf(atPos(pos), ... )
286 if ident, _ := n.Args[0].(*ast.Ident); ident != nil && ident.Name == "pos" {
287 pos := n.Args[0].Pos()
288 fun := newIdent(pos, "atPos")
289 arg := &ast.CallExpr{Fun: fun, Lparen: pos, Args: []ast.Expr{ident}, Ellipsis: token.NoPos, Rparen: pos}
301 // fixTraceSel renames uses of x.Trace to x.trace, where x for any x with a Trace field.
302 func fixTraceSel(f *ast.File) {
303 ast.Inspect(f, func(n ast.Node) bool {
304 switch n := n.(type) {
305 case *ast.SelectorExpr:
306 // rewrite x.Trace to x._Trace (for Config.Trace)
307 if n.Sel.Name == "Trace" {
308 n.Sel.Name = "_Trace"
316 // fixGlobalTypVarDecl changes the global Typ variable from an array to a slice
317 // (in types2 we use an array for efficiency, in go/types it's a slice and we
318 // cannot change that).
319 func fixGlobalTypVarDecl(f *ast.File) {
320 ast.Inspect(f, func(n ast.Node) bool {
321 switch n := n.(type) {
323 // rewrite type Typ = [...]Type{...} to type Typ = []Type{...}
324 if len(n.Names) == 1 && n.Names[0].Name == "Typ" && len(n.Values) == 1 {
325 n.Values[0].(*ast.CompositeLit).Type.(*ast.ArrayType).Len = nil
333 // fixSprintf adds an extra nil argument for the *token.FileSet parameter in sprintf calls.
334 func fixSprintf(f *ast.File) {
335 ast.Inspect(f, func(n ast.Node) bool {
336 switch n := n.(type) {
338 if fun, _ := n.Fun.(*ast.Ident); fun != nil && fun.Name == "sprintf" && len(n.Args) >= 4 /* ... args */ {
339 n.Args = insert(n.Args, 1, newIdent(n.Args[1].Pos(), "nil"))
347 // newIdent returns a new identifier with the given position and name.
348 func newIdent(pos token.Pos, name string) *ast.Ident {
349 id := ast.NewIdent(name)
354 // insert inserts x at list[at] and moves the remaining elements up.
355 func insert(list []ast.Expr, at int, x ast.Expr) []ast.Expr {
356 list = append(list, nil)
357 copy(list[at+1:], list[at:])