Debian Codegraph @

powernap/pkg/lsp/client.go

raw
1 // Package lsp provides a client implementation for the Language Server
2 // Protocol (LSP).
3 package lsp
4
5 import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "io"
10 "log/slog"
11 "os"
12 "os/exec"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
18 "github.com/charmbracelet/x/powernap/pkg/transport"
19 )
20
21 // LSP method constants
22 const (
23 MethodInitialize = "initialize"
24 MethodInitialized = "initialized"
25 MethodShutdown = "shutdown"
26 MethodExit = "exit"
27 MethodTextDocumentDidOpen = "textDocument/didOpen"
28 MethodTextDocumentDidChange = "textDocument/didChange"
29 MethodTextDocumentDidSave = "textDocument/didSave"
30 MethodTextDocumentDidClose = "textDocument/didClose"
31 MethodTextDocumentCompletion = "textDocument/completion"
32 MethodTextDocumentHover = "textDocument/hover"
33 MethodTextDocumentDefinition = "textDocument/definition"
34 MethodTextDocumentReferences = "textDocument/references"
35 MethodTextDocumentDiagnostic = "textDocument/publishDiagnostics"
36 MethodWorkspaceConfiguration = "workspace/configuration"
37 MethodWorkspaceDidChangeConfiguration = "workspace/didChangeConfiguration"
38 MethodWorkspaceDidChangeWorkspaceFolders = "workspace/didChangeWorkspaceFolders"
39 MethodWorkspaceDidChangeWatchedFiles = "workspace/didChangeWatchedFiles"
40 )
41
42 // NewClient creates a new LSP client with the given configuration.
43 func NewClient(config ClientConfig) (*Client, error) {
44 ctx, cancel := context.WithCancel(context.Background())
45
46 client := &Client{
47 ID: config.Command, // Will be updated after initialization
48 Name: config.Command,
49 ctx: ctx,
50 cancel: cancel,
51 rootURI: config.RootURI,
52 workspaceFolders: config.WorkspaceFolders,
53 config: config.Settings,
54 initOptions: config.InitOptions,
55 offsetEncoding: UTF16, // Default to UTF16
56 }
57
58 // Start the language server process
59 stream, err := startServerProcess(ctx, config)
60 if err != nil {
61 cancel()
62 return nil, fmt.Errorf("failed to start language server: %w", err)
63 }
64
65 // Create transport connection
66 conn, err := transport.NewConnection(ctx, stream, slog.Default())
67 if err != nil {
68 cancel()
69 return nil, fmt.Errorf("failed to create connection: %w", err)
70 }
71
72 client.conn = conn
73
74 // Register handlers for server-initiated requests
75 client.setupHandlers()
76
77 return client, nil
78 }
79
80 // Initialize sends the initialize request to the language server.
81 func (c *Client) Initialize(ctx context.Context, enableSnippets bool) error {
82 if c.initialized {
83 return fmt.Errorf("client already initialized")
84 }
85
86 // Extract root path from URI
87 rootPath := ""
88 if c.rootURI != "" {
89 rootPath = strings.TrimPrefix(c.rootURI, "file://")
90 }
91
92 // Prepare workspace folders - some servers don't like nil
93 workspaceFolders := c.workspaceFolders
94 if workspaceFolders == nil {
95 workspaceFolders = []protocol.WorkspaceFolder{}
96 }
97
98 initParams := map[string]any{
99 "processId": os.Getpid(),
100 "clientInfo": map[string]any{
101 "name": "powernap",
102 "version": "0.1.0",
103 },
104 "locale": "en-us",
105 "rootPath": rootPath, // Deprecated but some servers still use it
106 "rootUri": c.rootURI,
107 "capabilities": c.makeClientCapabilities(enableSnippets),
108 "workspaceFolders": workspaceFolders,
109 "initializationOptions": c.initOptions, // Use the client's init options
110 "trace": "off", // Can be "off", "messages", or "verbose"
111 }
112
113 // Log the initialization params for debugging
114 paramsJSON, _ := json.MarshalIndent(initParams, "", " ")
115 slog.Debug("Sending initialize request", "params", string(paramsJSON))
116
117 var result protocol.InitializeResult
118 err := c.conn.Call(ctx, MethodInitialize, initParams, &result)
119 if err != nil {
120 return fmt.Errorf("initialize request failed: %w", err)
121 }
122
123 // Store server capabilities
124 c.capabilities = result.Capabilities
125
126 // Handle offset encoding
127 if result.OffsetEncoding != "" {
128 switch result.OffsetEncoding {
129 case "utf-8":
130 c.offsetEncoding = UTF8
131 case "utf-16":
132 c.offsetEncoding = UTF16
133 case "utf-32":
134 c.offsetEncoding = UTF32
135 }
136 }
137
138 // Send initialized notification
139 err = c.conn.Notify(ctx, MethodInitialized, map[string]any{})
140 if err != nil {
141 return fmt.Errorf("initialized notification failed: %w", err)
142 }
143
144 c.initialized = true
145
146 // For gopls, send workspace/didChangeConfiguration to ensure it's ready
147 // This helps gopls properly set up its workspace views
148 if strings.Contains(c.Name, "gopls") {
149 configParams := map[string]any{
150 "settings": c.config,
151 }
152 _ = c.conn.Notify(ctx, MethodWorkspaceDidChangeConfiguration, configParams)
153
154 // Also send workspace/didChangeWatchedFiles to trigger gopls to scan the workspace
155 // This helps with the "no views" error
156 if c.rootURI != "" {
157 changesParams := map[string]any{
158 "changes": []map[string]any{
159 {
160 "uri": c.rootURI,
161 "type": 1, // Created
162 },
163 },
164 }
165 _ = c.conn.Notify(ctx, "workspace/didChangeWatchedFiles", changesParams)
166 }
167 }
168
169 return nil
170 }
171
172 // Shutdown sends a shutdown request to the language server.
173 func (c *Client) Shutdown(ctx context.Context) error {
174 if c.shutdown {
175 return nil
176 }
177
178 err := c.conn.Call(ctx, MethodShutdown, nil, nil)
179 if err != nil {
180 return fmt.Errorf("shutdown request failed: %w", err)
181 }
182
183 c.shutdown = true
184 return nil
185 }
186
187 // Exit sends an exit notification to the language server.
188 func (c *Client) Exit() error {
189 err := c.conn.Notify(c.ctx, MethodExit, nil)
190 if err != nil {
191 return fmt.Errorf("exit notification failed: %w", err)
192 }
193
194 c.cancel()
195 return nil
196 }
197
198 // GetCapabilities returns the server capabilities.
199 func (c *Client) GetCapabilities() protocol.ServerCapabilities {
200 return c.capabilities
201 }
202
203 // IsInitialized returns whether the client has been initialized.
204 func (c *Client) IsInitialized() bool {
205 return c.initialized
206 }
207
208 // IsRunning returns whether the client connection is still active.
209 func (c *Client) IsRunning() bool {
210 return c.conn != nil && c.conn.IsConnected() && c.initialized && !c.shutdown
211 }
212
213 // RegisterNotificationHandler registers a handler for server-initiated notifications.
214 func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
215 if c.conn != nil {
216 c.conn.RegisterNotificationHandler(method, handler)
217 }
218 }
219
220 // RegisterHandler registers a handler for server-initiated requests.
221 func (c *Client) RegisterHandler(method string, handler transport.Handler) {
222 if c.conn != nil {
223 c.conn.RegisterHandler(method, handler)
224 }
225 }
226
227 // NotifyDidOpenTextDocument notifies the server that a document was opened.
228 func (c *Client) NotifyDidOpenTextDocument(ctx context.Context, uri string, languageID string, version int, text string) error {
229 if !c.initialized {
230 return fmt.Errorf("client not initialized")
231 }
232
233 params := protocol.DidOpenTextDocumentParams{
234 TextDocument: protocol.TextDocumentItem{
235 URI: protocol.DocumentURI(uri),
236 LanguageID: protocol.LanguageKind(languageID),
237 Version: int32(version),
238 Text: text,
239 },
240 }
241
242 // Log what we're sending for debugging
243 slog.Debug("Sending textDocument/didOpen",
244 "uri", uri,
245 "languageId", languageID,
246 "version", version,
247 "textLength", len(text))
248
249 return c.conn.Notify(ctx, MethodTextDocumentDidOpen, params)
250 }
251
252 // NotifyDidCloseTextDocument notifies the server that a document was closeed.
253 func (c *Client) NotifyDidCloseTextDocument(ctx context.Context, uri string) error {
254 if !c.initialized {
255 return fmt.Errorf("client not initialized")
256 }
257
258 params := protocol.DidCloseTextDocumentParams{
259 TextDocument: protocol.TextDocumentIdentifier{
260 URI: protocol.DocumentURI(uri),
261 },
262 }
263
264 return c.conn.Notify(ctx, MethodTextDocumentDidClose, params)
265 }
266
267 // NotifyDidChangeTextDocument notifies the server that a document was changed.
268 func (c *Client) NotifyDidChangeTextDocument(ctx context.Context, uri string, version int, changes []protocol.TextDocumentContentChangeEvent) error {
269 if !c.initialized {
270 return fmt.Errorf("client not initialized")
271 }
272
273 params := protocol.DidChangeTextDocumentParams{
274 TextDocument: protocol.VersionedTextDocumentIdentifier{
275 Version: int32(version),
276 TextDocumentIdentifier: protocol.TextDocumentIdentifier{
277 URI: protocol.DocumentURI(uri),
278 },
279 },
280 ContentChanges: changes,
281 }
282
283 return c.conn.Notify(ctx, MethodTextDocumentDidChange, params)
284 }
285
286 // NotifyDidChangeWatchedFiles notifies the server that watched files have
287 // changed.
288 func (c *Client) NotifyDidChangeWatchedFiles(ctx context.Context, changes []protocol.FileEvent) error {
289 if !c.initialized {
290 return fmt.Errorf("client not initialized")
291 }
292
293 params := protocol.DidChangeWatchedFilesParams{
294 Changes: changes,
295 }
296
297 return c.conn.Notify(ctx, MethodWorkspaceDidChangeWatchedFiles, params)
298 }
299
300 // NotifyWorkspaceDidChangeConfiguration notifies the server that the workspace configuration has changed.
301 func (c *Client) NotifyWorkspaceDidChangeConfiguration(ctx context.Context, settings any) error {
302 if !c.initialized {
303 return fmt.Errorf("client not initialized")
304 }
305
306 params := map[string]any{
307 "settings": settings,
308 }
309
310 return c.conn.Notify(ctx, MethodWorkspaceDidChangeConfiguration, params)
311 }
312
313 // RequestCompletion requests completion items at the given position.
314 func (c *Client) RequestCompletion(ctx context.Context, uri string, position protocol.Position) (*protocol.CompletionList, error) {
315 if !c.initialized {
316 return nil, fmt.Errorf("client not initialized")
317 }
318
319 params := protocol.CompletionParams{
320 Context: protocol.CompletionContext{
321 TriggerKind: protocol.Invoked,
322 },
323 TextDocumentPositionParams: protocol.TextDocumentPositionParams{
324 TextDocument: protocol.TextDocumentIdentifier{
325 URI: protocol.DocumentURI(uri),
326 },
327 Position: position,
328 },
329 }
330
331 var result any
332 err := c.conn.Call(ctx, MethodTextDocumentCompletion, params, &result)
333 if err != nil {
334 return nil, fmt.Errorf("completion request failed: %w", err)
335 }
336
337 // Parse the result - can be CompletionList or []CompletionItem
338 var completionList protocol.CompletionList
339
340 switch v := result.(type) {
341 case map[string]any:
342 // It's a CompletionList
343 data, err := json.Marshal(v)
344 if err != nil {
345 return nil, err
346 }
347 if err := json.Unmarshal(data, &completionList); err != nil {
348 return nil, err
349 }
350 case []any:
351 // It's an array of CompletionItem
352 data, err := json.Marshal(v)
353 if err != nil {
354 return nil, err
355 }
356 var items []protocol.CompletionItem
357 if err := json.Unmarshal(data, &items); err != nil {
358 return nil, err
359 }
360 completionList.Items = items
361 completionList.IsIncomplete = false
362 }
363
364 return &completionList, nil
365 }
366
367 // RequestHover requests hover information at the given position.
368 func (c *Client) RequestHover(ctx context.Context, uri string, position protocol.Position) (*protocol.Hover, error) {
369 if !c.initialized {
370 return nil, fmt.Errorf("client not initialized")
371 }
372
373 params := map[string]any{
374 "textDocument": map[string]any{
375 "uri": uri,
376 },
377 "position": position,
378 }
379
380 var result protocol.Hover
381 err := c.conn.Call(ctx, MethodTextDocumentHover, params, &result)
382 if err != nil {
383 return nil, fmt.Errorf("hover request failed: %w", err)
384 }
385
386 return &result, nil
387 }
388
389 // FindReferences finds all references to the symbol at the given position.
390 func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
391 uri := string(protocol.URIFromPath(filepath))
392 params := protocol.ReferenceParams{
393 TextDocumentPositionParams: protocol.TextDocumentPositionParams{
394 TextDocument: protocol.TextDocumentIdentifier{
395 URI: protocol.DocumentURI(uri),
396 },
397 Position: protocol.Position{
398 Line: uint32(line),
399 Character: uint32(character),
400 },
401 },
402 Context: protocol.ReferenceContext{
403 IncludeDeclaration: includeDeclaration,
404 },
405 }
406
407 var result []protocol.Location
408 err := c.conn.Call(ctx, MethodTextDocumentReferences, params, &result)
409 if err != nil {
410 return nil, fmt.Errorf("find references request failed: %w", err)
411 }
412 return result, nil
413 }
414
415 // setupHandlers registers handlers for server-initiated requests.
416 func (c *Client) setupHandlers() {
417 // Handle workspace/configuration requests
418 c.conn.RegisterHandler(MethodWorkspaceConfiguration, func(ctx context.Context, method string, params json.RawMessage) (any, error) {
419 var configParams protocol.ConfigurationParams
420 if err := json.Unmarshal(params, &configParams); err != nil {
421 return nil, err
422 }
423
424 // Return configuration for each requested item
425 result := make([]any, len(configParams.Items))
426 for i := range configParams.Items {
427 result[i] = c.config
428 }
429
430 return result, nil
431 })
432
433 // Handle other common server requests
434 // Add more handlers as needed
435 }
436
437 // makeClientCapabilities creates the client capabilities for initialization.
438 func (c *Client) makeClientCapabilities(enableSnippets bool) map[string]any {
439 return map[string]any{
440 "textDocument": map[string]any{
441 "synchronization": map[string]any{
442 "dynamicRegistration": true,
443 "willSave": true,
444 "willSaveWaitUntil": true,
445 "didSave": true,
446 },
447 "completion": map[string]any{
448 "dynamicRegistration": true,
449 "completionItem": map[string]any{
450 "snippetSupport": enableSnippets,
451 "commitCharactersSupport": true,
452 "documentationFormat": []string{"markdown", "plaintext"},
453 "deprecatedSupport": true,
454 "preselectSupport": true,
455 "insertReplaceSupport": true,
456 "tagSupport": map[string]any{
457 "valueSet": []int{1}, // Deprecated
458 },
459 "resolveSupport": map[string]any{
460 "properties": []string{"documentation", "detail", "additionalTextEdits"},
461 },
462 },
463 "contextSupport": true,
464 },
465 "hover": map[string]any{
466 "dynamicRegistration": true,
467 "contentFormat": []string{"markdown", "plaintext"},
468 },
469 "definition": map[string]any{
470 "dynamicRegistration": true,
471 "linkSupport": true,
472 },
473 "references": map[string]any{
474 "dynamicRegistration": true,
475 },
476 "documentHighlight": map[string]any{
477 "dynamicRegistration": true,
478 },
479 "documentSymbol": map[string]any{
480 "dynamicRegistration": true,
481 "hierarchicalDocumentSymbolSupport": true,
482 },
483 "formatting": map[string]any{
484 "dynamicRegistration": true,
485 },
486 "rangeFormatting": map[string]any{
487 "dynamicRegistration": true,
488 },
489 "rename": map[string]any{
490 "dynamicRegistration": true,
491 "prepareSupport": true,
492 },
493 "publishDiagnostics": map[string]any{
494 "relatedInformation": true,
495 "versionSupport": true,
496 "tagSupport": map[string]any{"valueSet": []int{1, 2}},
497 "codeDescriptionSupport": true,
498 "dataSupport": true,
499 },
500 "codeAction": map[string]any{
501 "dynamicRegistration": true,
502 "codeActionLiteralSupport": map[string]any{
503 "codeActionKind": map[string]any{
504 "valueSet": []string{
505 "quickfix",
506 "refactor",
507 "refactor.extract",
508 "refactor.inline",
509 "refactor.rewrite",
510 "source",
511 "source.organizeImports",
512 },
513 },
514 },
515 "isPreferredSupport": true,
516 "dataSupport": true,
517 "resolveSupport": map[string]any{
518 "properties": []string{"edit"},
519 },
520 },
521 },
522 "workspace": map[string]any{
523 "applyEdit": true,
524 "workspaceEdit": map[string]any{
525 "documentChanges": true,
526 "resourceOperations": []string{"create", "rename", "delete"},
527 "failureHandling": "textOnlyTransactional",
528 "normalizesLineEndings": true,
529 },
530 "didChangeConfiguration": map[string]any{
531 "dynamicRegistration": true,
532 },
533 "didChangeWatchedFiles": map[string]any{
534 "dynamicRegistration": true,
535 "relativePatternSupport": true,
536 },
537 "symbol": map[string]any{
538 "dynamicRegistration": true,
539 },
540 "configuration": true,
541 "workspaceFolders": true,
542 "fileOperations": map[string]any{
543 "dynamicRegistration": true,
544 "didCreate": true,
545 "willCreate": true,
546 "didRename": true,
547 "willRename": true,
548 "didDelete": true,
549 "willDelete": true,
550 },
551 },
552 "window": map[string]any{
553 "workDoneProgress": true,
554 "showMessage": map[string]any{
555 "messageActionItem": map[string]any{
556 "additionalPropertiesSupport": true,
557 },
558 },
559 "showDocument": map[string]any{
560 "support": true,
561 },
562 },
563 "general": map[string]any{
564 "regularExpressions": map[string]any{
565 "engine": "ECMAScript",
566 "version": "ES2020",
567 },
568 "markdown": map[string]any{
569 "parser": "marked",
570 "version": "1.1.0",
571 },
572 "positionEncodings": []string{"utf-16"},
573 },
574 }
575 }
576
577 // startServerProcess starts the language server process.
578 func startServerProcess(ctx context.Context, config ClientConfig) (io.ReadWriteCloser, error) {
579 cmd := exec.CommandContext(ctx, config.Command, config.Args...)
580
581 // Set environment variables
582 if config.Environment != nil {
583 cmd.Env = os.Environ()
584 for k, v := range config.Environment {
585 cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
586 }
587 }
588
589 // Create pipes
590 stdin, err := cmd.StdinPipe()
591 if err != nil {
592 return nil, fmt.Errorf("failed to create stdin pipe: %w", err)
593 }
594
595 stdout, err := cmd.StdoutPipe()
596 if err != nil {
597 return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
598 }
599
600 // Create stderr pipe to capture error messages
601 stderr, err := cmd.StderrPipe()
602 if err != nil {
603 return nil, fmt.Errorf("failed to create stderr pipe: %w", err)
604 }
605
606 // Start the process
607 if err := cmd.Start(); err != nil {
608 return nil, fmt.Errorf("failed to start process: %w", err)
609 }
610
611 // Monitor stderr
612 go func() {
613 buf := make([]byte, 4096)
614 for {
615 n, err := stderr.Read(buf)
616 if err != nil {
617 if err != io.EOF {
618 slog.Error("Error reading stderr", "error", err)
619 }
620 break
621 }
622 if n > 0 {
623 slog.Error("Language server stderr", "command", config.Command, "output", string(buf[:n]))
624 }
625 }
626 }()
627
628 // Monitor process exit
629 go func() {
630 if err := cmd.Wait(); err != nil {
631 slog.Error("Language server process exited with error", "command", config.Command, "error", err)
632 } else {
633 slog.Info("Language server process exited normally", "command", config.Command)
634 }
635 }()
636
637 // Create a stream transport
638 stream := transport.NewStreamTransport(stdout, stdin, &processCloser{
639 cmd: cmd,
640 stdin: stdin,
641 stdout: stdout,
642 stderr: stderr,
643 })
644
645 return stream, nil
646 }
647
648 type processCloser struct {
649 cmd *exec.Cmd
650 stdin io.WriteCloser
651 stdout io.ReadCloser
652 stderr io.ReadCloser
653 mu sync.Mutex
654 }
655
656 func (c *processCloser) Close() error {
657 c.mu.Lock()
658 defer c.mu.Unlock()
659
660 var errs []error
661
662 if err := c.stdin.Close(); err != nil {
663 errs = append(errs, err)
664 }
665
666 if err := c.stdout.Close(); err != nil {
667 errs = append(errs, err)
668 }
669
670 if err := c.stderr.Close(); err != nil {
671 errs = append(errs, err)
672 }
673
674 // Give the process time to exit gracefully
675 done := make(chan error, 1)
676 go func() {
677 done <- c.cmd.Wait()
678 }()
679
680 select {
681 case <-done:
682 // Process exited
683 case <-time.After(5 * time.Second):
684 // Timeout, kill the process
685 if err := c.cmd.Process.Kill(); err != nil {
686 errs = append(errs, err)
687 }
688 }
689
690 if len(errs) > 0 {
691 return fmt.Errorf("errors closing process: %v", errs)
692 }
693
694 return nil
695 }