1package tools
2
3import (
4 "cmp"
5 "context"
6 _ "embed"
7 "errors"
8 "fmt"
9 "log/slog"
10 "maps"
11 "path/filepath"
12 "regexp"
13 "slices"
14 "sort"
15 "strings"
16
17 "charm.land/fantasy"
18 "github.com/charmbracelet/crush/internal/lsp"
19 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
20)
21
22type ReferencesParams struct {
23 Symbol string `json:"symbol" description:"The symbol name to search for (e.g., function name, variable name, type name)"`
24 Path string `json:"path,omitempty" description:"The directory to search in. Use a directory/file to narrow down the symbol search. Defaults to the current working directory."`
25}
26
27type referencesTool struct {
28 lspManager *lsp.Manager
29}
30
31const ReferencesToolName = "lsp_references"
32
33//go:embed references.md
34var referencesDescription []byte
35
36func NewReferencesTool(lspManager *lsp.Manager) fantasy.AgentTool {
37 return fantasy.NewAgentTool(
38 ReferencesToolName,
39 string(referencesDescription),
40 func(ctx context.Context, params ReferencesParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
41 if params.Symbol == "" {
42 return fantasy.NewTextErrorResponse("symbol is required"), nil
43 }
44
45 if lspManager.Clients().Len() == 0 {
46 return fantasy.NewTextErrorResponse("no LSP clients available"), nil
47 }
48
49 workingDir := cmp.Or(params.Path, ".")
50
51 matches, _, err := searchFiles(ctx, regexp.QuoteMeta(params.Symbol), workingDir, "", 100)
52 if err != nil {
53 return fantasy.NewTextErrorResponse(fmt.Sprintf("failed to search for symbol: %s", err)), nil
54 }
55
56 if len(matches) == 0 {
57 return fantasy.NewTextResponse(fmt.Sprintf("Symbol '%s' not found", params.Symbol)), nil
58 }
59
60 var allLocations []protocol.Location
61 var allErrs error
62 for _, match := range matches {
63 locations, err := find(ctx, lspManager, params.Symbol, match)
64 if err != nil {
65 if strings.Contains(err.Error(), "no identifier found") {
66 // grep probably matched a comment, string value, or something else that's irrelevant
67 continue
68 }
69 slog.Error("Failed to find references", "error", err, "symbol", params.Symbol, "path", match.path, "line", match.lineNum, "char", match.charNum)
70 allErrs = errors.Join(allErrs, err)
71 continue
72 }
73 allLocations = append(allLocations, locations...)
74 // XXX: should we break here or look for all results?
75 }
76
77 if len(allLocations) > 0 {
78 output := formatReferences(cleanupLocations(allLocations))
79 return fantasy.NewTextResponse(output), nil
80 }
81
82 if allErrs != nil {
83 return fantasy.NewTextErrorResponse(allErrs.Error()), nil
84 }
85 return fantasy.NewTextResponse(fmt.Sprintf("No references found for symbol '%s'", params.Symbol)), nil
86 })
87}
88
89func (r *referencesTool) Name() string {
90 return ReferencesToolName
91}
92
93func find(ctx context.Context, lspManager *lsp.Manager, symbol string, match grepMatch) ([]protocol.Location, error) {
94 absPath, err := filepath.Abs(match.path)
95 if err != nil {
96 return nil, fmt.Errorf("failed to get absolute path: %s", err)
97 }
98
99 var client *lsp.Client
100 for c := range lspManager.Clients().Seq() {
101 if c.HandlesFile(absPath) {
102 client = c
103 break
104 }
105 }
106
107 if client == nil {
108 slog.Warn("No LSP clients to handle", "path", match.path)
109 return nil, nil
110 }
111
112 return client.FindReferences(
113 ctx,
114 absPath,
115 match.lineNum,
116 match.charNum+getSymbolOffset(symbol),
117 true,
118 )
119}
120
121// getSymbolOffset returns the character offset to the actual symbol name
122// in a qualified symbol (e.g., "Bar" in "foo.Bar" or "method" in "Class::method").
123func getSymbolOffset(symbol string) int {
124 // Check for :: separator (Rust, C++, Ruby modules/classes, PHP static).
125 if idx := strings.LastIndex(symbol, "::"); idx != -1 {
126 return idx + 2
127 }
128 // Check for . separator (Go, Python, JavaScript, Java, C#, Ruby methods).
129 if idx := strings.LastIndex(symbol, "."); idx != -1 {
130 return idx + 1
131 }
132 // Check for \ separator (PHP namespaces).
133 if idx := strings.LastIndex(symbol, "\\"); idx != -1 {
134 return idx + 1
135 }
136 return 0
137}
138
139func cleanupLocations(locations []protocol.Location) []protocol.Location {
140 slices.SortFunc(locations, func(a, b protocol.Location) int {
141 if a.URI != b.URI {
142 return strings.Compare(string(a.URI), string(b.URI))
143 }
144 if a.Range.Start.Line != b.Range.Start.Line {
145 return cmp.Compare(a.Range.Start.Line, b.Range.Start.Line)
146 }
147 return cmp.Compare(a.Range.Start.Character, b.Range.Start.Character)
148 })
149 return slices.CompactFunc(locations, func(a, b protocol.Location) bool {
150 return a.URI == b.URI &&
151 a.Range.Start.Line == b.Range.Start.Line &&
152 a.Range.Start.Character == b.Range.Start.Character
153 })
154}
155
156func groupByFilename(locations []protocol.Location) map[string][]protocol.Location {
157 files := make(map[string][]protocol.Location)
158 for _, loc := range locations {
159 path, err := loc.URI.Path()
160 if err != nil {
161 slog.Error("Failed to convert location URI to path", "uri", loc.URI, "error", err)
162 continue
163 }
164 files[path] = append(files[path], loc)
165 }
166 return files
167}
168
169func formatReferences(locations []protocol.Location) string {
170 fileRefs := groupByFilename(locations)
171 files := slices.Collect(maps.Keys(fileRefs))
172 sort.Strings(files)
173
174 var output strings.Builder
175 output.WriteString(fmt.Sprintf("Found %d reference(s) in %d file(s):\n\n", len(locations), len(files)))
176
177 for _, file := range files {
178 refs := fileRefs[file]
179 output.WriteString(fmt.Sprintf("%s (%d reference(s)):\n", file, len(refs)))
180 for _, ref := range refs {
181 line := ref.Range.Start.Line + 1
182 char := ref.Range.Start.Character + 1
183 output.WriteString(fmt.Sprintf(" Line %d, Column %d\n", line, char))
184 }
185 output.WriteString("\n")
186 }
187
188 return output.String()
189}