Debian Codegraph @

gopls/internal/golang/identifier.go

raw symbols SCIP
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 golang
6
7 import (
8 "errors"
9 "go/ast"
10 "go/types"
11
12 "golang.org/x/tools/go/ast/inspector"
13 "golang.org/x/tools/gopls/internal/util/cursorutil"
14 "golang.org/x/tools/internal/typesinternal"
15 )
16
17 // ErrNoIdentFound is error returned when no identifier is found at a particular position
18 var ErrNoIdentFound = errors.New("no identifier found")
19
20 // searchForEnclosing returns, given the AST path to a SelectorExpr,
21 // the exported named type of the innermost implicit field selection.
22 //
23 // For example, given "new(A).d" where this is (due to embedding) a
24 // shorthand for "new(A).b.c.d", it returns the named type of c,
25 // if it is exported, otherwise the type of b, or A.
26 func searchForEnclosing(info *types.Info, curIdent inspector.Cursor) *types.TypeName {
27 selector, _ := cursorutil.FirstEnclosing[*ast.SelectorExpr](curIdent)
28 if selector == nil {
29 return nil
30 }
31 sel, ok := info.Selections[selector]
32 if !ok {
33 return nil
34 }
35 recv := typesinternal.Unpointer(sel.Recv())
36
37 // Keep track of the last exported type seen.
38 var exported *types.TypeName
39 if named, ok := types.Unalias(recv).(*types.Named); ok && named.Obj().Exported() {
40 exported = named.Obj()
41 }
42 // We don't want the last element, as that's the field or
43 // method itself.
44 for _, index := range sel.Index()[:len(sel.Index())-1] {
45 if r, ok := recv.Underlying().(*types.Struct); ok {
46 recv = typesinternal.Unpointer(r.Field(index).Type())
47 if named, ok := types.Unalias(recv).(*types.Named); ok && named.Obj().Exported() {
48 exported = named.Obj()
49 }
50 }
51 }
52 return exported
53 }
54
55 // typeToObjects returns the underlying type name objects for the given type.
56 // It unwraps composite types (pointers, slices, etc), and accumulates names
57 // from each parameter of a function type
58 func typeToObjects(typ types.Type) []*types.TypeName {
59 switch typ := typ.(type) {
60 case *types.Alias:
61 return []*types.TypeName{typ.Origin().Obj()}
62 case *types.Named:
63 return []*types.TypeName{typ.Origin().Obj()}
64 case *types.Pointer:
65 return typeToObjects(typ.Elem())
66 case *types.Array:
67 return typeToObjects(typ.Elem())
68 case *types.Slice:
69 return typeToObjects(typ.Elem())
70 case *types.Chan:
71 return typeToObjects(typ.Elem())
72 case *types.Tuple:
73 var res []*types.TypeName
74 for v := range typ.Variables() {
75 res = append(res, typeToObjects(v.Type())...)
76 }
77 return res
78 case *types.Signature:
79 return typeToObjects(typ.Results())
80 case *types.Basic:
81 tname, ok := types.Universe.Lookup(typ.Name()).(*types.TypeName)
82 if !ok {
83 return nil
84 }
85 return []*types.TypeName{tname}
86 default:
87 return nil
88 }
89 }