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 // Create a context with timeout
281 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
282 defer cancel()
283
284 // Try to ping the server with a simple request
285 ticker := time.NewTicker(500 * time.Millisecond)
286 defer ticker.Stop()
287
288 if c.debug {
289 slog.Debug("Waiting for LSP server to be ready...")
290 }
291
292 c.openKeyConfigFiles(ctx)
293
294 for {
295 select {
296 case <-ctx.Done():
297 c.SetServerState(StateError)
298 return fmt.Errorf("timeout waiting for LSP server to be ready")
299 case <-ticker.C:
300 // Check if client is running
301 if !c.client.IsRunning() {
302 if c.debug {
303 slog.Debug("LSP server not ready yet", "server", c.name)
304 }
305 continue
306 }
307
308 // Server is ready
309 c.SetServerState(StateReady)
310 if c.debug {
311 slog.Debug("LSP server is ready")
312 }
313 return nil
314 }
315 }
316}
317
318// OpenFileInfo contains information about an open file
319type OpenFileInfo struct {
320 Version int32
321 URI protocol.DocumentURI
322}
323
324// HandlesFile checks if this LSP client handles the given file based on its
325// extension and whether it's within the working directory.
326func (c *Client) HandlesFile(path string) bool {
327 if c == nil {
328 return false
329 }
330 if !fsext.HasPrefix(path, c.cwd) {
331 slog.Debug("File outside workspace", "name", c.name, "file", path, "workDir", c.cwd)
332 return false
333 }
334 return handlesFiletype(c.name, c.fileTypes, path)
335}
336
337// OpenFile opens a file in the LSP server.
338func (c *Client) OpenFile(ctx context.Context, filepath string) error {
339 if !c.HandlesFile(filepath) {
340 return nil
341 }
342
343 uri := string(protocol.URIFromPath(filepath))
344
345 if _, exists := c.openFiles.Get(uri); exists {
346 return nil // Already open
347 }
348
349 // Skip files that do not exist or cannot be read
350 content, err := os.ReadFile(filepath)
351 if err != nil {
352 return fmt.Errorf("error reading file: %w", err)
353 }
354
355 // Notify the server about the opened document
356 if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(powernap.DetectLanguage(filepath)), 1, string(content)); err != nil {
357 return err
358 }
359
360 c.openFiles.Set(uri, &OpenFileInfo{
361 Version: 1,
362 URI: protocol.DocumentURI(uri),
363 })
364
365 return nil
366}
367
368// NotifyChange notifies the server about a file change.
369func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
370 if c == nil {
371 return nil
372 }
373 uri := string(protocol.URIFromPath(filepath))
374
375 content, err := os.ReadFile(filepath)
376 if err != nil {
377 return fmt.Errorf("error reading file: %w", err)
378 }
379
380 fileInfo, isOpen := c.openFiles.Get(uri)
381 if !isOpen {
382 return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
383 }
384
385 // Increment version
386 fileInfo.Version++
387
388 // Create change event
389 changes := []protocol.TextDocumentContentChangeEvent{
390 {
391 Value: protocol.TextDocumentContentChangeWholeDocument{
392 Text: string(content),
393 },
394 },
395 }
396
397 return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
398}
399
400// IsFileOpen checks if a file is currently open.
401func (c *Client) IsFileOpen(filepath string) bool {
402 uri := string(protocol.URIFromPath(filepath))
403 _, exists := c.openFiles.Get(uri)
404 return exists
405}
406
407// CloseAllFiles closes all currently open files.
408func (c *Client) CloseAllFiles(ctx context.Context) {
409 for uri := range c.openFiles.Seq2() {
410 if c.debug {
411 slog.Debug("Closing file", "file", uri)
412 }
413 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
414 slog.Warn("Error closing file", "uri", uri, "error", err)
415 continue
416 }
417 c.openFiles.Del(uri)
418 }
419}
420
421// GetFileDiagnostics returns diagnostics for a specific file.
422func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
423 diags, _ := c.diagnostics.Get(uri)
424 return diags
425}
426
427// GetDiagnostics returns all diagnostics for all files.
428func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
429 if c == nil {
430 return nil
431 }
432 return c.diagnostics.Copy()
433}
434
435// GetDiagnosticCounts returns cached diagnostic counts by severity.
436// Uses the VersionedMap version to avoid recomputing on every call.
437func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
438 if c == nil {
439 return DiagnosticCounts{}
440 }
441 currentVersion := c.diagnostics.Version()
442
443 c.diagCountsMu.Lock()
444 defer c.diagCountsMu.Unlock()
445
446 if currentVersion == c.diagCountsVersion {
447 return c.diagCountsCache
448 }
449
450 // Recompute counts.
451 counts := DiagnosticCounts{}
452 for _, diags := range c.diagnostics.Seq2() {
453 for _, diag := range diags {
454 switch diag.Severity {
455 case protocol.SeverityError:
456 counts.Error++
457 case protocol.SeverityWarning:
458 counts.Warning++
459 case protocol.SeverityInformation:
460 counts.Information++
461 case protocol.SeverityHint:
462 counts.Hint++
463 }
464 }
465 }
466
467 c.diagCountsCache = counts
468 c.diagCountsVersion = currentVersion
469 return counts
470}
471
472// OpenFileOnDemand opens a file only if it's not already open.
473func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
474 if c == nil {
475 return nil
476 }
477 // Check if the file is already open
478 if c.IsFileOpen(filepath) {
479 return nil
480 }
481
482 // Open the file
483 return c.OpenFile(ctx, filepath)
484}
485
486// RegisterNotificationHandler registers a notification handler.
487func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
488 c.client.RegisterNotificationHandler(method, handler)
489}
490
491// RegisterServerRequestHandler handles server requests.
492func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
493 c.client.RegisterHandler(method, handler)
494}
495
496// openKeyConfigFiles opens important configuration files that help initialize the server.
497func (c *Client) openKeyConfigFiles(ctx context.Context) {
498 wd, err := os.Getwd()
499 if err != nil {
500 return
501 }
502
503 // Try to open each file, ignoring errors if they don't exist
504 for _, file := range c.config.RootMarkers {
505 file = filepath.Join(wd, file)
506 if _, err := os.Stat(file); err == nil {
507 // File exists, try to open it
508 if err := c.OpenFile(ctx, file); err != nil {
509 slog.Error("Failed to open key config file", "file", file, "error", err)
510 } else {
511 slog.Debug("Opened key config file for initialization", "file", file)
512 }
513 }
514 }
515}
516
517// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
518func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
519 if c == nil {
520 return
521 }
522 ticker := time.NewTicker(200 * time.Millisecond)
523 defer ticker.Stop()
524 timeout := time.After(d)
525 pv := c.diagnostics.Version()
526 for {
527 select {
528 case <-ctx.Done():
529 return
530 case <-timeout:
531 return
532 case <-ticker.C:
533 if pv != c.diagnostics.Version() {
534 return
535 }
536 }
537 }
538}
539
540// FindReferences finds all references to the symbol at the given position.
541func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
542 if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
543 return nil, err
544 }
545 // NOTE: line and character should be 0-based.
546 // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
547 return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
548}