Debian Codegraph @

internal/typeparams/copytermlist.go

raw symbols SCIP
1 // Copyright 2021 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.
4
5 //go:build ignore
6
7 // copytermlist.go copies the term list algorithm from GOROOT/src/go/types.
8
9 package main
10
11 import (
12 "bytes"
13 "fmt"
14 "go/ast"
15 "go/format"
16 "go/parser"
17 "go/token"
18 "os"
19 "path/filepath"
20 "reflect"
21 "runtime"
22 "strings"
23
24 "golang.org/x/tools/go/ast/astutil"
25 )
26
27 func main() {
28 if err := doCopy(); err != nil {
29 fmt.Fprintf(os.Stderr, "error copying from go/types: %v", err)
30 os.Exit(1)
31 }
32 }
33
34 func doCopy() error {
35 dir := filepath.Join(runtime.GOROOT(), "src", "go", "types")
36 for _, name := range []string{"typeterm.go", "termlist.go"} {
37 path := filepath.Join(dir, name)
38 fset := token.NewFileSet()
39 file, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
40 if err != nil {
41 return err
42 }
43 file.Name.Name = "typeparams"
44 file.Doc = &ast.CommentGroup{List: []*ast.Comment{{Text: "DO NOT MODIFY"}}}
45 var needImport bool
46 selectorType := reflect.TypeOf((*ast.SelectorExpr)(nil))
47 astutil.Apply(file, func(c *astutil.Cursor) bool {
48 if id, _ := c.Node().(*ast.Ident); id != nil {
49 // Check if this ident should be qualified with types. For simplicity,
50 // assume the copied files do not themselves contain any exported
51 // symbols.
52
53 // As a simple heuristic, just verify that the ident may be replaced by
54 // a selector.
55 if !token.IsExported(id.Name) {
56 return false
57 }
58 v := reflect.TypeOf(c.Parent()).Elem() // ast nodes are all pointers
59 field, ok := v.FieldByName(c.Name())
60 if !ok {
61 panic("missing field")
62 }
63 t := field.Type
64 if c.Index() > 0 { // => t is a slice
65 t = t.Elem()
66 }
67 if !selectorType.AssignableTo(t) {
68 return false
69 }
70 needImport = true
71 c.Replace(&ast.SelectorExpr{
72 X: &ast.Ident{NamePos: id.NamePos, Name: "types"},
73 Sel: &ast.Ident{NamePos: id.NamePos, Name: id.Name, Obj: id.Obj},
74 })
75 }
76 return true
77 }, nil)
78 if needImport {
79 astutil.AddImport(fset, file, "go/types")
80 }
81
82 var b bytes.Buffer
83 if err := format.Node(&b, fset, file); err != nil {
84 return err
85 }
86
87 // Hack in the 'generated' byline.
88 content := b.String()
89 header := "// Code generated by copytermlist.go DO NOT EDIT.\n\npackage typeparams"
90 content = strings.Replace(content, "package typeparams", header, 1)
91
92 if err := os.WriteFile(name, []byte(content), 0644); err != nil {
93 return err
94 }
95 }
96 return nil
97 }