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 // MaybePointerLike returns true if type T is like a pointer. This returns true
148 // for all nillable types, unsafe.Pointer, type sets where at least one term is
149 // pointer-like, and type sets without structural restrictions..
150 func MaybePointerLike(T types.Type) bool {
151 switch T := T.Underlying().(type) {
152 case *types.Interface:
153 if T.IsMethodSet() {
154 return true
155 } else {
156 terms, err := typeparams.NormalTerms(T)
157 if err != nil {
158 return false
159 }
160 for _, term := range terms {
161 if MaybePointerLike(term.Type()) {
162 return true
163 }
164 }
165 return len(terms) == 0
166 }
167 case *types.Chan, *types.Map, *types.Signature, *types.Pointer, *types.Slice:
168 return true
169 case *types.Basic:
170 return T.Kind() == types.UnsafePointer
171 }
172 return false
173 }
174
175 type Field struct {
176 Var *types.Var
177 Tag string
178 Path []int
179 }
180
181 // FlattenFields recursively flattens T and embedded structs,
182 // returning a list of fields. If multiple fields with the same name
183 // exist, all will be returned.
184 func FlattenFields(T *types.Struct) []Field {
185 return flattenFields(T, nil, nil)
186 }
187
188 func flattenFields(T *types.Struct, path []int, seen map[types.Type]bool) []Field {
189 if seen == nil {
190 seen = map[types.Type]bool{}
191 }
192 if seen[T] {
193 return nil
194 }
195 seen[T] = true
196 var out []Field
197 for i := 0; i < T.NumFields(); i++ {
198 field := T.Field(i)
199 tag := T.Tag(i)
200 np := append(path[:len(path):len(path)], i)
201 if field.Anonymous() {
202 if s, ok := Dereference(field.Type()).Underlying().(*types.Struct); ok {
203 out = append(out, flattenFields(s, np, seen)...)
204 } else {
205 out = append(out, Field{field, tag, np})
206 }
207 } else {
208 out = append(out, Field{field, tag, np})
209 }
210 }
211 return out
212 }