1package tools
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log/slog"
  8	"sort"
  9	"strings"
 10	"time"
 11
 12	"github.com/charmbracelet/crush/internal/lsp"
 13	"github.com/charmbracelet/x/powernap/pkg/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 := client.GetDiagnostics()
112
113		handler := func(_ context.Context, _ string, params json.RawMessage) {
114			lsp.HandleDiagnostics(client, params)
115			var diagParams protocol.PublishDiagnosticsParams
116			if err := json.Unmarshal(params, &diagParams); err != nil {
117				return
118			}
119
120			path, err := diagParams.URI.Path()
121			if err != nil {
122				slog.Error("Failed to convert diagnostic URI to path", "uri", diagParams.URI, "error", err)
123				return
124			}
125
126			if path == filePath || hasDiagnosticsChanged(client.GetDiagnostics(), originalDiags) {
127				select {
128				case diagChan <- struct{}{}:
129				default:
130				}
131			}
132		}
133
134		client.RegisterNotificationHandler("textDocument/publishDiagnostics", handler)
135
136		if client.IsFileOpen(filePath) {
137			err := client.NotifyChange(ctx, filePath)
138			if err != nil {
139				continue
140			}
141		} else {
142			err := client.OpenFile(ctx, filePath)
143			if err != nil {
144				continue
145			}
146		}
147	}
148
149	select {
150	case <-diagChan:
151	case <-time.After(5 * time.Second):
152	case <-ctx.Done():
153	}
154}
155
156func hasDiagnosticsChanged(current, original map[protocol.DocumentURI][]protocol.Diagnostic) bool {
157	for uri, diags := range current {
158		origDiags, exists := original[uri]
159		if !exists || len(diags) != len(origDiags) {
160			return true
161		}
162	}
163	return false
164}
165
166func getDiagnostics(filePath string, lsps map[string]*lsp.Client) string {
167	fileDiagnostics := []string{}
168	projectDiagnostics := []string{}
169
170	for lspName, client := range lsps {
171		for location, diags := range client.GetDiagnostics() {
172			path, err := location.Path()
173			if err != nil {
174				slog.Error("Failed to convert diagnostic location URI to path", "uri", location, "error", err)
175				continue
176			}
177			isCurrentFile := path == filePath
178			for _, diag := range diags {
179				formattedDiag := formatDiagnostic(path, diag, lspName)
180				if isCurrentFile {
181					fileDiagnostics = append(fileDiagnostics, formattedDiag)
182				} else {
183					projectDiagnostics = append(projectDiagnostics, formattedDiag)
184				}
185			}
186		}
187	}
188
189	sortDiagnostics(fileDiagnostics)
190	sortDiagnostics(projectDiagnostics)
191
192	var output strings.Builder
193	writeDiagnostics(&output, "file_diagnostics", fileDiagnostics)
194	writeDiagnostics(&output, "project_diagnostics", projectDiagnostics)
195
196	if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
197		fileErrors := countSeverity(fileDiagnostics, "Error")
198		fileWarnings := countSeverity(fileDiagnostics, "Warn")
199		projectErrors := countSeverity(projectDiagnostics, "Error")
200		projectWarnings := countSeverity(projectDiagnostics, "Warn")
201
202		output.WriteString("\n<diagnostic_summary>\n")
203		fmt.Fprintf(&output, "Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
204		fmt.Fprintf(&output, "Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
205		output.WriteString("</diagnostic_summary>\n")
206	}
207
208	out := output.String()
209	slog.Info("Diagnostics", "output", fmt.Sprintf("%q", out))
210	return out
211}
212
213func writeDiagnostics(output *strings.Builder, tag string, in []string) {
214	if len(in) == 0 {
215		return
216	}
217	output.WriteString("\n<" + tag + ">\n")
218	if len(in) > 10 {
219		output.WriteString(strings.Join(in[:10], "\n"))
220		fmt.Fprintf(output, "\n... and %d more diagnostics", len(in)-10)
221	} else {
222		output.WriteString(strings.Join(in, "\n"))
223	}
224	output.WriteString("\n</" + tag + ">\n")
225}
226
227func sortDiagnostics(in []string) []string {
228	sort.Slice(in, func(i, j int) bool {
229		iIsError := strings.HasPrefix(in[i], "Error")
230		jIsError := strings.HasPrefix(in[j], "Error")
231		if iIsError != jIsError {
232			return iIsError // Errors come first
233		}
234		return in[i] < in[j] // Then alphabetically
235	})
236	return in
237}
238
239func formatDiagnostic(pth string, diagnostic protocol.Diagnostic, source string) string {
240	severity := "Info"
241	switch diagnostic.Severity {
242	case protocol.SeverityError:
243		severity = "Error"
244	case protocol.SeverityWarning:
245		severity = "Warn"
246	case protocol.SeverityHint:
247		severity = "Hint"
248	}
249
250	location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
251
252	sourceInfo := ""
253	if diagnostic.Source != "" {
254		sourceInfo = diagnostic.Source
255	} else if source != "" {
256		sourceInfo = source
257	}
258
259	codeInfo := ""
260	if diagnostic.Code != nil {
261		codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
262	}
263
264	tagsInfo := ""
265	if len(diagnostic.Tags) > 0 {
266		tags := []string{}
267		for _, tag := range diagnostic.Tags {
268			switch tag {
269			case protocol.Unnecessary:
270				tags = append(tags, "unnecessary")
271			case protocol.Deprecated:
272				tags = append(tags, "deprecated")
273			}
274		}
275		if len(tags) > 0 {
276			tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
277		}
278	}
279
280	return fmt.Sprintf("%s: %s [%s]%s%s %s",
281		severity,
282		location,
283		sourceInfo,
284		codeInfo,
285		tagsInfo,
286		diagnostic.Message)
287}
288
289func countSeverity(diagnostics []string, severity string) int {
290	count := 0
291	for _, diag := range diagnostics {
292		if strings.HasPrefix(diag, severity) {
293			count++
294		}
295	}
296	return count
297}