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