Debian Codegraph @

gopls/internal/golang/type_definition.go

raw symbols SCIP
1 // Copyright 2023 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 "context"
9 "fmt"
10 "go/ast"
11 "go/types"
12
13 "golang.org/x/tools/go/ast/edge"
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/file"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/internal/astutil"
18 "golang.org/x/tools/internal/event"
19 )
20
21 // TypeDefinition handles the textDocument/typeDefinition request for Go files.
22 func TypeDefinition(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.Location, error) {
23 ctx, done := event.Start(ctx, "golang.TypeDefinition")
24 defer done()
25
26 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
27 if err != nil {
28 return nil, err
29 }
30 start, end, err := pgf.RangePos(rng)
31 if err != nil {
32 return nil, err
33 }
34 cur, _, _, _ := astutil.Select(pgf.Cursor(), start, end) // can't fail (start, end are within File)
35
36 // Find innermost enclosing expression that has a type.
37 // It needn't be an identifier.
38 var (
39 info = pkg.TypesInfo()
40 t types.Type
41 )
42 for cur := range cur.Enclosing() {
43 expr, ok := cur.Node().(ast.Expr)
44 if !ok {
45 continue
46 }
47
48 // edge case: switch id := expr.(type) {}
49 // id has no type; use expr instead.
50 if cur.ParentEdgeKind() == edge.AssignStmt_Lhs &&
51 cur.Parent().ParentEdgeKind() == edge.TypeSwitchStmt_Assign {
52 expr = cur.Parent().Node().(*ast.AssignStmt).Rhs[0].(*ast.TypeAssertExpr).X
53 }
54
55 if id, ok := expr.(*ast.Ident); ok {
56 if obj := info.ObjectOf(id); obj != nil {
57 t = obj.Type()
58 }
59 } else {
60 t = info.TypeOf(expr)
61 }
62 if t != nil {
63 break
64 }
65 }
66 if t == nil {
67 return nil, fmt.Errorf("no enclosing expression has a type")
68 }
69 tnames := typeToObjects(t)
70 if len(tnames) == 0 {
71 return nil, fmt.Errorf("cannot find type name(s) from type %s", t)
72 }
73
74 var locs []protocol.Location
75 for _, t := range tnames {
76 loc, err := ObjectLocation(ctx, pkg.FileSet(), snapshot, t)
77 if err != nil {
78 return nil, err
79 }
80 locs = append(locs, loc)
81 }
82
83 return locs, nil
84 }