1package lsp
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "maps"
9 "os"
10 "path/filepath"
11 "sync"
12 "sync/atomic"
13 "time"
14
15 "github.com/charmbracelet/crush/internal/config"
16 "github.com/charmbracelet/crush/internal/csync"
17 "github.com/charmbracelet/crush/internal/fsext"
18 "github.com/charmbracelet/crush/internal/home"
19 powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
20 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
21 "github.com/charmbracelet/x/powernap/pkg/transport"
22)
23
24// DiagnosticCounts holds the count of diagnostics by severity.
25type DiagnosticCounts struct {
26 Error int
27 Warning int
28 Information int
29 Hint int
30}
31
32type Client struct {
33 client *powernap.Client
34 name string
35 debug bool
36
37 // Working directory this LSP is scoped to.
38 cwd string
39
40 // File types this LSP server handles (e.g., .go, .rs, .py)
41 fileTypes []string
42
43 // Configuration for this LSP client
44 config config.LSPConfig
45
46 // Original context and resolver for recreating the client
47 ctx context.Context
48 resolver config.VariableResolver
49
50 // Diagnostic change callback
51 onDiagnosticsChanged func(name string, count int)
52
53 // Diagnostic cache
54 diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
55
56 // Cached diagnostic counts to avoid map copy on every UI render.
57 diagCountsCache DiagnosticCounts
58 diagCountsVersion uint64
59 diagCountsMu sync.Mutex
60
61 // Files are currently opened by the LSP
62 openFiles *csync.Map[string, *OpenFileInfo]
63
64 // Server state
65 serverState atomic.Value
66}
67
68// New creates a new LSP client using the powernap implementation.
69func New(
70 ctx context.Context,
71 name string,
72 cfg config.LSPConfig,
73 resolver config.VariableResolver,
74 cwd string,
75 debug bool,
76) (*Client, error) {
77 client := &Client{
78 name: name,
79 fileTypes: cfg.FileTypes,
80 diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
81 openFiles: csync.NewMap[string, *OpenFileInfo](),
82 config: cfg,
83 ctx: ctx,
84 debug: debug,
85 resolver: resolver,
86 cwd: cwd,
87 }
88 client.serverState.Store(StateStopped)
89
90 if err := client.createPowernapClient(); err != nil {
91 return nil, err
92 }
93
94 return client, nil
95}
96
97// Initialize initializes the LSP client and returns the server capabilities.
98func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
99 if err := c.client.Initialize(ctx, false); err != nil {
100 return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
101 }
102
103 // Convert powernap capabilities to protocol capabilities
104 caps := c.client.GetCapabilities()
105 protocolCaps := protocol.ServerCapabilities{
106 TextDocumentSync: caps.TextDocumentSync,
107 CompletionProvider: func() *protocol.CompletionOptions {
108 if caps.CompletionProvider != nil {
109 return &protocol.CompletionOptions{
110 TriggerCharacters: caps.CompletionProvider.TriggerCharacters,
111 AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
112 ResolveProvider: caps.CompletionProvider.ResolveProvider,
113 }
114 }
115 return nil
116 }(),
117 }
118
119 result := &protocol.InitializeResult{
120 Capabilities: protocolCaps,
121 }
122
123 c.registerHandlers()
124
125 return result, nil
126}
127
128// Kill kills the client without doing anything else.
129func (c *Client) Kill() { c.client.Kill() }
130
131// Close closes all open files in the client, then the client.
132func (c *Client) Close(ctx context.Context) error {
133 c.CloseAllFiles(ctx)
134
135 // Shutdown and exit the client
136 if err := c.client.Shutdown(ctx); err != nil {
137 slog.Warn("Failed to shutdown LSP client", "error", err)
138 }
139
140 return c.client.Exit()
141}
142
143// createPowernapClient creates a new powernap client with the current configuration.
144func (c *Client) createPowernapClient() error {
145 rootURI := string(protocol.URIFromPath(c.cwd))
146
147 command, err := c.resolver.ResolveValue(c.config.Command)
148 if err != nil {
149 return fmt.Errorf("invalid lsp command: %w", err)
150 }
151
152 clientConfig := powernap.ClientConfig{
153 Command: home.Long(command),
154 Args: c.config.Args,
155 RootURI: rootURI,
156 Environment: maps.Clone(c.config.Env),
157 Settings: c.config.Options,
158 InitOptions: c.config.InitOptions,
159 WorkspaceFolders: []protocol.WorkspaceFolder{
160 {
161 URI: rootURI,
162 Name: filepath.Base(c.cwd),
163 },
164 },
165 }
166
167 powernapClient, err := powernap.NewClient(clientConfig)
168 if err != nil {
169 return fmt.Errorf("failed to create lsp client: %w", err)
170 }
171
172 c.client = powernapClient
173 return nil
174}
175
176// registerHandlers registers the standard LSP notification and request handlers.
177func (c *Client) registerHandlers() {
178 c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
179 c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
180 c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
181 c.RegisterNotificationHandler("window/showMessage", func(ctx context.Context, method string, params json.RawMessage) {
182 if c.debug {
183 HandleServerMessage(ctx, method, params)
184 }
185 })
186 c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
187 HandleDiagnostics(c, params)
188 })
189}
190
191// Restart closes the current LSP client and creates a new one with the same configuration.
192func (c *Client) Restart() error {
193 var openFiles []string
194 for uri := range c.openFiles.Seq2() {
195 openFiles = append(openFiles, string(uri))
196 }
197
198 closeCtx, cancel := context.WithTimeout(c.ctx, 10*time.Second)
199 defer cancel()
200
201 if err := c.Close(closeCtx); err != nil {
202 slog.Warn("Error closing client during restart", "name", c.name, "error", err)
203 }
204
205 c.SetServerState(StateStopped)
206
207 c.diagCountsCache = DiagnosticCounts{}
208 c.diagCountsVersion = 0
209
210 if err := c.createPowernapClient(); err != nil {
211 return err
212 }
213
214 initCtx, cancel := context.WithTimeout(c.ctx, 30*time.Second)
215 defer cancel()
216
217 c.SetServerState(StateStarting)
218
219 if err := c.client.Initialize(initCtx, false); err != nil {
220 c.SetServerState(StateError)
221 return fmt.Errorf("failed to initialize lsp client: %w", err)
222 }
223
224 c.registerHandlers()
225
226 if err := c.WaitForServerReady(initCtx); err != nil {
227 slog.Error("Server failed to become ready after restart", "name", c.name, "error", err)
228 c.SetServerState(StateError)
229 return err
230 }
231
232 for _, uri := range openFiles {
233 if err := c.OpenFile(initCtx, uri); err != nil {
234 slog.Warn("Failed to reopen file after restart", "file", uri, "error", err)
235 }
236 }
237 return nil
238}
239
240// ServerState represents the state of an LSP server
241type ServerState int
242
243const (
244 StateUnstarted ServerState = iota
245 StateStarting
246 StateReady
247 StateError
248 StateStopped
249 StateDisabled
250)
251
252// GetServerState returns the current state of the LSP server
253func (c *Client) GetServerState() ServerState {
254 if val := c.serverState.Load(); val != nil {
255 return val.(ServerState)
256 }
257 return StateStarting
258}
259
260// SetServerState sets the current state of the LSP server
261func (c *Client) SetServerState(state ServerState) {
262 c.serverState.Store(state)
263}
264
265// GetName returns the name of the LSP client
266func (c *Client) GetName() string {
267 return c.name
268}
269
270// SetDiagnosticsCallback sets the callback function for diagnostic changes
271func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
272 c.onDiagnosticsChanged = callback
273}
274
275// WaitForServerReady waits for the server to be ready
276func (c *Client) WaitForServerReady(ctx context.Context) error {
277 // Set initial state
278 c.SetServerState(StateStarting)
279
280 // Try to ping the server with a simple request
281 ticker := time.NewTicker(500 * time.Millisecond)
282 defer ticker.Stop()
283
284 if c.debug {
285 slog.Debug("Waiting for LSP server to be ready...")
286 }
287
288 c.openKeyConfigFiles(ctx)
289
290 for {
291 select {
292 case <-ctx.Done():
293 c.SetServerState(StateError)
294 return fmt.Errorf("timeout waiting for LSP server to be ready")
295 case <-ticker.C:
296 // Check if client is running
297 if !c.client.IsRunning() {
298 if c.debug {
299 slog.Debug("LSP server not ready yet", "server", c.name)
300 }
301 continue
302 }
303
304 // Server is ready
305 c.SetServerState(StateReady)
306 if c.debug {
307 slog.Debug("LSP server is ready")
308 }
309 return nil
310 }
311 }
312}
313
314// OpenFileInfo contains information about an open file
315type OpenFileInfo struct {
316 Version int32
317 URI protocol.DocumentURI
318}
319
320// HandlesFile checks if this LSP client handles the given file based on its
321// extension and whether it's within the working directory.
322func (c *Client) HandlesFile(path string) bool {
323 if c == nil {
324 return false
325 }
326 if !fsext.HasPrefix(path, c.cwd) {
327 slog.Debug("File outside workspace", "name", c.name, "file", path, "workDir", c.cwd)
328 return false
329 }
330 return handlesFiletype(c.name, c.fileTypes, path)
331}
332
333// OpenFile opens a file in the LSP server.
334func (c *Client) OpenFile(ctx context.Context, filepath string) error {
335 if !c.HandlesFile(filepath) {
336 return nil
337 }
338
339 uri := string(protocol.URIFromPath(filepath))
340
341 if _, exists := c.openFiles.Get(uri); exists {
342 return nil // Already open
343 }
344
345 // Skip files that do not exist or cannot be read
346 content, err := os.ReadFile(filepath)
347 if err != nil {
348 return fmt.Errorf("error reading file: %w", err)
349 }
350
351 // Notify the server about the opened document
352 if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(powernap.DetectLanguage(filepath)), 1, string(content)); err != nil {
353 return err
354 }
355
356 c.openFiles.Set(uri, &OpenFileInfo{
357 Version: 1,
358 URI: protocol.DocumentURI(uri),
359 })
360
361 return nil
362}
363
364// NotifyChange notifies the server about a file change.
365func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
366 if c == nil {
367 return nil
368 }
369 uri := string(protocol.URIFromPath(filepath))
370
371 content, err := os.ReadFile(filepath)
372 if err != nil {
373 return fmt.Errorf("error reading file: %w", err)
374 }
375
376 fileInfo, isOpen := c.openFiles.Get(uri)
377 if !isOpen {
378 return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
379 }
380
381 // Increment version
382 fileInfo.Version++
383
384 // Create change event
385 changes := []protocol.TextDocumentContentChangeEvent{
386 {
387 Value: protocol.TextDocumentContentChangeWholeDocument{
388 Text: string(content),
389 },
390 },
391 }
392
393 return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
394}
395
396// IsFileOpen checks if a file is currently open.
397func (c *Client) IsFileOpen(filepath string) bool {
398 uri := string(protocol.URIFromPath(filepath))
399 _, exists := c.openFiles.Get(uri)
400 return exists
401}
402
403// CloseAllFiles closes all currently open files.
404func (c *Client) CloseAllFiles(ctx context.Context) {
405 for uri := range c.openFiles.Seq2() {
406 if c.debug {
407 slog.Debug("Closing file", "file", uri)
408 }
409 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
410 slog.Warn("Error closing file", "uri", uri, "error", err)
411 continue
412 }
413 c.openFiles.Del(uri)
414 }
415}
416
417// GetFileDiagnostics returns diagnostics for a specific file.
418func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
419 diags, _ := c.diagnostics.Get(uri)
420 return diags
421}
422
423// GetDiagnostics returns all diagnostics for all files.
424func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
425 if c == nil {
426 return nil
427 }
428 return c.diagnostics.Copy()
429}
430
431// GetDiagnosticCounts returns cached diagnostic counts by severity.
432// Uses the VersionedMap version to avoid recomputing on every call.
433func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
434 if c == nil {
435 return DiagnosticCounts{}
436 }
437 currentVersion := c.diagnostics.Version()
438
439 c.diagCountsMu.Lock()
440 defer c.diagCountsMu.Unlock()
441
442 if currentVersion == c.diagCountsVersion {
443 return c.diagCountsCache
444 }
445
446 // Recompute counts.
447 counts := DiagnosticCounts{}
448 for _, diags := range c.diagnostics.Seq2() {
449 for _, diag := range diags {
450 switch diag.Severity {
451 case protocol.SeverityError:
452 counts.Error++
453 case protocol.SeverityWarning:
454 counts.Warning++
455 case protocol.SeverityInformation:
456 counts.Information++
457 case protocol.SeverityHint:
458 counts.Hint++
459 }
460 }
461 }
462
463 c.diagCountsCache = counts
464 c.diagCountsVersion = currentVersion
465 return counts
466}
467
468// OpenFileOnDemand opens a file only if it's not already open.
469func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
470 if c == nil {
471 return nil
472 }
473 // Check if the file is already open
474 if c.IsFileOpen(filepath) {
475 return nil
476 }
477
478 // Open the file
479 return c.OpenFile(ctx, filepath)
480}
481
482// RegisterNotificationHandler registers a notification handler.
483func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
484 c.client.RegisterNotificationHandler(method, handler)
485}
486
487// RegisterServerRequestHandler handles server requests.
488func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
489 c.client.RegisterHandler(method, handler)
490}
491
492// openKeyConfigFiles opens important configuration files that help initialize the server.
493func (c *Client) openKeyConfigFiles(ctx context.Context) {
494 // Try to open each file, ignoring errors if they don't exist
495 for _, file := range c.config.RootMarkers {
496 file = filepath.Join(c.cwd, file)
497 if _, err := os.Stat(file); err == nil {
498 // File exists, try to open it
499 if err := c.OpenFile(ctx, file); err != nil {
500 slog.Error("Failed to open key config file", "file", file, "error", err)
501 } else {
502 slog.Debug("Opened key config file for initialization", "file", file)
503 }
504 }
505 }
506}
507
508// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
509func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
510 if c == nil {
511 return
512 }
513 ticker := time.NewTicker(200 * time.Millisecond)
514 defer ticker.Stop()
515 timeout := time.After(d)
516 pv := c.diagnostics.Version()
517 for {
518 select {
519 case <-ctx.Done():
520 return
521 case <-timeout:
522 return
523 case <-ticker.C:
524 if pv != c.diagnostics.Version() {
525 return
526 }
527 }
528 }
529}
530
531// FindReferences finds all references to the symbol at the given position.
532func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
533 if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
534 return nil, err
535 }
536
537 // Add timeout to prevent hanging on slow LSP servers.
538 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
539 defer cancel()
540
541 // NOTE: line and character should be 0-based.
542 // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
543 return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
544}