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(StateStarting)
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 StateStopped ServerState = iota
245 StateStarting
246 StateReady
247 StateError
248 StateDisabled
249)
250
251// GetServerState returns the current state of the LSP server
252func (c *Client) GetServerState() ServerState {
253 if val := c.serverState.Load(); val != nil {
254 return val.(ServerState)
255 }
256 return StateStarting
257}
258
259// SetServerState sets the current state of the LSP server
260func (c *Client) SetServerState(state ServerState) {
261 c.serverState.Store(state)
262}
263
264// GetName returns the name of the LSP client
265func (c *Client) GetName() string {
266 return c.name
267}
268
269// SetDiagnosticsCallback sets the callback function for diagnostic changes
270func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
271 c.onDiagnosticsChanged = callback
272}
273
274// WaitForServerReady waits for the server to be ready
275func (c *Client) WaitForServerReady(ctx context.Context) error {
276 // Set initial state
277 c.SetServerState(StateStarting)
278
279 // Create a context with timeout
280 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
281 defer cancel()
282
283 // Try to ping the server with a simple request
284 ticker := time.NewTicker(500 * time.Millisecond)
285 defer ticker.Stop()
286
287 if c.debug {
288 slog.Debug("Waiting for LSP server to be ready...")
289 }
290
291 c.openKeyConfigFiles(ctx)
292
293 for {
294 select {
295 case <-ctx.Done():
296 c.SetServerState(StateError)
297 return fmt.Errorf("timeout waiting for LSP server to be ready")
298 case <-ticker.C:
299 // Check if client is running
300 if !c.client.IsRunning() {
301 if c.debug {
302 slog.Debug("LSP server not ready yet", "server", c.name)
303 }
304 continue
305 }
306
307 // Server is ready
308 c.SetServerState(StateReady)
309 if c.debug {
310 slog.Debug("LSP server is ready")
311 }
312 return nil
313 }
314 }
315}
316
317// OpenFileInfo contains information about an open file
318type OpenFileInfo struct {
319 Version int32
320 URI protocol.DocumentURI
321}
322
323// HandlesFile checks if this LSP client handles the given file based on its
324// extension and whether it's within the working directory.
325func (c *Client) HandlesFile(path string) bool {
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 uri := string(protocol.URIFromPath(filepath))
367
368 content, err := os.ReadFile(filepath)
369 if err != nil {
370 return fmt.Errorf("error reading file: %w", err)
371 }
372
373 fileInfo, isOpen := c.openFiles.Get(uri)
374 if !isOpen {
375 return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
376 }
377
378 // Increment version
379 fileInfo.Version++
380
381 // Create change event
382 changes := []protocol.TextDocumentContentChangeEvent{
383 {
384 Value: protocol.TextDocumentContentChangeWholeDocument{
385 Text: string(content),
386 },
387 },
388 }
389
390 return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
391}
392
393// IsFileOpen checks if a file is currently open.
394func (c *Client) IsFileOpen(filepath string) bool {
395 uri := string(protocol.URIFromPath(filepath))
396 _, exists := c.openFiles.Get(uri)
397 return exists
398}
399
400// CloseAllFiles closes all currently open files.
401func (c *Client) CloseAllFiles(ctx context.Context) {
402 for uri := range c.openFiles.Seq2() {
403 if c.debug {
404 slog.Debug("Closing file", "file", uri)
405 }
406 if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
407 slog.Warn("Error closing file", "uri", uri, "error", err)
408 continue
409 }
410 c.openFiles.Del(uri)
411 }
412}
413
414// GetFileDiagnostics returns diagnostics for a specific file.
415func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
416 diags, _ := c.diagnostics.Get(uri)
417 return diags
418}
419
420// GetDiagnostics returns all diagnostics for all files.
421func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
422 return c.diagnostics.Copy()
423}
424
425// GetDiagnosticCounts returns cached diagnostic counts by severity.
426// Uses the VersionedMap version to avoid recomputing on every call.
427func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
428 currentVersion := c.diagnostics.Version()
429
430 c.diagCountsMu.Lock()
431 defer c.diagCountsMu.Unlock()
432
433 if currentVersion == c.diagCountsVersion {
434 return c.diagCountsCache
435 }
436
437 // Recompute counts.
438 counts := DiagnosticCounts{}
439 for _, diags := range c.diagnostics.Seq2() {
440 for _, diag := range diags {
441 switch diag.Severity {
442 case protocol.SeverityError:
443 counts.Error++
444 case protocol.SeverityWarning:
445 counts.Warning++
446 case protocol.SeverityInformation:
447 counts.Information++
448 case protocol.SeverityHint:
449 counts.Hint++
450 }
451 }
452 }
453
454 c.diagCountsCache = counts
455 c.diagCountsVersion = currentVersion
456 return counts
457}
458
459// OpenFileOnDemand opens a file only if it's not already open.
460func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
461 // Check if the file is already open
462 if c.IsFileOpen(filepath) {
463 return nil
464 }
465
466 // Open the file
467 return c.OpenFile(ctx, filepath)
468}
469
470// RegisterNotificationHandler registers a notification handler.
471func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
472 c.client.RegisterNotificationHandler(method, handler)
473}
474
475// RegisterServerRequestHandler handles server requests.
476func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
477 c.client.RegisterHandler(method, handler)
478}
479
480// openKeyConfigFiles opens important configuration files that help initialize the server.
481func (c *Client) openKeyConfigFiles(ctx context.Context) {
482 wd, err := os.Getwd()
483 if err != nil {
484 return
485 }
486
487 // Try to open each file, ignoring errors if they don't exist
488 for _, file := range c.config.RootMarkers {
489 file = filepath.Join(wd, file)
490 if _, err := os.Stat(file); err == nil {
491 // File exists, try to open it
492 if err := c.OpenFile(ctx, file); err != nil {
493 slog.Error("Failed to open key config file", "file", file, "error", err)
494 } else {
495 slog.Debug("Opened key config file for initialization", "file", file)
496 }
497 }
498 }
499}
500
501// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
502func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
503 ticker := time.NewTicker(200 * time.Millisecond)
504 defer ticker.Stop()
505 timeout := time.After(d)
506 pv := c.diagnostics.Version()
507 for {
508 select {
509 case <-ctx.Done():
510 return
511 case <-timeout:
512 return
513 case <-ticker.C:
514 if pv != c.diagnostics.Version() {
515 return
516 }
517 }
518 }
519}
520
521// FindReferences finds all references to the symbol at the given position.
522func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
523 if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
524 return nil, err
525 }
526 // NOTE: line and character should be 0-based.
527 // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
528 return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
529}