1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "maps"
8 "sort"
9 "strings"
10 "time"
11
12 "github.com/charmbracelet/crush/internal/lsp"
13 "github.com/charmbracelet/crush/internal/lsp/protocol"
14)
15
16type DiagnosticsParams struct {
17 FilePath string `json:"file_path"`
18}
19type diagnosticsTool struct {
20 lspClients map[string]*lsp.Client
21}
22
23const (
24 DiagnosticsToolName = "diagnostics"
25 diagnosticsDescription = `Get diagnostics for a file and/or project.
26WHEN TO USE THIS TOOL:
27- Use when you need to check for errors or warnings in your code
28- Helpful for debugging and ensuring code quality
29- Good for getting a quick overview of issues in a file or project
30HOW TO USE:
31- Provide a path to a file to get diagnostics for that file
32- Leave the path empty to get diagnostics for the entire project
33- Results are displayed in a structured format with severity levels
34FEATURES:
35- Displays errors, warnings, and hints
36- Groups diagnostics by severity
37- Provides detailed information about each diagnostic
38LIMITATIONS:
39- Results are limited to the diagnostics provided by the LSP clients
40- May not cover all possible issues in the code
41- Does not provide suggestions for fixing issues
42TIPS:
43- Use in conjunction with other tools for a comprehensive code review
44- Combine with the LSP client for real-time diagnostics
45`
46)
47
48func NewDiagnosticsTool(lspClients map[string]*lsp.Client) BaseTool {
49 return &diagnosticsTool{
50 lspClients,
51 }
52}
53
54func (b *diagnosticsTool) Name() string {
55 return DiagnosticsToolName
56}
57
58func (b *diagnosticsTool) Info() ToolInfo {
59 return ToolInfo{
60 Name: DiagnosticsToolName,
61 Description: diagnosticsDescription,
62 Parameters: map[string]any{
63 "file_path": map[string]any{
64 "type": "string",
65 "description": "The path to the file to get diagnostics for (leave w empty for project diagnostics)",
66 },
67 },
68 Required: []string{},
69 }
70}
71
72func (b *diagnosticsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
73 var params DiagnosticsParams
74 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
75 return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
76 }
77
78 lsps := b.lspClients
79
80 if len(lsps) == 0 {
81 return NewTextErrorResponse("no LSP clients available"), nil
82 }
83
84 if params.FilePath != "" {
85 notifyLspOpenFile(ctx, params.FilePath, lsps)
86 waitForLspDiagnostics(ctx, params.FilePath, lsps)
87 }
88
89 output := getDiagnostics(params.FilePath, lsps)
90
91 return NewTextResponse(output), nil
92}
93
94func notifyLspOpenFile(ctx context.Context, filePath string, lsps map[string]*lsp.Client) {
95 for _, client := range lsps {
96 err := client.OpenFile(ctx, filePath)
97 if err != nil {
98 continue
99 }
100 }
101}
102
103func waitForLspDiagnostics(ctx context.Context, filePath string, lsps map[string]*lsp.Client) {
104 if len(lsps) == 0 {
105 return
106 }
107
108 diagChan := make(chan struct{}, 1)
109
110 for _, client := range lsps {
111 originalDiags := make(map[protocol.DocumentURI][]protocol.Diagnostic)
112 maps.Copy(originalDiags, client.GetDiagnostics())
113
114 handler := func(params json.RawMessage) {
115 lsp.HandleDiagnostics(client, params)
116 var diagParams protocol.PublishDiagnosticsParams
117 if err := json.Unmarshal(params, &diagParams); err != nil {
118 return
119 }
120
121 if diagParams.URI.Path() == filePath || hasDiagnosticsChanged(client.GetDiagnostics(), originalDiags) {
122 select {
123 case diagChan <- struct{}{}:
124 default:
125 }
126 }
127 }
128
129 client.RegisterNotificationHandler("textDocument/publishDiagnostics", handler)
130
131 if client.IsFileOpen(filePath) {
132 err := client.NotifyChange(ctx, filePath)
133 if err != nil {
134 continue
135 }
136 } else {
137 err := client.OpenFile(ctx, filePath)
138 if err != nil {
139 continue
140 }
141 }
142 }
143
144 select {
145 case <-diagChan:
146 case <-time.After(5 * time.Second):
147 case <-ctx.Done():
148 }
149}
150
151func hasDiagnosticsChanged(current, original map[protocol.DocumentURI][]protocol.Diagnostic) bool {
152 for uri, diags := range current {
153 origDiags, exists := original[uri]
154 if !exists || len(diags) != len(origDiags) {
155 return true
156 }
157 }
158 return false
159}
160
161func getDiagnostics(filePath string, lsps map[string]*lsp.Client) string {
162 fileDiagnostics := []string{}
163 projectDiagnostics := []string{}
164
165 formatDiagnostic := func(pth string, diagnostic protocol.Diagnostic, source string) string {
166 severity := "Info"
167 switch diagnostic.Severity {
168 case protocol.SeverityError:
169 severity = "Error"
170 case protocol.SeverityWarning:
171 severity = "Warn"
172 case protocol.SeverityHint:
173 severity = "Hint"
174 }
175
176 location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
177
178 sourceInfo := ""
179 if diagnostic.Source != "" {
180 sourceInfo = diagnostic.Source
181 } else if source != "" {
182 sourceInfo = source
183 }
184
185 codeInfo := ""
186 if diagnostic.Code != nil {
187 codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
188 }
189
190 tagsInfo := ""
191 if len(diagnostic.Tags) > 0 {
192 tags := []string{}
193 for _, tag := range diagnostic.Tags {
194 switch tag {
195 case protocol.Unnecessary:
196 tags = append(tags, "unnecessary")
197 case protocol.Deprecated:
198 tags = append(tags, "deprecated")
199 }
200 }
201 if len(tags) > 0 {
202 tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
203 }
204 }
205
206 return fmt.Sprintf("%s: %s [%s]%s%s %s",
207 severity,
208 location,
209 sourceInfo,
210 codeInfo,
211 tagsInfo,
212 diagnostic.Message)
213 }
214
215 for lspName, client := range lsps {
216 diagnostics := client.GetDiagnostics()
217 if len(diagnostics) > 0 {
218 for location, diags := range diagnostics {
219 isCurrentFile := location.Path() == filePath
220
221 for _, diag := range diags {
222 formattedDiag := formatDiagnostic(location.Path(), diag, lspName)
223
224 if isCurrentFile {
225 fileDiagnostics = append(fileDiagnostics, formattedDiag)
226 } else {
227 projectDiagnostics = append(projectDiagnostics, formattedDiag)
228 }
229 }
230 }
231 }
232 }
233
234 sort.Slice(fileDiagnostics, func(i, j int) bool {
235 iIsError := strings.HasPrefix(fileDiagnostics[i], "Error")
236 jIsError := strings.HasPrefix(fileDiagnostics[j], "Error")
237 if iIsError != jIsError {
238 return iIsError // Errors come first
239 }
240 return fileDiagnostics[i] < fileDiagnostics[j] // Then alphabetically
241 })
242
243 sort.Slice(projectDiagnostics, func(i, j int) bool {
244 iIsError := strings.HasPrefix(projectDiagnostics[i], "Error")
245 jIsError := strings.HasPrefix(projectDiagnostics[j], "Error")
246 if iIsError != jIsError {
247 return iIsError
248 }
249 return projectDiagnostics[i] < projectDiagnostics[j]
250 })
251
252 var output strings.Builder
253
254 if len(fileDiagnostics) > 0 {
255 output.WriteString("\n<file_diagnostics>\n")
256 if len(fileDiagnostics) > 10 {
257 output.WriteString(strings.Join(fileDiagnostics[:10], "\n"))
258 fmt.Fprintf(&output, "\n... and %d more diagnostics", len(fileDiagnostics)-10)
259 } else {
260 output.WriteString(strings.Join(fileDiagnostics, "\n"))
261 }
262 output.WriteString("\n</file_diagnostics>\n")
263 }
264
265 if len(projectDiagnostics) > 0 {
266 output.WriteString("\n<project_diagnostics>\n")
267 if len(projectDiagnostics) > 10 {
268 output.WriteString(strings.Join(projectDiagnostics[:10], "\n"))
269 fmt.Fprintf(&output, "\n... and %d more diagnostics", len(projectDiagnostics)-10)
270 } else {
271 output.WriteString(strings.Join(projectDiagnostics, "\n"))
272 }
273 output.WriteString("\n</project_diagnostics>\n")
274 }
275
276 if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
277 fileErrors := countSeverity(fileDiagnostics, "Error")
278 fileWarnings := countSeverity(fileDiagnostics, "Warn")
279 projectErrors := countSeverity(projectDiagnostics, "Error")
280 projectWarnings := countSeverity(projectDiagnostics, "Warn")
281
282 output.WriteString("\n<diagnostic_summary>\n")
283 fmt.Fprintf(&output, "Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
284 fmt.Fprintf(&output, "Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
285 output.WriteString("</diagnostic_summary>\n")
286 }
287
288 return output.String()
289}
290
291func countSeverity(diagnostics []string, severity string) int {
292 count := 0
293 for _, diag := range diagnostics {
294 if strings.HasPrefix(diag, severity) {
295 count++
296 }
297 }
298 return count
299}