Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201105173854-bc9fc8d8c4bc / internal / lsp / source / identifier.go
1 // Copyright 2018 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 source
6
7 import (
8         "context"
9         "fmt"
10         "go/ast"
11         "go/token"
12         "go/types"
13         "sort"
14         "strconv"
15
16         "golang.org/x/tools/internal/event"
17         "golang.org/x/tools/internal/lsp/protocol"
18         errors "golang.org/x/xerrors"
19 )
20
21 // IdentifierInfo holds information about an identifier in Go source.
22 type IdentifierInfo struct {
23         Name     string
24         Snapshot Snapshot
25         MappedRange
26
27         Type struct {
28                 MappedRange
29                 Object types.Object
30         }
31
32         Declaration Declaration
33
34         ident *ast.Ident
35
36         // enclosing is an expression used to determine the link anchor for an
37         // identifier. If it's a named type, it should be exported.
38         enclosing types.Type
39
40         pkg Package
41         qf  types.Qualifier
42 }
43
44 type Declaration struct {
45         MappedRange []MappedRange
46         node        ast.Node
47         obj         types.Object
48
49         // typeSwitchImplicit indicates that the declaration is in an implicit
50         // type switch. Its type is the type of the variable on the right-hand
51         // side of the type switch.
52         typeSwitchImplicit types.Type
53 }
54
55 // Identifier returns identifier information for a position
56 // in a file, accounting for a potentially incomplete selector.
57 func Identifier(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) (*IdentifierInfo, error) {
58         ctx, done := event.Start(ctx, "source.Identifier")
59         defer done()
60
61         pkgs, err := snapshot.PackagesForFile(ctx, fh.URI(), TypecheckAll)
62         if err != nil {
63                 return nil, err
64         }
65         if len(pkgs) == 0 {
66                 return nil, fmt.Errorf("no packages for file %v", fh.URI())
67         }
68         sort.Slice(pkgs, func(i, j int) bool {
69                 return len(pkgs[i].CompiledGoFiles()) < len(pkgs[j].CompiledGoFiles())
70         })
71         var findErr error
72         for _, pkg := range pkgs {
73                 pgf, err := pkg.File(fh.URI())
74                 if err != nil {
75                         return nil, err
76                 }
77                 spn, err := pgf.Mapper.PointSpan(pos)
78                 if err != nil {
79                         return nil, err
80                 }
81                 rng, err := spn.Range(pgf.Mapper.Converter)
82                 if err != nil {
83                         return nil, err
84                 }
85                 var ident *IdentifierInfo
86                 ident, findErr = findIdentifier(ctx, snapshot, pkg, pgf.File, rng.Start)
87                 if findErr == nil {
88                         return ident, nil
89                 }
90         }
91         return nil, findErr
92 }
93
94 // ErrNoIdentFound is error returned when no identifer is found at a particular position
95 var ErrNoIdentFound = errors.New("no identifier found")
96
97 func findIdentifier(ctx context.Context, snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) {
98         // Handle import specs separately, as there is no formal position for a
99         // package declaration.
100         if result, err := importSpec(snapshot, pkg, file, pos); result != nil || err != nil {
101                 if snapshot.View().Options().ImportShortcut.ShowDefinition() {
102                         return result, err
103                 }
104                 return nil, nil
105         }
106         path := pathEnclosingObjNode(file, pos)
107         if path == nil {
108                 return nil, ErrNoIdentFound
109         }
110
111         qf := Qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo())
112
113         ident, _ := path[0].(*ast.Ident)
114         if ident == nil {
115                 return nil, ErrNoIdentFound
116         }
117         // Special case for package declarations, since they have no
118         // corresponding types.Object.
119         if ident == file.Name {
120                 rng, err := posToMappedRange(snapshot, pkg, file.Name.Pos(), file.Name.End())
121                 if err != nil {
122                         return nil, err
123                 }
124                 var declAST *ast.File
125                 for _, pgf := range pkg.CompiledGoFiles() {
126                         if pgf.File.Doc != nil {
127                                 declAST = pgf.File
128                         }
129                 }
130                 // If there's no package documentation, just use current file.
131                 if declAST == nil {
132                         declAST = file
133                 }
134                 declRng, err := posToMappedRange(snapshot, pkg, declAST.Name.Pos(), declAST.Name.End())
135                 if err != nil {
136                         return nil, err
137                 }
138                 return &IdentifierInfo{
139                         Name:        file.Name.Name,
140                         ident:       file.Name,
141                         MappedRange: rng,
142                         pkg:         pkg,
143                         qf:          qf,
144                         Snapshot:    snapshot,
145                         Declaration: Declaration{
146                                 node:        declAST.Name,
147                                 MappedRange: []MappedRange{declRng},
148                         },
149                 }, nil
150         }
151
152         result := &IdentifierInfo{
153                 Snapshot:  snapshot,
154                 qf:        qf,
155                 pkg:       pkg,
156                 ident:     ident,
157                 enclosing: searchForEnclosing(pkg.GetTypesInfo(), path),
158         }
159
160         var wasEmbeddedField bool
161         for _, n := range path[1:] {
162                 if field, ok := n.(*ast.Field); ok {
163                         wasEmbeddedField = len(field.Names) == 0
164                         break
165                 }
166         }
167
168         result.Name = result.ident.Name
169         var err error
170         if result.MappedRange, err = posToMappedRange(snapshot, pkg, result.ident.Pos(), result.ident.End()); err != nil {
171                 return nil, err
172         }
173
174         result.Declaration.obj = pkg.GetTypesInfo().ObjectOf(result.ident)
175         if result.Declaration.obj == nil {
176                 // If there was no types.Object for the declaration, there might be an
177                 // implicit local variable declaration in a type switch.
178                 if objs, typ := typeSwitchImplicits(pkg, path); len(objs) > 0 {
179                         // There is no types.Object for the declaration of an implicit local variable,
180                         // but all of the types.Objects associated with the usages of this variable can be
181                         // used to connect it back to the declaration.
182                         // Preserve the first of these objects and treat it as if it were the declaring object.
183                         result.Declaration.obj = objs[0]
184                         result.Declaration.typeSwitchImplicit = typ
185                 } else {
186                         // Probably a type error.
187                         return nil, errors.Errorf("%w for ident %v", errNoObjectFound, result.Name)
188                 }
189         }
190
191         // Handle builtins separately.
192         if result.Declaration.obj.Parent() == types.Universe {
193                 builtin, err := snapshot.BuiltinPackage(ctx)
194                 if err != nil {
195                         return nil, err
196                 }
197                 builtinObj := builtin.Package.Scope.Lookup(result.Name)
198                 if builtinObj == nil {
199                         return nil, fmt.Errorf("no builtin object for %s", result.Name)
200                 }
201                 decl, ok := builtinObj.Decl.(ast.Node)
202                 if !ok {
203                         return nil, errors.Errorf("no declaration for %s", result.Name)
204                 }
205                 result.Declaration.node = decl
206
207                 // The builtin package isn't in the dependency graph, so the usual
208                 // utilities won't work here.
209                 rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, decl.Pos(), decl.Pos()+token.Pos(len(result.Name)))
210                 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
211                 return result, nil
212         }
213
214         // (error).Error is a special case of builtin. Lots of checks to confirm
215         // that this is the builtin Error.
216         if obj := result.Declaration.obj; obj.Parent() == nil && obj.Pkg() == nil && obj.Name() == "Error" {
217                 if _, ok := obj.Type().(*types.Signature); ok {
218                         builtin, err := snapshot.BuiltinPackage(ctx)
219                         if err != nil {
220                                 return nil, err
221                         }
222                         // Look up "error" and then navigate to its only method.
223                         // The Error method does not appear in the builtin package's scope.log.Pri
224                         const errorName = "error"
225                         builtinObj := builtin.Package.Scope.Lookup(errorName)
226                         if builtinObj == nil {
227                                 return nil, fmt.Errorf("no builtin object for %s", errorName)
228                         }
229                         decl, ok := builtinObj.Decl.(ast.Node)
230                         if !ok {
231                                 return nil, errors.Errorf("no declaration for %s", errorName)
232                         }
233                         spec, ok := decl.(*ast.TypeSpec)
234                         if !ok {
235                                 return nil, fmt.Errorf("no type spec for %s", errorName)
236                         }
237                         iface, ok := spec.Type.(*ast.InterfaceType)
238                         if !ok {
239                                 return nil, fmt.Errorf("%s is not an interface", errorName)
240                         }
241                         if iface.Methods.NumFields() != 1 {
242                                 return nil, fmt.Errorf("expected 1 method for %s, got %v", errorName, iface.Methods.NumFields())
243                         }
244                         method := iface.Methods.List[0]
245                         if len(method.Names) != 1 {
246                                 return nil, fmt.Errorf("expected 1 name for %v, got %v", method, len(method.Names))
247                         }
248                         name := method.Names[0].Name
249                         result.Declaration.node = method
250                         rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, method.Pos(), method.Pos()+token.Pos(len(name)))
251                         result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
252                         return result, nil
253                 }
254         }
255
256         if wasEmbeddedField {
257                 // The original position was on the embedded field declaration, so we
258                 // try to dig out the type and jump to that instead.
259                 if v, ok := result.Declaration.obj.(*types.Var); ok {
260                         if typObj := typeToObject(v.Type()); typObj != nil {
261                                 result.Declaration.obj = typObj
262                         }
263                 }
264         }
265
266         rng, err := objToMappedRange(snapshot, pkg, result.Declaration.obj)
267         if err != nil {
268                 return nil, err
269         }
270         result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
271
272         if result.Declaration.node, err = objToDecl(ctx, snapshot, pkg, result.Declaration.obj); err != nil {
273                 return nil, err
274         }
275         typ := pkg.GetTypesInfo().TypeOf(result.ident)
276         if typ == nil {
277                 return result, nil
278         }
279
280         result.Type.Object = typeToObject(typ)
281         if result.Type.Object != nil {
282                 // Identifiers with the type "error" are a special case with no position.
283                 if hasErrorType(result.Type.Object) {
284                         return result, nil
285                 }
286                 if result.Type.MappedRange, err = objToMappedRange(snapshot, pkg, result.Type.Object); err != nil {
287                         return nil, err
288                 }
289         }
290         return result, nil
291 }
292
293 func searchForEnclosing(info *types.Info, path []ast.Node) types.Type {
294         for _, n := range path {
295                 switch n := n.(type) {
296                 case *ast.SelectorExpr:
297                         if sel, ok := info.Selections[n]; ok {
298                                 recv := Deref(sel.Recv())
299
300                                 // Keep track of the last exported type seen.
301                                 var exported types.Type
302                                 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
303                                         exported = named
304                                 }
305                                 // We don't want the last element, as that's the field or
306                                 // method itself.
307                                 for _, index := range sel.Index()[:len(sel.Index())-1] {
308                                         if r, ok := recv.Underlying().(*types.Struct); ok {
309                                                 recv = Deref(r.Field(index).Type())
310                                                 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
311                                                         exported = named
312                                                 }
313                                         }
314                                 }
315                                 return exported
316                         }
317                 case *ast.CompositeLit:
318                         if t, ok := info.Types[n]; ok {
319                                 return t.Type
320                         }
321                 case *ast.TypeSpec:
322                         if _, ok := n.Type.(*ast.StructType); ok {
323                                 if t, ok := info.Defs[n.Name]; ok {
324                                         return t.Type()
325                                 }
326                         }
327                 }
328         }
329         return nil
330 }
331
332 func typeToObject(typ types.Type) types.Object {
333         switch typ := typ.(type) {
334         case *types.Named:
335                 return typ.Obj()
336         case *types.Pointer:
337                 return typeToObject(typ.Elem())
338         default:
339                 return nil
340         }
341 }
342
343 func hasErrorType(obj types.Object) bool {
344         return types.IsInterface(obj.Type()) && obj.Pkg() == nil && obj.Name() == "error"
345 }
346
347 func objToDecl(ctx context.Context, snapshot Snapshot, srcPkg Package, obj types.Object) (ast.Decl, error) {
348         pgf, _, err := FindPosInPackage(snapshot, srcPkg, obj.Pos())
349         if err != nil {
350                 return nil, err
351         }
352         posToDecl, err := snapshot.PosToDecl(ctx, pgf)
353         if err != nil {
354                 return nil, err
355         }
356         return posToDecl[obj.Pos()], nil
357 }
358
359 // importSpec handles positions inside of an *ast.ImportSpec.
360 func importSpec(snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) {
361         var imp *ast.ImportSpec
362         for _, spec := range file.Imports {
363                 if spec.Path.Pos() <= pos && pos < spec.Path.End() {
364                         imp = spec
365                 }
366         }
367         if imp == nil {
368                 return nil, nil
369         }
370         importPath, err := strconv.Unquote(imp.Path.Value)
371         if err != nil {
372                 return nil, errors.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err)
373         }
374         result := &IdentifierInfo{
375                 Snapshot: snapshot,
376                 Name:     importPath,
377                 pkg:      pkg,
378         }
379         if result.MappedRange, err = posToMappedRange(snapshot, pkg, imp.Path.Pos(), imp.Path.End()); err != nil {
380                 return nil, err
381         }
382         // Consider the "declaration" of an import spec to be the imported package.
383         importedPkg, err := pkg.GetImport(importPath)
384         if err != nil {
385                 return nil, err
386         }
387         // Return all of the files in the package as the definition of the import spec.
388         for _, dst := range importedPkg.GetSyntax() {
389                 rng, err := posToMappedRange(snapshot, pkg, dst.Pos(), dst.End())
390                 if err != nil {
391                         return nil, err
392                 }
393                 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
394         }
395
396         result.Declaration.node = imp
397         return result, nil
398 }
399
400 // typeSwitchImplicits returns all the implicit type switch objects that
401 // correspond to the leaf *ast.Ident. It also returns the original type
402 // associated with the identifier (outside of a case clause).
403 func typeSwitchImplicits(pkg Package, path []ast.Node) ([]types.Object, types.Type) {
404         ident, _ := path[0].(*ast.Ident)
405         if ident == nil {
406                 return nil, nil
407         }
408
409         var (
410                 ts     *ast.TypeSwitchStmt
411                 assign *ast.AssignStmt
412                 cc     *ast.CaseClause
413                 obj    = pkg.GetTypesInfo().ObjectOf(ident)
414         )
415
416         // Walk our ancestors to determine if our leaf ident refers to a
417         // type switch variable, e.g. the "a" from "switch a := b.(type)".
418 Outer:
419         for i := 1; i < len(path); i++ {
420                 switch n := path[i].(type) {
421                 case *ast.AssignStmt:
422                         // Check if ident is the "a" in "a := foo.(type)". The "a" in
423                         // this case has no types.Object, so check for ident equality.
424                         if len(n.Lhs) == 1 && n.Lhs[0] == ident {
425                                 assign = n
426                         }
427                 case *ast.CaseClause:
428                         // Check if ident is a use of "a" within a case clause. Each
429                         // case clause implicitly maps "a" to a different types.Object,
430                         // so check if ident's object is the case clause's implicit
431                         // object.
432                         if obj != nil && pkg.GetTypesInfo().Implicits[n] == obj {
433                                 cc = n
434                         }
435                 case *ast.TypeSwitchStmt:
436                         // Look for the type switch that owns our previously found
437                         // *ast.AssignStmt or *ast.CaseClause.
438                         if n.Assign == assign {
439                                 ts = n
440                                 break Outer
441                         }
442
443                         for _, stmt := range n.Body.List {
444                                 if stmt == cc {
445                                         ts = n
446                                         break Outer
447                                 }
448                         }
449                 }
450         }
451         if ts == nil {
452                 return nil, nil
453         }
454         // Our leaf ident refers to a type switch variable. Fan out to the
455         // type switch's implicit case clause objects.
456         var objs []types.Object
457         for _, cc := range ts.Body.List {
458                 if ccObj := pkg.GetTypesInfo().Implicits[cc]; ccObj != nil {
459                         objs = append(objs, ccObj)
460                 }
461         }
462         // The right-hand side of a type switch should only have one
463         // element, and we need to track its type in order to generate
464         // hover information for implicit type switch variables.
465         var typ types.Type
466         if assign, ok := ts.Assign.(*ast.AssignStmt); ok && len(assign.Rhs) == 1 {
467                 if rhs := assign.Rhs[0].(*ast.TypeAssertExpr); ok {
468                         typ = pkg.GetTypesInfo().TypeOf(rhs.X)
469                 }
470         }
471         return objs, typ
472 }