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