Debian Codegraph @

gopls/internal/golang/completion/util.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 completion
6
7 import (
8 "go/ast"
9 "go/token"
10 "go/types"
11 "slices"
12
13 "golang.org/x/tools/go/types/typeutil"
14 "golang.org/x/tools/gopls/internal/golang"
15 "golang.org/x/tools/gopls/internal/protocol"
16 "golang.org/x/tools/gopls/internal/util/safetoken"
17 "golang.org/x/tools/internal/diff"
18 "golang.org/x/tools/internal/typeparams"
19 )
20
21 // exprAtPos returns the index of the expression containing pos.
22 func exprAtPos(pos token.Pos, args []ast.Expr) int {
23 for i, expr := range args {
24 if expr.Pos() <= pos && pos <= expr.End() {
25 return i
26 }
27 }
28 return len(args)
29 }
30
31 // eachField invokes fn for each field that can be selected from a
32 // value of type T.
33 func eachField(T types.Type, fn func(*types.Var)) {
34 // TODO(adonovan): this algorithm doesn't exclude ambiguous
35 // selections that match more than one field/method.
36 // types.NewSelectionSet should do that for us.
37
38 // for termination on recursive types
39 var seen typeutil.Map
40
41 var visit func(T types.Type)
42 visit = func(T types.Type) {
43 // T may be a Struct, optionally Named, with an optional
44 // Pointer (with optional Aliases at every step!):
45 // Consider: type T *struct{ f int }; _ = T(nil).f
46 if T, ok := typeparams.Deref(T).Underlying().(*types.Struct); ok {
47 if seen.At(T) != nil {
48 return
49 }
50
51 for f := range T.Fields() {
52 fn(f)
53 if f.Anonymous() {
54 seen.Set(T, true)
55 visit(f.Type())
56 }
57 }
58 }
59 }
60 visit(T)
61 }
62
63 // typeIsValid reports whether typ doesn't contain any Invalid types.
64 func typeIsValid(typ types.Type) bool {
65 // Check named types separately, because we don't want
66 // to call Underlying() on them to avoid problems with recursive types.
67 if _, ok := types.Unalias(typ).(*types.Named); ok {
68 return true
69 }
70
71 switch typ := typ.Underlying().(type) {
72 case *types.Basic:
73 return typ.Kind() != types.Invalid
74 case *types.Array:
75 return typeIsValid(typ.Elem())
76 case *types.Slice:
77 return typeIsValid(typ.Elem())
78 case *types.Pointer:
79 return typeIsValid(typ.Elem())
80 case *types.Map:
81 return typeIsValid(typ.Key()) && typeIsValid(typ.Elem())
82 case *types.Chan:
83 return typeIsValid(typ.Elem())
84 case *types.Signature:
85 return typeIsValid(typ.Params()) && typeIsValid(typ.Results())
86 case *types.Tuple:
87 for v := range typ.Variables() {
88 if !typeIsValid(v.Type()) {
89 return false
90 }
91 }
92 return true
93 case *types.Struct, *types.Interface:
94 // Don't bother checking structs, interfaces for validity.
95 return true
96 default:
97 return false
98 }
99 }
100
101 // resolveInvalid traverses the node of the AST that defines the scope
102 // containing the declaration of obj, and attempts to find a user-friendly
103 // name for its invalid type. The resulting Object and its Type are fake.
104 func resolveInvalid(fset *token.FileSet, obj types.Object, node ast.Node, info *types.Info) types.Object {
105 var resultExpr ast.Expr
106 ast.Inspect(node, func(node ast.Node) bool {
107 switch n := node.(type) {
108 case *ast.ValueSpec:
109 for _, name := range n.Names {
110 if info.Defs[name] == obj {
111 resultExpr = n.Type
112 }
113 }
114 return false
115 case *ast.Field: // This case handles parameters and results of a FuncDecl or FuncLit.
116 for _, name := range n.Names {
117 if info.Defs[name] == obj {
118 resultExpr = n.Type
119 }
120 }
121 return false
122 default:
123 return true
124 }
125 })
126 // Construct a fake type for the object and return a fake object with this type.
127 typename := golang.FormatNode(fset, resultExpr)
128 typ := types.NewNamed(types.NewTypeName(token.NoPos, obj.Pkg(), typename, nil), types.Typ[types.Invalid], nil)
129 v := types.NewVar(obj.Pos(), obj.Pkg(), obj.Name(), typ)
130 v.SetKind(types.PackageVar)
131 return v
132 }
133
134 // TODO(adonovan): inline these.
135 func isVar(obj types.Object) bool { return is[*types.Var](obj) }
136 func isTypeName(obj types.Object) bool { return is[*types.TypeName](obj) }
137 func isFunc(obj types.Object) bool { return is[*types.Func](obj) }
138 func isPkgName(obj types.Object) bool { return is[*types.PkgName](obj) }
139
140 // isPointer reports whether T is a Pointer, or an alias of one.
141 // It returns false for a Named type whose Underlying is a Pointer.
142 //
143 // TODO(adonovan): shouldn't this use CoreType(T)?
144 func isPointer(T types.Type) bool { return is[*types.Pointer](types.Unalias(T)) }
145
146 // isEmptyInterface whether T is a (possibly Named or Alias) empty interface
147 // type, such that every type is assignable to T.
148 //
149 // isEmptyInterface returns false for type parameters, since they have
150 // different assignability rules.
151 func isEmptyInterface(T types.Type) bool {
152 if _, ok := T.(*types.TypeParam); ok {
153 return false
154 }
155 intf, _ := T.Underlying().(*types.Interface)
156 return intf != nil && intf.Empty()
157 }
158
159 func isUntyped(T types.Type) bool {
160 if basic, ok := types.Unalias(T).(*types.Basic); ok {
161 return basic.Info()&types.IsUntyped > 0
162 }
163 return false
164 }
165
166 func deslice(T types.Type) types.Type {
167 if slice, ok := T.Underlying().(*types.Slice); ok {
168 return slice.Elem()
169 }
170 return nil
171 }
172
173 // enclosingSelector returns the enclosing *ast.SelectorExpr when pos is in the
174 // selector.
175 func enclosingSelector(path []ast.Node, pos token.Pos) *ast.SelectorExpr {
176 if len(path) == 0 {
177 return nil
178 }
179
180 if sel, ok := path[0].(*ast.SelectorExpr); ok {
181 return sel
182 }
183
184 // TODO(adonovan): consider ast.ParenExpr (e.g. (x).name)
185 if _, ok := path[0].(*ast.Ident); ok && len(path) > 1 {
186 if sel, ok := path[1].(*ast.SelectorExpr); ok && pos >= sel.Sel.Pos() {
187 return sel
188 }
189 }
190
191 return nil
192 }
193
194 // enclosingDeclLHS returns LHS idents from containing value spec or
195 // assign statement.
196 func enclosingDeclLHS(path []ast.Node) []*ast.Ident {
197 for _, n := range path {
198 switch n := n.(type) {
199 case *ast.ValueSpec:
200 return n.Names
201 case *ast.AssignStmt:
202 ids := make([]*ast.Ident, 0, len(n.Lhs))
203 for _, e := range n.Lhs {
204 if id, ok := e.(*ast.Ident); ok {
205 ids = append(ids, id)
206 }
207 }
208 return ids
209 }
210 }
211
212 return nil
213 }
214
215 // exprObj returns the types.Object associated with the *ast.Ident or
216 // *ast.SelectorExpr e.
217 func exprObj(info *types.Info, e ast.Expr) types.Object {
218 var ident *ast.Ident
219 switch expr := e.(type) {
220 case *ast.Ident:
221 ident = expr
222 case *ast.SelectorExpr:
223 ident = expr.Sel
224 default:
225 return nil
226 }
227
228 return info.ObjectOf(ident)
229 }
230
231 // typeConversion returns the type being converted to if call is a type
232 // conversion expression.
233 func typeConversion(call *ast.CallExpr, info *types.Info) types.Type {
234 // Type conversion (e.g. "float64(foo)").
235 if fun, _ := exprObj(info, call.Fun).(*types.TypeName); fun != nil {
236 return fun.Type()
237 }
238
239 return nil
240 }
241
242 // fieldsAccessible returns whether s has at least one field accessible by p.
243 func fieldsAccessible(s *types.Struct, p *types.Package) bool {
244 for f := range s.Fields() {
245 if f.Exported() || f.Pkg() == p {
246 return true
247 }
248 }
249 return false
250 }
251
252 // prevStmt returns the statement that precedes the statement containing pos.
253 // For example:
254 //
255 // foo := 1
256 // bar(1 + 2<>)
257 //
258 // If "<>" is pos, prevStmt returns "foo := 1"
259 func prevStmt(pos token.Pos, path []ast.Node) ast.Stmt {
260 var blockLines []ast.Stmt
261 for i := 0; i < len(path) && blockLines == nil; i++ {
262 switch n := path[i].(type) {
263 case *ast.BlockStmt:
264 blockLines = n.List
265 case *ast.CommClause:
266 blockLines = n.Body
267 case *ast.CaseClause:
268 blockLines = n.Body
269 }
270 }
271
272 for _, stmt := range slices.Backward(blockLines) {
273 if stmt.End() < pos {
274 return stmt
275 }
276 }
277
278 return nil
279 }
280
281 // isBasicKind returns whether t is a basic type of kind k.
282 func isBasicKind(t types.Type, k types.BasicInfo) bool {
283 b, _ := t.Underlying().(*types.Basic)
284 return b != nil && b.Info()&k > 0
285 }
286
287 func (c *completer) editText(from, to token.Pos, newText string) ([]protocol.TextEdit, error) {
288 start, end, err := safetoken.Offsets(c.pgf.Tok, from, to)
289 if err != nil {
290 return nil, err // can't happen: from/to came from c
291 }
292 return protocol.EditsFromDiffEdits(c.mapper, []diff.Edit{{
293 Start: start,
294 End: end,
295 New: newText,
296 }})
297 }
298
299 // assignableTo is like types.AssignableTo, but returns false if
300 // either type is invalid.
301 func assignableTo(x, to types.Type) bool {
302 if types.Unalias(x) == types.Typ[types.Invalid] ||
303 types.Unalias(to) == types.Typ[types.Invalid] {
304 return false
305 }
306
307 return types.AssignableTo(x, to)
308 }
309
310 // convertibleTo is like types.ConvertibleTo, but returns false if
311 // either type is invalid.
312 func convertibleTo(x, to types.Type) bool {
313 if types.Unalias(x) == types.Typ[types.Invalid] ||
314 types.Unalias(to) == types.Typ[types.Invalid] {
315 return false
316 }
317
318 return types.ConvertibleTo(x, to)
319 }