Debian Codegraph @

internal/typesinternal/types.go

raw symbols SCIP
1 // Copyright 2020 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 // Package typesinternal provides helpful operators for dealing with
6 // go/types:
7 //
8 // - operators for querying typed syntax trees (e.g. [Imports], [IsFunctionNamed]);
9 // - functions for converting types to strings or syntax (e.g. [TypeExpr], FileQualifier]);
10 // - helpers for working with the [go/types] API (e.g. [NewTypesInfo]);
11 // - access to internal go/types APIs that are not yet
12 // exported (e.g. [SetUsesCgo], [ErrorCodeStartEnd], [VarKind]); and
13 // - common algorithms related to types (e.g. [TooNewStdSymbols]).
14 //
15 // See also:
16 // - [golang.org/x/tools/internal/astutil], for operations on untyped syntax;
17 // - [golang.org/x/tools/internal/analysisinernal], for helpers for analyzers;
18 // - [golang.org/x/tools/internal/refactor], for operators to compute text edits.
19 package typesinternal
20
21 import (
22 "go/ast"
23 "go/token"
24 "go/types"
25 "iter"
26 "reflect"
27
28 "golang.org/x/tools/go/ast/inspector"
29 )
30
31 func SetUsesCgo(conf *types.Config) bool {
32 v := reflect.ValueOf(conf).Elem()
33
34 f := v.FieldByName("go115UsesCgo")
35 if !f.IsValid() {
36 f = v.FieldByName("UsesCgo")
37 if !f.IsValid() {
38 return false
39 }
40 }
41
42 *(*bool)(f.Addr().UnsafePointer()) = true
43
44 return true
45 }
46
47 // ErrorCodeStartEnd extracts additional information from types.Error values
48 // generated by Go version 1.16 and later: the error code, start position, and
49 // end position. If all positions are valid, start <= err.Pos <= end.
50 //
51 // If the data could not be read, the final result parameter will be false.
52 //
53 // TODO(adonovan): eliminate start/end when proposal #71803 is accepted.
54 func ErrorCodeStartEnd(err types.Error) (code ErrorCode, start, end token.Pos, ok bool) {
55 var data [3]int
56 // By coincidence all of these fields are ints, which simplifies things.
57 v := reflect.ValueOf(err)
58 for i, name := range []string{"go116code", "go116start", "go116end"} {
59 f := v.FieldByName(name)
60 if !f.IsValid() {
61 return 0, 0, 0, false
62 }
63 data[i] = int(f.Int())
64 }
65 return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true
66 }
67
68 // NameRelativeTo returns a types.Qualifier that qualifies members of
69 // all packages other than pkg, using only the package name.
70 // (By contrast, [types.RelativeTo] uses the complete package path,
71 // which is often excessive.)
72 //
73 // If pkg is nil, it is equivalent to [*types.Package.Name].
74 //
75 // TODO(adonovan): all uses of this with TypeString should be
76 // eliminated when https://go.dev/issues/75604 is resolved.
77 func NameRelativeTo(pkg *types.Package) types.Qualifier {
78 return func(other *types.Package) string {
79 if pkg != nil && pkg == other {
80 return "" // same package; unqualified
81 }
82 return other.Name()
83 }
84 }
85
86 // TypeNameFor returns the type name symbol for the specified type, if
87 // it is a [*types.Alias], [*types.Named], [*types.TypeParam], or a
88 // [*types.Basic] representing a type.
89 //
90 // For all other types, and for Basic types representing a builtin,
91 // constant, or nil, it returns nil. Be careful not to convert the
92 // resulting nil pointer to a [types.Object]!
93 //
94 // If t is the type of a constant, it may be an "untyped" type, which
95 // has no TypeName. To access the name of such types (e.g. "untyped
96 // int"), use [types.Basic.Name].
97 func TypeNameFor(t types.Type) *types.TypeName {
98 switch t := t.(type) {
99 case *types.Alias:
100 return t.Obj()
101 case *types.Named:
102 return t.Obj()
103 case *types.TypeParam:
104 return t.Obj()
105 case *types.Basic:
106 // See issues #71886 and #66890 for some history.
107 if tname, ok := types.Universe.Lookup(t.Name()).(*types.TypeName); ok {
108 return tname
109 }
110 }
111 return nil
112 }
113
114 // A NamedOrAlias is a [types.Type] that is named (as
115 // defined by the spec) and capable of bearing type parameters: it
116 // abstracts aliases ([types.Alias]) and defined types
117 // ([types.Named]).
118 //
119 // Every type declared by an explicit "type" declaration is a
120 // NamedOrAlias. (Built-in type symbols may additionally
121 // have type [types.Basic], which is not a NamedOrAlias,
122 // though the spec regards them as "named"; see [TypeNameFor].)
123 //
124 // NamedOrAlias cannot expose the Origin method, because
125 // [types.Alias.Origin] and [types.Named.Origin] have different
126 // (covariant) result types; use [Origin] instead.
127 type NamedOrAlias interface {
128 types.Type
129 Obj() *types.TypeName
130 TypeArgs() *types.TypeList
131 TypeParams() *types.TypeParamList
132 SetTypeParams(tparams []*types.TypeParam)
133 }
134
135 var (
136 _ NamedOrAlias = (*types.Alias)(nil)
137 _ NamedOrAlias = (*types.Named)(nil)
138 )
139
140 // Origin returns the generic type of the Named or Alias type t if it
141 // is instantiated, otherwise it returns t.
142 func Origin(t NamedOrAlias) NamedOrAlias {
143 switch t := t.(type) {
144 case *types.Alias:
145 return t.Origin()
146 case *types.Named:
147 return t.Origin()
148 }
149 return t
150 }
151
152 // IsPackageLevel reports whether obj is a package-level symbol.
153 func IsPackageLevel(obj types.Object) bool {
154 return obj.Pkg() != nil && obj.Parent() == obj.Pkg().Scope()
155 }
156
157 // NewTypesInfo returns a *types.Info with all maps populated.
158 func NewTypesInfo() *types.Info {
159 return &types.Info{
160 Types: map[ast.Expr]types.TypeAndValue{},
161 Instances: map[*ast.Ident]types.Instance{},
162 Defs: map[*ast.Ident]types.Object{},
163 Uses: map[*ast.Ident]types.Object{},
164 Implicits: map[ast.Node]types.Object{},
165 Selections: map[*ast.SelectorExpr]*types.Selection{},
166 Scopes: map[ast.Node]*types.Scope{},
167 FileVersions: map[*ast.File]string{},
168 }
169 }
170
171 // EnclosingScope returns the innermost block logically enclosing the cursor.
172 func EnclosingScope(info *types.Info, cur inspector.Cursor) *types.Scope {
173 for cur := range cur.Enclosing() {
174 n := cur.Node()
175 // A function's Scope is associated with its FuncType.
176 switch f := n.(type) {
177 case *ast.FuncDecl:
178 n = f.Type
179 case *ast.FuncLit:
180 n = f.Type
181 }
182 if b := info.Scopes[n]; b != nil {
183 return b
184 }
185 }
186 panic("no Scope for *ast.File")
187 }
188
189 // Imports reports whether path is imported by pkg.
190 func Imports(pkg *types.Package, path string) bool {
191 for _, imp := range pkg.Imports() {
192 if imp.Path() == path {
193 return true
194 }
195 }
196 return false
197 }
198
199 // ObjectKind returns a description of the object's kind.
200 //
201 // from objectKind in go/types
202 func ObjectKind(obj types.Object) string {
203 switch obj := obj.(type) {
204 case *types.PkgName:
205 return "package name"
206 case *types.Const:
207 return "constant"
208 case *types.TypeName:
209 if obj.IsAlias() {
210 return "type alias"
211 } else if _, ok := obj.Type().(*types.TypeParam); ok {
212 return "type parameter"
213 } else {
214 return "defined type"
215 }
216 case *types.Var:
217 switch obj.Kind() {
218 case PackageVar:
219 return "package-level variable"
220 case LocalVar:
221 return "local variable"
222 case RecvVar:
223 return "receiver"
224 case ParamVar:
225 return "parameter"
226 case ResultVar:
227 return "result variable"
228 case FieldVar:
229 return "struct field"
230 }
231 case *types.Func:
232 if obj.Signature().Recv() != nil {
233 return "method"
234 } else {
235 return "function"
236 }
237 case *types.Label:
238 return "label"
239 case *types.Builtin:
240 return "built-in function"
241 case *types.Nil:
242 return "untyped nil"
243 }
244 return "unknown symbol"
245 }
246
247 // ImplicitFieldSelections returns the sequence of implicit embedded fields
248 // traversed by the given selection. It skips the final leaf field or method.
249 // The boolean component indicates whether the traversal traversed a pointer.
250 func ImplicitFieldSelections(seln types.Selection) iter.Seq2[*types.Var, bool] {
251 return func(yield func(*types.Var, bool) bool) {
252 var (
253 t = seln.Recv()
254 indices = seln.Index()
255 )
256 for _, idx := range indices[:len(indices)-1] {
257 ptr, isPtr := t.Underlying().(*types.Pointer)
258 if isPtr {
259 t = ptr.Elem()
260 }
261 structType, ok := t.Underlying().(*types.Struct)
262 if !ok {
263 break
264 }
265 field := structType.Field(idx)
266 if !yield(field, isPtr) {
267 break
268 }
269 t = field.Type()
270 }
271 }
272 }