Debian Codegraph @

go/types/typeutil/util.go

raw
1 package typeutil
2
3 import (
4 "bytes"
5 "go/types"
6 "strings"
7 "sync"
8
9 "golang.org/x/exp/typeparams"
10 )
11
12 var bufferPool = &sync.Pool{
13 New: func() any {
14 buf := bytes.NewBuffer(nil)
15 buf.Grow(64)
16 return buf
17 },
18 }
19
20 func FuncName(f *types.Func) string {
21 // We don't care about aliases in this function because we use FuncName to check calls
22 // to known methods, and method receivers are determined by the method declaration,
23 // not the call. Thus, even if a user does 'type Alias = *sync.Mutex' and calls
24 // Alias.Lock, we'll still see it as (*sync.Mutex).Lock.
25
26 buf := bufferPool.Get().(*bytes.Buffer)
27 buf.Reset()
28 if f.Type() != nil {
29 sig := f.Type().(*types.Signature)
30 if recv := sig.Recv(); recv != nil {
31 buf.WriteByte('(')
32 if _, ok := recv.Type().(*types.Interface); ok {
33 // gcimporter creates abstract methods of
34 // named interfaces using the interface type
35 // (not the named type) as the receiver.
36 // Don't print it in full.
37 buf.WriteString("interface")
38 } else {
39 types.WriteType(buf, recv.Type(), nil)
40 }
41 buf.WriteByte(')')
42 buf.WriteByte('.')
43 } else if f.Pkg() != nil {
44 writePackage(buf, f.Pkg())
45 }
46 }
47 buf.WriteString(f.Name())
48 s := buf.String()
49 bufferPool.Put(buf)
50 return s
51 }
52
53 func writePackage(buf *bytes.Buffer, pkg *types.Package) {
54 if pkg == nil {
55 return
56 }
57 s := pkg.Path()
58 if s != "" {
59 buf.WriteString(s)
60 buf.WriteByte('.')
61 }
62 }
63
64 // Dereference returns a pointer's element type; otherwise it returns
65 // T.
66 func Dereference(T types.Type) types.Type {
67 if p, ok := T.Underlying().(*types.Pointer); ok {
68 return p.Elem()
69 }
70 return T
71 }
72
73 // DereferenceR returns a pointer's element type; otherwise it returns
74 // T. If the element type is itself a pointer, DereferenceR will be
75 // applied recursively.
76 func DereferenceR(T types.Type) types.Type {
77 if p, ok := T.Underlying().(*types.Pointer); ok {
78 return DereferenceR(p.Elem())
79 }
80 return T
81 }
82
83 func IsObject(obj types.Object, name string) bool {
84 var path string
85 if pkg := obj.Pkg(); pkg != nil {
86 path = pkg.Path() + "."
87 }
88 return path+obj.Name() == name
89 }
90
91 // IsTypeName reports whether obj represents the qualified name. If obj is a type alias,
92 // IsTypeName checks both the alias and the aliased type, if the aliased type has a type
93 // name.
94 func IsTypeName(obj *types.TypeName, name string) bool {
95 var qf string
96 if idx := strings.LastIndex(name, "."); idx != -1 {
97 qf = name[:idx]
98 name = name[idx+1:]
99 }
100 if obj.Name() == name &&
101 ((qf == "" && obj.Pkg() == nil) || (obj.Pkg() != nil && obj.Pkg().Path() == qf)) {
102 return true
103 }
104
105 if !obj.IsAlias() {
106 return false
107 }
108
109 // FIXME(dh): we should peel away one layer of alias at a time; this is blocked on
110 // github.com/golang/go/issues/66559
111 if typ, ok := types.Unalias(obj.Type()).(interface{ Obj() *types.TypeName }); ok {
112 return IsTypeName(typ.Obj(), name)
113 }
114
115 return false
116 }
117
118 func IsPointerToTypeWithName(typ types.Type, name string) bool {
119 ptr, ok := types.Unalias(typ).(*types.Pointer)
120 if !ok {
121 return false
122 }
123 return IsTypeWithName(ptr.Elem(), name)
124 }
125
126 // IsTypeWithName reports whether typ represents a type with the qualified name, If typ is
127 // a type alias, IsTypeWithName checks both the alias and the aliased type. The following
128 // types can have names: Basic, Named, Alias.
129 func IsTypeWithName(typ types.Type, name string) bool {
130 switch typ := typ.(type) {
131 case *types.Basic:
132 return typ.Name() == name
133 case *types.Named:
134 return IsTypeName(typ.Obj(), name)
135 case *types.Alias:
136 // FIXME(dh): we should peel away one layer of alias at a time; this is blocked on
137 // github.com/golang/go/issues/66559
138
139 // IsTypeName already handles aliases to other aliases or named types; our
140 // fallback is required for aliases to basic types.
141 return IsTypeName(typ.Obj(), name) || IsTypeWithName(types.Unalias(typ), name)
142 default:
143 return false
144 }
145 }
146
147 // IsPointerLike returns true if type T is like a pointer. This returns true for all nillable types,
148 // unsafe.Pointer, and type sets where at least one term is pointer-like.
149 func IsPointerLike(T types.Type) bool {
150 switch T := T.Underlying().(type) {
151 case *types.Interface:
152 if T.IsMethodSet() {
153 return true
154 } else {
155 terms, err := typeparams.NormalTerms(T)
156 if err != nil {
157 return false
158 }
159 for _, term := range terms {
160 if IsPointerLike(term.Type()) {
161 return true
162 }
163 }
164 return false
165 }
166 case *types.Chan, *types.Map, *types.Signature, *types.Pointer, *types.Slice:
167 return true
168 case *types.Basic:
169 return T.Kind() == types.UnsafePointer
170 }
171 return false
172 }
173
174 type Field struct {
175 Var *types.Var
176 Tag string
177 Path []int
178 }
179
180 // FlattenFields recursively flattens T and embedded structs,
181 // returning a list of fields. If multiple fields with the same name
182 // exist, all will be returned.
183 func FlattenFields(T *types.Struct) []Field {
184 return flattenFields(T, nil, nil)
185 }
186
187 func flattenFields(T *types.Struct, path []int, seen map[types.Type]bool) []Field {
188 if seen == nil {
189 seen = map[types.Type]bool{}
190 }
191 if seen[T] {
192 return nil
193 }
194 seen[T] = true
195 var out []Field
196 for i := 0; i < T.NumFields(); i++ {
197 field := T.Field(i)
198 tag := T.Tag(i)
199 np := append(path[:len(path):len(path)], i)
200 if field.Anonymous() {
201 if s, ok := Dereference(field.Type()).Underlying().(*types.Struct); ok {
202 out = append(out, flattenFields(s, np, seen)...)
203 } else {
204 out = append(out, Field{field, tag, np})
205 }
206 } else {
207 out = append(out, Field{field, tag, np})
208 }
209 }
210 return out
211 }