| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 18 |
var ErrNoIdentFound = errors.New("no identifier found") |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 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 |
|
| 38 |
var exported *types.TypeName |
| 39 |
if named, ok := types.Unalias(recv).(*types.Named); ok && named.Obj().Exported() { |
| 40 |
exported = named.Obj() |
| 41 |
} |
| 42 |
|
| 43 |
|
| 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 |
|
| 56 |
|
| 57 |
|
| 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 |
} |