Debian Codegraph @

gopls/internal/mcp/symbol_references.go

raw symbols SCIP
1 // Copyright 2025 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 package mcp
5
6 import (
7 "context"
8 "fmt"
9 "go/ast"
10 "go/parser"
11 "go/token"
12 "go/types"
13
14 "github.com/modelcontextprotocol/go-sdk/mcp"
15 "golang.org/x/tools/gopls/internal/cache"
16 "golang.org/x/tools/gopls/internal/cache/parsego"
17 "golang.org/x/tools/gopls/internal/file"
18 "golang.org/x/tools/gopls/internal/golang"
19 "golang.org/x/tools/gopls/internal/protocol"
20 )
21
22 // symbolReferencesParams defines the parameters for the "go_symbol_references"
23 // tool.
24 type symbolReferencesParams struct {
25 File string `json:"file" jsonschema:"the absolute path to the file containing the symbol"`
26 Symbol string `json:"symbol" jsonschema:"the symbol or qualified symbol"`
27 }
28
29 // symbolReferencesHandler is the handler for the "go_symbol_references" tool.
30 // It finds all references to the requested symbol and describes their
31 // locations.
32 func (h *handler) symbolReferencesHandler(ctx context.Context, req *mcp.CallToolRequest, params symbolReferencesParams) (*mcp.CallToolResult, any, error) {
33 countGoSymbolReferencesMCP.Inc()
34 fh, snapshot, release, err := h.fileOf(ctx, params.File)
35 if err != nil {
36 return nil, nil, err
37 }
38 defer release()
39
40 if snapshot.FileKind(fh) != file.Go {
41 return nil, nil, fmt.Errorf("can't provide references for non-Go files")
42 }
43
44 loc, err := symbolLocation(ctx, snapshot, fh.URI(), params.Symbol)
45 if err != nil {
46 return nil, nil, err
47 }
48 declFH, err := snapshot.ReadFile(ctx, loc.URI)
49 if err != nil {
50 return nil, nil, err
51 }
52 refs, err := golang.References(ctx, snapshot, declFH, loc.Range, true)
53 if err != nil {
54 return nil, nil, err
55 }
56 formatted, err := formatReferences(ctx, snapshot, refs)
57 return formatted, nil, err
58 }
59
60 // symbolLocation returns the protocol.Location of the given symbol within the file uri, or an error if it cannot be located.
61 func symbolLocation(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, symbol string) (protocol.Location, error) {
62 // Parse and extract names before type checking, to fail fast in the case of
63 // invalid inputs.
64 e, err := parser.ParseExpr(symbol)
65 if err != nil {
66 return protocol.Location{}, fmt.Errorf("\"symbol\" failed to parse: %v", err)
67 }
68 path, err := extractPath(e)
69 if err != nil {
70 return protocol.Location{}, err
71 }
72
73 pkg, pgf, err := golang.NarrowestPackageForFile(ctx, snapshot, uri)
74 if err != nil {
75 return protocol.Location{}, err
76 }
77
78 target, err := resolveSymbol(path, pkg, pgf)
79 if err != nil {
80 return protocol.Location{}, err
81 }
82
83 loc, err := golang.ObjectLocation(ctx, pkg.FileSet(), snapshot, target)
84 if err != nil {
85 return protocol.Location{}, fmt.Errorf("finding symbol location: %v", err)
86 }
87 return loc, nil
88 }
89
90 // extractPath extracts the 'path' of names from e, which must be of the form
91 // a, a.b, or a.b.c.
92 //
93 // If a nil error is returned, the resulting path is either length 1, 2, or 3.
94 func extractPath(e ast.Expr) ([]string, error) {
95 switch e := e.(type) {
96 case *ast.Ident:
97 return []string{e.Name}, nil
98 case *ast.SelectorExpr:
99 switch x := e.X.(type) {
100 case *ast.Ident:
101 // Qualified identifier 'a.b', where a is a package or receiver.
102 return []string{x.Name, e.Sel.Name}, nil
103 case *ast.SelectorExpr:
104 // Imported field or method a.b.c: a must be a package name.
105 if x2, ok := x.X.(*ast.Ident); ok {
106 return []string{x2.Name, x.Sel.Name, e.Sel.Name}, nil
107 }
108 }
109 }
110 return nil, fmt.Errorf("invalid qualified symbol: expected a.b or a.b.c")
111 }
112
113 // resolveSymbol resolves the types.Object for the given qualified path, which
114 // must be of length 1, 2, or 3:
115 // - For length 1 paths, the symbol is a name in the file scope.
116 // - For length 2 paths, the symbol is either field, method, or imported symbol.
117 // - For length 3 paths, the symbol is a field or method on an important object.
118 func resolveSymbol(path []string, pkg *cache.Package, pgf *parsego.File) (types.Object, error) {
119 fileScope, ok := pkg.TypesInfo().Scopes[pgf.File]
120 if !ok {
121 return nil, fmt.Errorf("internal error: no scope for file")
122 }
123
124 switch len(path) {
125 case 1:
126 _, target := fileScope.LookupParent(path[0], token.NoPos)
127 if target == nil {
128 return nil, fmt.Errorf("failed to resolve name %q", path[0])
129 }
130 return target, nil
131 case 2:
132 switch _, obj := fileScope.LookupParent(path[0], token.NoPos); obj := obj.(type) {
133 case *types.PkgName:
134 target := obj.Imported().Scope().Lookup(path[1])
135 if target == nil {
136 return nil, fmt.Errorf("failed to resolve member %q of %q", path[1], path[0])
137 }
138 return target, nil
139 case nil:
140 return nil, fmt.Errorf("failed to resolve name %q", path[0])
141 default:
142 target, _, _ := types.LookupFieldOrMethod(obj.Type(), true, pkg.Types(), path[1])
143 if target == nil {
144 return nil, fmt.Errorf("failed to resolve member %q of %q", path[1], path[0])
145 }
146 return target, nil
147 }
148 case 3:
149 // Imported field or method a.b.c: a must be a package name.
150 obj := fileScope.Lookup(path[0])
151 p, ok := obj.(*types.PkgName)
152 if !ok {
153 return nil, fmt.Errorf("invalid qualified symbol: %q must be a package (got %T)", path[0], obj)
154 }
155 recv := p.Imported().Scope().Lookup(path[1])
156 if recv == nil {
157 return nil, fmt.Errorf("invalid qualified symbol: could not find %q in package %q", path[1], path[0])
158 }
159 target, _, _ := types.LookupFieldOrMethod(recv.Type(), true, pkg.Types(), path[2])
160 if target == nil {
161 return nil, fmt.Errorf("failed to resolve member %q of %q", path[2], path[1])
162 }
163 return target, nil
164 }
165 panic("unreachable")
166 }