.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.1.1-0.20210319172145-bda8f5cee399 / 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                 return result, err
102         }
103         path := pathEnclosingObjNode(file, pos)
104         if path == nil {
105                 return nil, ErrNoIdentFound
106         }
107
108         qf := Qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo())
109
110         ident, _ := path[0].(*ast.Ident)
111         if ident == nil {
112                 return nil, ErrNoIdentFound
113         }
114         // Special case for package declarations, since they have no
115         // corresponding types.Object.
116         if ident == file.Name {
117                 rng, err := posToMappedRange(snapshot, pkg, file.Name.Pos(), file.Name.End())
118                 if err != nil {
119                         return nil, err
120                 }
121                 var declAST *ast.File
122                 for _, pgf := range pkg.CompiledGoFiles() {
123                         if pgf.File.Doc != nil {
124                                 declAST = pgf.File
125                         }
126                 }
127                 // If there's no package documentation, just use current file.
128                 if declAST == nil {
129                         declAST = file
130                 }
131                 declRng, err := posToMappedRange(snapshot, pkg, declAST.Name.Pos(), declAST.Name.End())
132                 if err != nil {
133                         return nil, err
134                 }
135                 return &IdentifierInfo{
136                         Name:        file.Name.Name,
137                         ident:       file.Name,
138                         MappedRange: rng,
139                         pkg:         pkg,
140                         qf:          qf,
141                         Snapshot:    snapshot,
142                         Declaration: Declaration{
143                                 node:        declAST.Name,
144                                 MappedRange: []MappedRange{declRng},
145                         },
146                 }, nil
147         }
148
149         result := &IdentifierInfo{
150                 Snapshot:  snapshot,
151                 qf:        qf,
152                 pkg:       pkg,
153                 ident:     ident,
154                 enclosing: searchForEnclosing(pkg.GetTypesInfo(), path),
155         }
156
157         result.Name = result.ident.Name
158         var err error
159         if result.MappedRange, err = posToMappedRange(snapshot, pkg, result.ident.Pos(), result.ident.End()); err != nil {
160                 return nil, err
161         }
162
163         result.Declaration.obj = pkg.GetTypesInfo().ObjectOf(result.ident)
164         if result.Declaration.obj == nil {
165                 // If there was no types.Object for the declaration, there might be an
166                 // implicit local variable declaration in a type switch.
167                 if objs, typ := typeSwitchImplicits(pkg, path); len(objs) > 0 {
168                         // There is no types.Object for the declaration of an implicit local variable,
169                         // but all of the types.Objects associated with the usages of this variable can be
170                         // used to connect it back to the declaration.
171                         // Preserve the first of these objects and treat it as if it were the declaring object.
172                         result.Declaration.obj = objs[0]
173                         result.Declaration.typeSwitchImplicit = typ
174                 } else {
175                         // Probably a type error.
176                         return nil, errors.Errorf("%w for ident %v", errNoObjectFound, result.Name)
177                 }
178         }
179
180         // Handle builtins separately.
181         if result.Declaration.obj.Parent() == types.Universe {
182                 builtin, err := snapshot.BuiltinPackage(ctx)
183                 if err != nil {
184                         return nil, err
185                 }
186                 builtinObj := builtin.Package.Scope.Lookup(result.Name)
187                 if builtinObj == nil {
188                         return nil, fmt.Errorf("no builtin object for %s", result.Name)
189                 }
190                 decl, ok := builtinObj.Decl.(ast.Node)
191                 if !ok {
192                         return nil, errors.Errorf("no declaration for %s", result.Name)
193                 }
194                 result.Declaration.node = decl
195
196                 // The builtin package isn't in the dependency graph, so the usual
197                 // utilities won't work here.
198                 rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, decl.Pos(), decl.Pos()+token.Pos(len(result.Name)))
199                 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
200                 return result, nil
201         }
202
203         // (error).Error is a special case of builtin. Lots of checks to confirm
204         // that this is the builtin Error.
205         if obj := result.Declaration.obj; obj.Parent() == nil && obj.Pkg() == nil && obj.Name() == "Error" {
206                 if _, ok := obj.Type().(*types.Signature); ok {
207                         builtin, err := snapshot.BuiltinPackage(ctx)
208                         if err != nil {
209                                 return nil, err
210                         }
211                         // Look up "error" and then navigate to its only method.
212                         // The Error method does not appear in the builtin package's scope.log.Pri
213                         const errorName = "error"
214                         builtinObj := builtin.Package.Scope.Lookup(errorName)
215                         if builtinObj == nil {
216                                 return nil, fmt.Errorf("no builtin object for %s", errorName)
217                         }
218                         decl, ok := builtinObj.Decl.(ast.Node)
219                         if !ok {
220                                 return nil, errors.Errorf("no declaration for %s", errorName)
221                         }
222                         spec, ok := decl.(*ast.TypeSpec)
223                         if !ok {
224                                 return nil, fmt.Errorf("no type spec for %s", errorName)
225                         }
226                         iface, ok := spec.Type.(*ast.InterfaceType)
227                         if !ok {
228                                 return nil, fmt.Errorf("%s is not an interface", errorName)
229                         }
230                         if iface.Methods.NumFields() != 1 {
231                                 return nil, fmt.Errorf("expected 1 method for %s, got %v", errorName, iface.Methods.NumFields())
232                         }
233                         method := iface.Methods.List[0]
234                         if len(method.Names) != 1 {
235                                 return nil, fmt.Errorf("expected 1 name for %v, got %v", method, len(method.Names))
236                         }
237                         name := method.Names[0].Name
238                         result.Declaration.node = method
239                         rng := NewMappedRange(snapshot.FileSet(), builtin.ParsedFile.Mapper, method.Pos(), method.Pos()+token.Pos(len(name)))
240                         result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
241                         return result, nil
242                 }
243         }
244
245         // If the original position was an embedded field, we want to jump
246         // to the field's type definition, not the field's definition.
247         if v, ok := result.Declaration.obj.(*types.Var); ok && v.Embedded() {
248                 // types.Info.Uses contains the embedded field's *types.TypeName.
249                 if typeName := pkg.GetTypesInfo().Uses[ident]; typeName != nil {
250                         result.Declaration.obj = typeName
251                 }
252         }
253
254         rng, err := objToMappedRange(snapshot, pkg, result.Declaration.obj)
255         if err != nil {
256                 return nil, err
257         }
258         result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
259
260         if result.Declaration.node, err = objToDecl(ctx, snapshot, pkg, result.Declaration.obj); err != nil {
261                 return nil, err
262         }
263         typ := pkg.GetTypesInfo().TypeOf(result.ident)
264         if typ == nil {
265                 return result, nil
266         }
267
268         result.Type.Object = typeToObject(typ)
269         if result.Type.Object != nil {
270                 // Identifiers with the type "error" are a special case with no position.
271                 if hasErrorType(result.Type.Object) {
272                         return result, nil
273                 }
274                 if result.Type.MappedRange, err = objToMappedRange(snapshot, pkg, result.Type.Object); err != nil {
275                         return nil, err
276                 }
277         }
278         return result, nil
279 }
280
281 func searchForEnclosing(info *types.Info, path []ast.Node) types.Type {
282         for _, n := range path {
283                 switch n := n.(type) {
284                 case *ast.SelectorExpr:
285                         if sel, ok := info.Selections[n]; ok {
286                                 recv := Deref(sel.Recv())
287
288                                 // Keep track of the last exported type seen.
289                                 var exported types.Type
290                                 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
291                                         exported = named
292                                 }
293                                 // We don't want the last element, as that's the field or
294                                 // method itself.
295                                 for _, index := range sel.Index()[:len(sel.Index())-1] {
296                                         if r, ok := recv.Underlying().(*types.Struct); ok {
297                                                 recv = Deref(r.Field(index).Type())
298                                                 if named, ok := recv.(*types.Named); ok && named.Obj().Exported() {
299                                                         exported = named
300                                                 }
301                                         }
302                                 }
303                                 return exported
304                         }
305                 case *ast.CompositeLit:
306                         if t, ok := info.Types[n]; ok {
307                                 return t.Type
308                         }
309                 case *ast.TypeSpec:
310                         if _, ok := n.Type.(*ast.StructType); ok {
311                                 if t, ok := info.Defs[n.Name]; ok {
312                                         return t.Type()
313                                 }
314                         }
315                 }
316         }
317         return nil
318 }
319
320 func typeToObject(typ types.Type) types.Object {
321         switch typ := typ.(type) {
322         case *types.Named:
323                 return typ.Obj()
324         case *types.Pointer:
325                 return typeToObject(typ.Elem())
326         default:
327                 return nil
328         }
329 }
330
331 func hasErrorType(obj types.Object) bool {
332         return types.IsInterface(obj.Type()) && obj.Pkg() == nil && obj.Name() == "error"
333 }
334
335 func objToDecl(ctx context.Context, snapshot Snapshot, srcPkg Package, obj types.Object) (ast.Decl, error) {
336         pgf, _, err := FindPosInPackage(snapshot, srcPkg, obj.Pos())
337         if err != nil {
338                 return nil, err
339         }
340         posToDecl, err := snapshot.PosToDecl(ctx, pgf)
341         if err != nil {
342                 return nil, err
343         }
344         return posToDecl[obj.Pos()], nil
345 }
346
347 // importSpec handles positions inside of an *ast.ImportSpec.
348 func importSpec(snapshot Snapshot, pkg Package, file *ast.File, pos token.Pos) (*IdentifierInfo, error) {
349         var imp *ast.ImportSpec
350         for _, spec := range file.Imports {
351                 if spec.Path.Pos() <= pos && pos < spec.Path.End() {
352                         imp = spec
353                 }
354         }
355         if imp == nil {
356                 return nil, nil
357         }
358         importPath, err := strconv.Unquote(imp.Path.Value)
359         if err != nil {
360                 return nil, errors.Errorf("import path not quoted: %s (%v)", imp.Path.Value, err)
361         }
362         result := &IdentifierInfo{
363                 Snapshot: snapshot,
364                 Name:     importPath,
365                 pkg:      pkg,
366         }
367         if result.MappedRange, err = posToMappedRange(snapshot, pkg, imp.Path.Pos(), imp.Path.End()); err != nil {
368                 return nil, err
369         }
370         // Consider the "declaration" of an import spec to be the imported package.
371         importedPkg, err := pkg.GetImport(importPath)
372         if err != nil {
373                 return nil, err
374         }
375         // Return all of the files in the package as the definition of the import spec.
376         for _, dst := range importedPkg.GetSyntax() {
377                 rng, err := posToMappedRange(snapshot, pkg, dst.Pos(), dst.End())
378                 if err != nil {
379                         return nil, err
380                 }
381                 result.Declaration.MappedRange = append(result.Declaration.MappedRange, rng)
382         }
383
384         result.Declaration.node = imp
385         return result, nil
386 }
387
388 // typeSwitchImplicits returns all the implicit type switch objects that
389 // correspond to the leaf *ast.Ident. It also returns the original type
390 // associated with the identifier (outside of a case clause).
391 func typeSwitchImplicits(pkg Package, path []ast.Node) ([]types.Object, types.Type) {
392         ident, _ := path[0].(*ast.Ident)
393         if ident == nil {
394                 return nil, nil
395         }
396
397         var (
398                 ts     *ast.TypeSwitchStmt
399                 assign *ast.AssignStmt
400                 cc     *ast.CaseClause
401                 obj    = pkg.GetTypesInfo().ObjectOf(ident)
402         )
403
404         // Walk our ancestors to determine if our leaf ident refers to a
405         // type switch variable, e.g. the "a" from "switch a := b.(type)".
406 Outer:
407         for i := 1; i < len(path); i++ {
408                 switch n := path[i].(type) {
409                 case *ast.AssignStmt:
410                         // Check if ident is the "a" in "a := foo.(type)". The "a" in
411                         // this case has no types.Object, so check for ident equality.
412                         if len(n.Lhs) == 1 && n.Lhs[0] == ident {
413                                 assign = n
414                         }
415                 case *ast.CaseClause:
416                         // Check if ident is a use of "a" within a case clause. Each
417                         // case clause implicitly maps "a" to a different types.Object,
418                         // so check if ident's object is the case clause's implicit
419                         // object.
420                         if obj != nil && pkg.GetTypesInfo().Implicits[n] == obj {
421                                 cc = n
422                         }
423                 case *ast.TypeSwitchStmt:
424                         // Look for the type switch that owns our previously found
425                         // *ast.AssignStmt or *ast.CaseClause.
426                         if n.Assign == assign {
427                                 ts = n
428                                 break Outer
429                         }
430
431                         for _, stmt := range n.Body.List {
432                                 if stmt == cc {
433                                         ts = n
434                                         break Outer
435                                 }
436                         }
437                 }
438         }
439         if ts == nil {
440                 return nil, nil
441         }
442         // Our leaf ident refers to a type switch variable. Fan out to the
443         // type switch's implicit case clause objects.
444         var objs []types.Object
445         for _, cc := range ts.Body.List {
446                 if ccObj := pkg.GetTypesInfo().Implicits[cc]; ccObj != nil {
447                         objs = append(objs, ccObj)
448                 }
449         }
450         // The right-hand side of a type switch should only have one
451         // element, and we need to track its type in order to generate
452         // hover information for implicit type switch variables.
453         var typ types.Type
454         if assign, ok := ts.Assign.(*ast.AssignStmt); ok && len(assign.Rhs) == 1 {
455                 if rhs := assign.Rhs[0].(*ast.TypeAssertExpr); ok {
456                         typ = pkg.GetTypesInfo().TypeOf(rhs.X)
457                 }
458         }
459         return objs, typ
460 }