Debian Codegraph @

gopls/internal/test/integration/fake/editor.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package fake
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "maps"
14 "math/rand/v2"
15 "os"
16 "path"
17 "path/filepath"
18 "regexp"
19 "slices"
20 "strings"
21 "sync"
22 "time"
23 "unicode/utf8"
24
25 "golang.org/x/tools/gopls/internal/protocol"
26 "golang.org/x/tools/gopls/internal/protocol/command"
27 "golang.org/x/tools/gopls/internal/test/integration/fake/glob"
28 "golang.org/x/tools/gopls/internal/util/bug"
29 "golang.org/x/tools/gopls/internal/util/pathutil"
30 "golang.org/x/tools/internal/jsonrpc2"
31 "golang.org/x/tools/internal/jsonrpc2/servertest"
32 )
33
34 // Editor is a fake client editor. It keeps track of client state and can be
35 // used for writing LSP tests.
36 type Editor struct {
37 // Server, client, and sandbox are concurrency safe and written only
38 // at construction time, so do not require synchronization.
39 Server protocol.Server
40 cancelConn func()
41 serverConn jsonrpc2.Conn
42 client *Client
43 sandbox *Sandbox
44
45 // TODO(rfindley): buffers should be keyed by protocol.DocumentURI.
46 mu sync.Mutex
47 config EditorConfig // editor configuration
48 buffers map[string]buffer // open buffers (relative path -> buffer content)
49 watchPatterns []*glob.Glob // glob patterns to watch
50 suggestionUseReplaceMode bool
51
52 // These fields are populated by Connect.
53 serverCapabilities protocol.ServerCapabilities
54 semTokOpts protocol.SemanticTokensOptions
55
56 // Call metrics for the purpose of expectations. This is done in an ad-hoc
57 // manner for now. Perhaps in the future we should do something more
58 // systematic. Guarded with a separate mutex as calls may need to be accessed
59 // asynchronously via callbacks into the Editor.
60 callsMu sync.Mutex
61 calls CallCounts
62 }
63
64 // CallCounts tracks the number of protocol notifications of different types.
65 type CallCounts struct {
66 DidOpen, DidChange, DidSave, DidChangeWatchedFiles, DidClose, DidChangeConfiguration uint64
67 }
68
69 // buffer holds information about an open buffer in the editor.
70 type buffer struct {
71 version int // monotonic version; incremented on edits
72 path string // relative path in the workspace
73 mapper *protocol.Mapper // buffer content
74 dirty bool // if true, content is unsaved (TODO(rfindley): rename this field)
75 }
76
77 func (b buffer) text() string {
78 return string(b.mapper.Content)
79 }
80
81 // EditorConfig configures the editor's LSP session. This is similar to
82 // golang.UserOptions, but we use a separate type here so that we expose only
83 // that configuration which we support.
84 //
85 // The zero value for EditorConfig is the default configuration.
86 type EditorConfig struct {
87 // ClientName sets the clientInfo.name for the LSP session (in the initialize request).
88 //
89 // Since this can only be set during initialization, changing this field via
90 // Editor.ChangeConfiguration has no effect.
91 //
92 // If empty, "fake.Editor" is used.
93 ClientName string
94
95 // Env holds environment variables to apply on top of the default editor
96 // environment. When applying these variables, the special string
97 // $SANDBOX_WORKDIR is replaced by the absolute path to the sandbox working
98 // directory.
99 Env map[string]string
100
101 // WorkspaceFolders is the workspace folders to configure on the LSP server.
102 // Each workspace folder is a file path relative to the sandbox workdir, or
103 // a uri (used when testing behavior with virtual file system or non-'file'
104 // scheme document uris).
105 //
106 // As special cases, if WorkspaceFolders is nil the editor defaults to
107 // configuring a single workspace folder corresponding to the workdir root.
108 // To explicitly send no workspace folders, use an empty (non-nil) slice.
109 WorkspaceFolders []string
110
111 // NoDefaultWorkspaceFiles is used to specify whether the fake editor
112 // should give a default workspace folder when WorkspaceFolders is nil.
113 // When it's true, the editor will pass original WorkspaceFolders as is to the LSP server.
114 NoDefaultWorkspaceFiles bool
115
116 // RelRootPath is the root path which will be converted to rootUri to configure on the LSP server.
117 RelRootPath string
118
119 // Whether to edit files with windows line endings.
120 WindowsLineEndings bool
121
122 // Map of language ID -> regexp to match, used to set the file type of new
123 // buffers. Applied as an overlay on top of the following defaults:
124 // "go" -> ".*\.go"
125 // "go.mod" -> "go\.mod"
126 // "go.sum" -> "go\.sum"
127 // "gotmpl" -> ".*tmpl"
128 // "go.s" -> ".*\.s"
129 FileAssociations map[protocol.LanguageKind]string
130
131 // Settings holds user-provided configuration for the LSP server.
132 Settings map[string]any
133
134 // FolderSettings holds user-provided per-folder configuration, if any.
135 //
136 // It maps each folder (as a relative path to the sandbox workdir) to its
137 // configuration mapping (like Settings).
138 FolderSettings map[string]map[string]any
139
140 // CapabilitiesJSON holds JSON client capabilities to overlay over the
141 // editor's default client capabilities.
142 //
143 // Specifically, this JSON string will be unmarshalled into the editor's
144 // client capabilities struct, before sending to the server.
145 CapabilitiesJSON []byte
146
147 // If non-nil, MessageResponder is used to respond to ShowMessageRequest
148 // messages.
149 MessageResponder func(params *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error)
150
151 // MaxMessageDelay is used for fuzzing message delivery to reproduce test
152 // flakes.
153 MaxMessageDelay time.Duration
154 }
155
156 // NewEditor creates a new Editor.
157 func NewEditor(sandbox *Sandbox, config EditorConfig) *Editor {
158 return &Editor{
159 buffers: make(map[string]buffer),
160 sandbox: sandbox,
161 config: config,
162 }
163 }
164
165 // Connect configures the editor to communicate with an LSP server on conn. It
166 // is not concurrency safe, and should be called at most once, before using the
167 // editor.
168 //
169 // It returns the editor, so that it may be called as follows:
170 //
171 // editor, err := NewEditor(s).Connect(ctx, conn, hooks)
172 func (e *Editor) Connect(ctx context.Context, connector servertest.Connector, hooks ClientHooks) (*Editor, error) {
173 bgCtx, cancelConn := context.WithCancel(context.WithoutCancel(ctx))
174 conn := connector.Connect(bgCtx)
175 e.cancelConn = cancelConn
176
177 e.serverConn = conn
178 e.Server = protocol.ServerDispatcher(conn)
179 e.client = &Client{editor: e, hooks: hooks}
180 handler := protocol.ClientHandler(e.client, jsonrpc2.MethodNotFound)
181 if e.config.MaxMessageDelay > 0 {
182 handler = DelayedHandler(e.config.MaxMessageDelay, handler)
183 }
184 conn.Go(bgCtx, protocol.Handlers(handler))
185
186 if err := e.initialize(ctx); err != nil {
187 return nil, err
188 }
189 e.sandbox.Workdir.AddWatcher(e.onFileChanges)
190 return e, nil
191 }
192
193 // DelayedHandler waits [0, maxDelay) before handling each message.
194 func DelayedHandler(maxDelay time.Duration, handler jsonrpc2.Handler) jsonrpc2.Handler {
195 return func(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) error {
196 delay := time.Duration(rand.Int64N(int64(maxDelay)))
197 select {
198 case <-ctx.Done():
199 case <-time.After(delay):
200 }
201 return handler(ctx, reply, req)
202 }
203 }
204
205 func (e *Editor) Stats() CallCounts {
206 e.callsMu.Lock()
207 defer e.callsMu.Unlock()
208 return e.calls
209 }
210
211 // Shutdown issues the 'shutdown' LSP notification.
212 func (e *Editor) Shutdown(ctx context.Context) error {
213 if e.Server != nil {
214 if err := e.Server.Shutdown(ctx); err != nil {
215 return fmt.Errorf("Shutdown: %w", err)
216 }
217 }
218 return nil
219 }
220
221 // Exit issues the 'exit' LSP notification.
222 func (e *Editor) Exit(ctx context.Context) error {
223 if e.Server != nil {
224 // Not all LSP clients issue the exit RPC, but we do so here to ensure that
225 // we gracefully handle it on multi-session servers.
226 if err := e.Server.Exit(ctx); err != nil {
227 return fmt.Errorf("Exit: %w", err)
228 }
229 }
230 return nil
231 }
232
233 // Close disconnects the LSP client session.
234 // TODO(rfindley): rename to 'Disconnect'.
235 func (e *Editor) Close(ctx context.Context) error {
236 if err := e.Shutdown(ctx); err != nil {
237 return err
238 }
239 if err := e.Exit(ctx); err != nil {
240 return err
241 }
242 defer func() {
243 e.cancelConn()
244 }()
245
246 // called close on the editor should result in the connection closing
247 select {
248 case <-e.serverConn.Done():
249 // connection closed itself
250 return nil
251 case <-ctx.Done():
252 return fmt.Errorf("connection not closed: %w", ctx.Err())
253 }
254 }
255
256 // Client returns the LSP client for this editor.
257 func (e *Editor) Client() *Client {
258 return e.client
259 }
260
261 // makeSettings builds the settings map for use in LSP settings RPCs.
262 func makeSettings(sandbox *Sandbox, config EditorConfig, scopeURI *protocol.URI) map[string]any {
263 env := make(map[string]string)
264 maps.Copy(env, sandbox.GoEnv())
265 maps.Copy(env, config.Env)
266 for k, v := range env {
267 v = strings.ReplaceAll(v, "$SANDBOX_WORKDIR", sandbox.Workdir.RootURI().Path())
268 env[k] = v
269 }
270
271 settings := map[string]any{
272 "env": env,
273
274 // Use verbose progress reporting so that integration tests can assert on
275 // asynchronous operations being completed (such as diagnosing a snapshot).
276 "verboseWorkDoneProgress": true,
277
278 // Set an unlimited completion budget, so that tests don't flake because
279 // completions are too slow.
280 "completionBudget": "0s",
281 }
282
283 for k, v := range config.Settings {
284 if k == "env" {
285 panic("must not provide env via the EditorConfig.Settings field: use the EditorConfig.Env field instead")
286 }
287 settings[k] = v
288 }
289
290 // If the server is requesting configuration for a specific scope, apply
291 // settings for the nearest folder that has customized settings, if any.
292 if scopeURI != nil {
293 var (
294 scopePath = protocol.DocumentURI(*scopeURI).Path()
295 closestDir string // longest dir with settings containing the scope, if any
296 closestSettings map[string]any // settings for that dir, if any
297 )
298 for relPath, settings := range config.FolderSettings {
299 dir := sandbox.Workdir.AbsPath(relPath)
300 if strings.HasPrefix(scopePath+string(filepath.Separator), dir+string(filepath.Separator)) && len(dir) > len(closestDir) {
301 closestDir = dir
302 closestSettings = settings
303 }
304 }
305 if closestSettings != nil {
306 maps.Copy(settings, closestSettings)
307 }
308 }
309
310 return settings
311 }
312
313 func (e *Editor) initialize(ctx context.Context) error {
314 config := e.Config()
315
316 clientName := config.ClientName
317 if clientName == "" {
318 clientName = "fake.Editor"
319 }
320
321 params := &protocol.ParamInitialize{}
322 params.ClientInfo = &protocol.ClientInfo{
323 Name: clientName,
324 Version: "v1.0.0",
325 }
326 params.InitializationOptions = makeSettings(e.sandbox, config, nil)
327
328 params.WorkspaceFolders = makeWorkspaceFolders(e.sandbox, config.WorkspaceFolders, config.NoDefaultWorkspaceFiles)
329 params.RootURI = protocol.URIFromPath(config.RelRootPath)
330 if !uriRE.MatchString(config.RelRootPath) { // relative file path
331 params.RootURI = e.sandbox.Workdir.URI(config.RelRootPath)
332 }
333
334 capabilities, err := clientCapabilities(config)
335 if err != nil {
336 return fmt.Errorf("unmarshalling EditorConfig.CapabilitiesJSON: %v", err)
337 }
338 params.Capabilities = capabilities
339
340 trace := protocol.TraceValue("messages")
341 params.Trace = &trace
342 // TODO: support workspace folders.
343 if e.Server != nil {
344 resp, err := e.Server.Initialize(ctx, params)
345 if err != nil {
346 return fmt.Errorf("initialize: %w", err)
347 }
348 semTokOpts, err := marshalUnmarshal[protocol.SemanticTokensOptions](resp.Capabilities.SemanticTokensProvider)
349 if err != nil {
350 return fmt.Errorf("unmarshalling semantic tokens options: %v", err)
351 }
352 e.serverCapabilities = resp.Capabilities
353 e.semTokOpts = semTokOpts
354
355 if err := e.Server.Initialized(ctx, &protocol.InitializedParams{}); err != nil {
356 return fmt.Errorf("initialized: %w", err)
357 }
358 }
359 // TODO: await initial configuration here, or expect gopls to manage that?
360 return nil
361 }
362
363 func clientCapabilities(cfg EditorConfig) (protocol.ClientCapabilities, error) {
364 var capabilities protocol.ClientCapabilities
365 // Set various client capabilities that are sought by gopls.
366 capabilities.Workspace.Configuration = true // support workspace/configuration
367 capabilities.TextDocument.Completion.CompletionItem.TagSupport = &protocol.CompletionItemTagOptions{}
368 capabilities.TextDocument.Completion.CompletionItem.TagSupport.ValueSet = []protocol.CompletionItemTag{protocol.ComplDeprecated}
369 capabilities.TextDocument.Completion.CompletionItem.SnippetSupport = true
370 capabilities.TextDocument.Completion.CompletionItem.InsertReplaceSupport = true
371 capabilities.TextDocument.SemanticTokens.Requests.Full = &protocol.Or_ClientSemanticTokensRequestOptions_full{Value: true}
372 capabilities.Window.WorkDoneProgress = true // support window/workDoneProgress
373 capabilities.Window.ShowDocument = &protocol.ShowDocumentClientCapabilities{Support: true} // support window/showDocument
374 capabilities.TextDocument.SemanticTokens.TokenTypes = []string{
375 "namespace", "type", "class", "enum", "interface",
376 "struct", "typeParameter", "parameter", "variable", "property", "enumMember",
377 "event", "function", "method", "macro", "keyword", "modifier", "comment",
378 "string", "number", "regexp", "operator",
379 // Additional types supported by this client:
380 "label",
381 }
382 capabilities.TextDocument.SemanticTokens.TokenModifiers = []string{
383 "declaration", "definition", "readonly", "static",
384 "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary",
385 // Additional modifiers supported by this client:
386 "interface", "struct", "signature", "pointer", "array", "map", "slice", "chan", "string", "number", "bool", "invalid",
387 }
388 // Request that the server provide its complete list of code action kinds.
389 capabilities.TextDocument.CodeAction = protocol.CodeActionClientCapabilities{
390 DataSupport: true,
391 ResolveSupport: &protocol.ClientCodeActionResolveOptions{
392 Properties: []string{"edit"},
393 },
394 CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{
395 CodeActionKind: protocol.ClientCodeActionKindOptions{
396 ValueSet: []protocol.CodeActionKind{protocol.Empty}, // => all
397 },
398 },
399 }
400 // The LSP tests have historically enabled this flag,
401 // but really we should test both ways for older editors.
402 capabilities.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport = true
403 // Glob pattern watching is enabled.
404 capabilities.Workspace.DidChangeWatchedFiles.DynamicRegistration = true
405 // "rename" operations are used for package renaming.
406 //
407 // TODO(rfindley): add support for other resource operations (create, delete, ...)
408 capabilities.Workspace.WorkspaceEdit = &protocol.WorkspaceEditClientCapabilities{
409 ResourceOperations: []protocol.ResourceOperationKind{
410 "rename",
411 },
412 }
413
414 // Apply capabilities overlay.
415 if cfg.CapabilitiesJSON != nil {
416 if err := json.Unmarshal(cfg.CapabilitiesJSON, &capabilities); err != nil {
417 return protocol.ClientCapabilities{}, fmt.Errorf("unmarshalling EditorConfig.CapabilitiesJSON: %v", err)
418 }
419 }
420 return capabilities, nil
421 }
422
423 // Returns the connected LSP server's capabilities.
424 // Only populated after a call to [Editor.Connect].
425 func (e *Editor) ServerCapabilities() protocol.ServerCapabilities {
426 return e.serverCapabilities
427 }
428
429 // marshalUnmarshal is a helper to json Marshal and then Unmarshal as a
430 // different type. Used to work around cases where our protocol types are not
431 // specific.
432 func marshalUnmarshal[T any](v any) (T, error) {
433 var t T
434 data, err := json.Marshal(v)
435 if err != nil {
436 return t, err
437 }
438 err = json.Unmarshal(data, &t)
439 return t, err
440 }
441
442 // HasCommand reports whether the connected server supports the command with the given ID.
443 func (e *Editor) HasCommand(cmd command.Command) bool {
444 return slices.Contains(e.serverCapabilities.ExecuteCommandProvider.Commands, cmd.String())
445 }
446
447 // Examples: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
448 var uriRE = regexp.MustCompile(`^[a-z][a-z0-9+\-.]*://\S+`)
449
450 // makeWorkspaceFolders creates a slice of workspace folders to use for
451 // this editing session, based on the editor configuration.
452 func makeWorkspaceFolders(sandbox *Sandbox, paths []string, useEmpty bool) (folders []protocol.WorkspaceFolder) {
453 if len(paths) == 0 {
454 if useEmpty {
455 return nil
456 }
457 paths = []string{string(sandbox.Workdir.RelativeTo)}
458 }
459
460 for _, path := range paths {
461 uri := path
462 if !uriRE.MatchString(path) { // relative file path
463 uri = string(sandbox.Workdir.URI(path))
464 }
465 folders = append(folders, protocol.WorkspaceFolder{
466 URI: uri,
467 Name: filepath.Base(uri),
468 })
469 }
470
471 return folders
472 }
473
474 // onFileChanges is registered to be called by the Workdir on any writes that
475 // go through the Workdir API. It is called synchronously by the Workdir.
476 func (e *Editor) onFileChanges(ctx context.Context, evts []protocol.FileEvent) {
477 if e.Server == nil {
478 return
479 }
480
481 // e may be locked when onFileChanges is called, but it is important that we
482 // synchronously increment this counter so that we can subsequently assert on
483 // the number of expected DidChangeWatchedFiles calls.
484 e.callsMu.Lock()
485 e.calls.DidChangeWatchedFiles++
486 e.callsMu.Unlock()
487
488 // Since e may be locked, we must run this mutation asynchronously.
489 go func() {
490 e.mu.Lock()
491 defer e.mu.Unlock()
492 for _, evt := range evts {
493 // Always send an on-disk change, even for events that seem useless
494 // because they're shadowed by an open buffer.
495 path := e.sandbox.Workdir.URIToPath(evt.URI)
496 if buf, ok := e.buffers[path]; ok {
497 // Following VS Code, don't honor deletions or changes to dirty buffers.
498 if buf.dirty || evt.Type == protocol.Deleted {
499 continue
500 }
501
502 content, err := e.sandbox.Workdir.ReadFile(path)
503 if err != nil {
504 continue // A race with some other operation.
505 }
506 // No need to update if the buffer content hasn't changed.
507 if string(content) == buf.text() {
508 continue
509 }
510 // During shutdown, this call will fail. Ignore the error.
511 _ = e.setBufferContentLocked(ctx, path, false, content, nil)
512 }
513 }
514 var matchedEvts []protocol.FileEvent
515 for _, evt := range evts {
516 filename := filepath.ToSlash(evt.URI.Path())
517 for _, g := range e.watchPatterns {
518 if g.Match(filename) {
519 matchedEvts = append(matchedEvts, evt)
520 break
521 }
522 }
523 }
524
525 // TODO(rfindley): don't send notifications while locked.
526 e.Server.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{
527 Changes: matchedEvts,
528 })
529 }()
530 }
531
532 // OpenFile creates a buffer for the given workdir-relative file.
533 //
534 // If the file is already open, it is a no-op.
535 func (e *Editor) OpenFile(ctx context.Context, path string) error {
536 if e.HasBuffer(path) {
537 return nil
538 }
539 content, err := e.sandbox.Workdir.ReadFile(path)
540 if err != nil {
541 return err
542 }
543 if e.Config().WindowsLineEndings {
544 content = toWindowsLineEndings(content)
545 }
546 return e.createBuffer(ctx, path, false, content)
547 }
548
549 // toWindowsLineEndings checks whether content has windows line endings.
550 //
551 // If so, it returns content unmodified. If not, it returns a new byte slice modified to use CRLF line endings.
552 func toWindowsLineEndings(content []byte) []byte {
553 abnormal := false
554 for i, b := range content {
555 if b == '\n' && (i == 0 || content[i-1] != '\r') {
556 abnormal = true
557 break
558 }
559 }
560 if !abnormal {
561 return content
562 }
563 var buf bytes.Buffer
564 for i, b := range content {
565 if b == '\n' && (i == 0 || content[i-1] != '\r') {
566 buf.WriteByte('\r')
567 }
568 buf.WriteByte(b)
569 }
570 return buf.Bytes()
571 }
572
573 // CreateBuffer creates a new unsaved buffer corresponding to the workdir path,
574 // containing the given textual content.
575 func (e *Editor) CreateBuffer(ctx context.Context, path, content string) error {
576 return e.createBuffer(ctx, path, true, []byte(content))
577 }
578
579 func (e *Editor) createBuffer(ctx context.Context, path string, dirty bool, content []byte) error {
580 e.mu.Lock()
581
582 if _, ok := e.buffers[path]; ok {
583 e.mu.Unlock()
584 return fmt.Errorf("buffer %q already exists", path)
585 }
586
587 uri := e.sandbox.Workdir.URI(path)
588 buf := buffer{
589 version: 1,
590 path: path,
591 mapper: protocol.NewMapper(uri, content),
592 dirty: dirty,
593 }
594 e.buffers[path] = buf
595
596 item := e.textDocumentItem(buf)
597 e.mu.Unlock()
598
599 return e.sendDidOpen(ctx, item)
600 }
601
602 // textDocumentItem builds a protocol.TextDocumentItem for the given buffer.
603 //
604 // Precondition: e.mu must be held.
605 func (e *Editor) textDocumentItem(buf buffer) protocol.TextDocumentItem {
606 return protocol.TextDocumentItem{
607 URI: e.sandbox.Workdir.URI(buf.path),
608 LanguageID: languageID(buf.path, e.config.FileAssociations),
609 Version: int32(buf.version),
610 Text: buf.text(),
611 }
612 }
613
614 func (e *Editor) sendDidOpen(ctx context.Context, item protocol.TextDocumentItem) error {
615 if e.Server != nil {
616 if err := e.Server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{
617 TextDocument: item,
618 }); err != nil {
619 return fmt.Errorf("DidOpen: %w", err)
620 }
621 e.callsMu.Lock()
622 e.calls.DidOpen++
623 e.callsMu.Unlock()
624 }
625 return nil
626 }
627
628 var defaultFileAssociations = map[protocol.LanguageKind]*regexp.Regexp{
629 "go": regexp.MustCompile(`^.*\.go$`), // '$' is important: don't match .gotmpl!
630 "go.mod": regexp.MustCompile(`^go\.mod$`),
631 "go.sum": regexp.MustCompile(`^go(\.work)?\.sum$`),
632 "go.work": regexp.MustCompile(`^go\.work$`),
633 "gotmpl": regexp.MustCompile(`^.*tmpl$`),
634 "go.s": regexp.MustCompile(`\.s$`),
635 }
636
637 // languageID returns the language identifier for the path p given the user
638 // configured fileAssociations.
639 func languageID(p string, fileAssociations map[protocol.LanguageKind]string) protocol.LanguageKind {
640 base := path.Base(p)
641 for lang, re := range fileAssociations {
642 re := regexp.MustCompile(re)
643 if re.MatchString(base) {
644 return lang
645 }
646 }
647 for lang, re := range defaultFileAssociations {
648 if re.MatchString(base) {
649 return lang
650 }
651 }
652 return ""
653 }
654
655 // CloseBuffer removes the current buffer (regardless of whether it is saved).
656 // CloseBuffer returns an error if the buffer is not open.
657 func (e *Editor) CloseBuffer(ctx context.Context, path string) error {
658 e.mu.Lock()
659 _, ok := e.buffers[path]
660 if !ok {
661 e.mu.Unlock()
662 return ErrUnknownBuffer
663 }
664 delete(e.buffers, path)
665 e.mu.Unlock()
666
667 return e.sendDidClose(ctx, e.TextDocumentIdentifier(path))
668 }
669
670 func (e *Editor) sendDidClose(ctx context.Context, doc protocol.TextDocumentIdentifier) error {
671 if e.Server != nil {
672 if err := e.Server.DidClose(ctx, &protocol.DidCloseTextDocumentParams{
673 TextDocument: doc,
674 }); err != nil {
675 return fmt.Errorf("DidClose: %w", err)
676 }
677 e.callsMu.Lock()
678 e.calls.DidClose++
679 e.callsMu.Unlock()
680 }
681 return nil
682 }
683
684 func (e *Editor) DocumentURI(path string) protocol.DocumentURI {
685 return e.sandbox.Workdir.URI(path)
686 }
687
688 func (e *Editor) TextDocumentIdentifier(path string) protocol.TextDocumentIdentifier {
689 return protocol.TextDocumentIdentifier{
690 URI: e.DocumentURI(path),
691 }
692 }
693
694 // SaveBuffer writes the content of the buffer specified by the given path to
695 // the filesystem.
696 func (e *Editor) SaveBuffer(ctx context.Context, path string) error {
697 if err := e.OrganizeImports(ctx, path); err != nil {
698 return fmt.Errorf("organizing imports before save: %w", err)
699 }
700 if err := e.FormatBuffer(ctx, path); err != nil {
701 return fmt.Errorf("formatting before save: %w", err)
702 }
703 return e.SaveBufferWithoutActions(ctx, path)
704 }
705
706 func (e *Editor) SaveBufferWithoutActions(ctx context.Context, path string) error {
707 e.mu.Lock()
708 defer e.mu.Unlock()
709 buf, ok := e.buffers[path]
710 if !ok {
711 return fmt.Errorf("unknown buffer: %q", path)
712 }
713 content := buf.text()
714 includeText := false
715 syncOptions, ok := e.serverCapabilities.TextDocumentSync.(protocol.TextDocumentSyncOptions)
716 if ok {
717 includeText = syncOptions.Save.IncludeText
718 }
719
720 docID := e.TextDocumentIdentifier(buf.path)
721 if e.Server != nil {
722 if err := e.Server.WillSave(ctx, &protocol.WillSaveTextDocumentParams{
723 TextDocument: docID,
724 Reason: protocol.Manual,
725 }); err != nil {
726 return fmt.Errorf("WillSave: %w", err)
727 }
728 }
729 if err := e.sandbox.Workdir.WriteFile(ctx, path, content); err != nil {
730 return fmt.Errorf("writing %q: %w", path, err)
731 }
732
733 buf.dirty = false
734 e.buffers[path] = buf
735
736 if e.Server != nil {
737 params := &protocol.DidSaveTextDocumentParams{
738 TextDocument: docID,
739 }
740 if includeText {
741 params.Text = &content
742 }
743 if err := e.Server.DidSave(ctx, params); err != nil {
744 return fmt.Errorf("DidSave: %w", err)
745 }
746 e.callsMu.Lock()
747 e.calls.DidSave++
748 e.callsMu.Unlock()
749 }
750 return nil
751 }
752
753 // ErrNoMatch is returned if a regexp search fails.
754 var (
755 ErrNoMatch = errors.New("no match")
756 ErrUnknownBuffer = errors.New("unknown buffer")
757 )
758
759 // regexpLocation returns the location of the first occurrence of either re
760 // or its singular subgroup. It returns ErrNoMatch if the regexp doesn't match.
761 func regexpLocation(mapper *protocol.Mapper, re string) (protocol.Location, error) {
762 var start, end int
763 rec, err := regexp.Compile(re)
764 if err != nil {
765 return protocol.Location{}, err
766 }
767 indexes := rec.FindSubmatchIndex(mapper.Content)
768 if indexes == nil {
769 return protocol.Location{}, ErrNoMatch
770 }
771 switch len(indexes) {
772 case 2:
773 // no subgroups: return the range of the regexp expression
774 start, end = indexes[0], indexes[1]
775 case 4:
776 // one subgroup: return its range
777 start, end = indexes[2], indexes[3]
778 default:
779 return protocol.Location{}, fmt.Errorf("invalid search regexp %q: expect either 0 or 1 subgroups, got %d", re, len(indexes)/2-1)
780 }
781 return mapper.OffsetLocation(start, end)
782 }
783
784 // RegexpSearch returns the Location of the first match for re in the buffer
785 // bufName. For convenience, RegexpSearch supports the following two modes:
786 // 1. If re has no subgroups, return the position of the match for re itself.
787 // 2. If re has one subgroup, return the position of the first subgroup.
788 //
789 // It returns an error re is invalid, has more than one subgroup, or doesn't
790 // match the buffer.
791 func (e *Editor) RegexpSearch(bufName, re string) (protocol.Location, error) {
792 e.mu.Lock()
793 buf, ok := e.buffers[bufName]
794 e.mu.Unlock()
795 if !ok {
796 return protocol.Location{}, ErrUnknownBuffer
797 }
798 return regexpLocation(buf.mapper, re)
799 }
800
801 // RegexpReplace edits the buffer corresponding to path by replacing the first
802 // instance of re, or its first subgroup, with the replace text. See
803 // RegexpSearch for more explanation of these two modes.
804 // It returns an error if re is invalid, has more than one subgroup, or doesn't
805 // match the buffer.
806 func (e *Editor) RegexpReplace(ctx context.Context, path, re, replace string) error {
807 e.mu.Lock()
808 defer e.mu.Unlock()
809 buf, ok := e.buffers[path]
810 if !ok {
811 return ErrUnknownBuffer
812 }
813 loc, err := regexpLocation(buf.mapper, re)
814 if err != nil {
815 return err
816 }
817 edits := []protocol.TextEdit{{
818 Range: loc.Range,
819 NewText: replace,
820 }}
821 patched, err := applyEdits(buf.mapper, edits, e.config.WindowsLineEndings)
822 if err != nil {
823 return fmt.Errorf("editing %q: %v", path, err)
824 }
825 return e.setBufferContentLocked(ctx, path, true, patched, edits)
826 }
827
828 // EditBuffer applies the given test edits to the buffer identified by path.
829 func (e *Editor) EditBuffer(ctx context.Context, path string, edits []protocol.TextEdit) error {
830 e.mu.Lock()
831 defer e.mu.Unlock()
832 return e.editBufferLocked(ctx, path, edits)
833 }
834
835 func (e *Editor) SetBufferContent(ctx context.Context, path, content string) error {
836 e.mu.Lock()
837 defer e.mu.Unlock()
838 return e.setBufferContentLocked(ctx, path, true, []byte(content), nil)
839 }
840
841 // HasBuffer reports whether the file name is open in the editor.
842 func (e *Editor) HasBuffer(name string) bool {
843 e.mu.Lock()
844 defer e.mu.Unlock()
845 _, ok := e.buffers[name]
846 return ok
847 }
848
849 // BufferText returns the content of the buffer with the given name, or "" if
850 // the file at that path is not open. The second return value reports whether
851 // the file is open.
852 func (e *Editor) BufferText(name string) (string, bool) {
853 e.mu.Lock()
854 defer e.mu.Unlock()
855 buf, ok := e.buffers[name]
856 if !ok {
857 return "", false
858 }
859 return buf.text(), true
860 }
861
862 // Mapper returns the protocol.Mapper for the given buffer name, if it is open.
863 func (e *Editor) Mapper(name string) (*protocol.Mapper, error) {
864 e.mu.Lock()
865 defer e.mu.Unlock()
866 buf, ok := e.buffers[name]
867 if !ok {
868 return nil, fmt.Errorf("no mapper for %q", name)
869 }
870 return buf.mapper, nil
871 }
872
873 // BufferVersion returns the current version of the buffer corresponding to
874 // name (or 0 if it is not being edited).
875 func (e *Editor) BufferVersion(name string) int {
876 e.mu.Lock()
877 defer e.mu.Unlock()
878 return e.buffers[name].version
879 }
880
881 func (e *Editor) editBufferLocked(ctx context.Context, path string, edits []protocol.TextEdit) error {
882 buf, ok := e.buffers[path]
883 if !ok {
884 return fmt.Errorf("unknown buffer %q", path)
885 }
886 content, err := applyEdits(buf.mapper, edits, e.config.WindowsLineEndings)
887 if err != nil {
888 return fmt.Errorf("editing %q: %v; edits:\n%v", path, err, edits)
889 }
890 return e.setBufferContentLocked(ctx, path, true, content, edits)
891 }
892
893 func (e *Editor) setBufferContentLocked(ctx context.Context, path string, dirty bool, content []byte, fromEdits []protocol.TextEdit) error {
894 buf, ok := e.buffers[path]
895 if !ok {
896 return fmt.Errorf("unknown buffer %q", path)
897 }
898 buf.mapper = protocol.NewMapper(buf.mapper.URI, content)
899 buf.version++
900 buf.dirty = dirty
901 e.buffers[path] = buf
902
903 // A simple heuristic: if there is only one edit, send it incrementally.
904 // Otherwise, send the entire content.
905 var evt protocol.TextDocumentContentChangeEvent
906 if len(fromEdits) == 1 {
907 evt.Range = &fromEdits[0].Range
908 evt.Text = fromEdits[0].NewText
909 } else {
910 evt.Text = buf.text()
911 }
912 params := &protocol.DidChangeTextDocumentParams{
913 TextDocument: protocol.VersionedTextDocumentIdentifier{
914 Version: int32(buf.version),
915 TextDocumentIdentifier: e.TextDocumentIdentifier(buf.path),
916 },
917 ContentChanges: []protocol.TextDocumentContentChangeEvent{evt},
918 }
919 if e.Server != nil {
920 if err := e.Server.DidChange(ctx, params); err != nil {
921 return fmt.Errorf("DidChange: %w", err)
922 }
923 e.callsMu.Lock()
924 e.calls.DidChange++
925 e.callsMu.Unlock()
926 }
927 return nil
928 }
929
930 // Definitions returns the definitions of the symbol at the given
931 // location in an open buffer.
932 func (e *Editor) Definitions(ctx context.Context, loc protocol.Location) ([]protocol.Location, error) {
933 if err := e.checkBufferLocation(loc); err != nil {
934 return nil, err
935 }
936 params := &protocol.DefinitionParams{}
937 params.TextDocument.URI = loc.URI
938 params.Position = loc.Range.Start
939
940 return e.Server.Definition(ctx, params)
941 }
942
943 // TypeDefinitions returns the type definitions of the symbol at the
944 // given location in an open buffer.
945 func (e *Editor) TypeDefinitions(ctx context.Context, loc protocol.Location) ([]protocol.Location, error) {
946 if err := e.checkBufferLocation(loc); err != nil {
947 return nil, err
948 }
949 params := &protocol.TypeDefinitionParams{}
950 params.TextDocument.URI = loc.URI
951 params.Position = loc.Range.Start
952 params.Range = loc.Range
953
954 return e.Server.TypeDefinition(ctx, params)
955 }
956
957 // Symbol performs a workspace symbol search using query
958 func (e *Editor) Symbol(ctx context.Context, query string) ([]protocol.SymbolInformation, error) {
959 params := &protocol.WorkspaceSymbolParams{Query: query}
960 return e.Server.Symbol(ctx, params)
961 }
962
963 // OrganizeImports requests and performs the source.organizeImports codeAction.
964 func (e *Editor) OrganizeImports(ctx context.Context, path string) error {
965 loc := e.sandbox.Workdir.EntireFile(path)
966 _, err := e.applyCodeActions(ctx, loc, nil, protocol.SourceOrganizeImports)
967 return err
968 }
969
970 // RefactorRewrite requests and performs the source.refactorRewrite codeAction.
971 func (e *Editor) RefactorRewrite(ctx context.Context, loc protocol.Location) error {
972 applied, err := e.applyCodeActions(ctx, loc, nil, protocol.RefactorRewrite)
973 if err != nil {
974 return err
975 }
976 if applied == 0 {
977 return fmt.Errorf("no refactorings were applied")
978 }
979 return nil
980 }
981
982 // ApplyQuickFixes requests and performs the quickfix codeAction.
983 func (e *Editor) ApplyQuickFixes(ctx context.Context, loc protocol.Location, diagnostics []protocol.Diagnostic) error {
984 applied, err := e.applyCodeActions(ctx, loc, diagnostics, protocol.SourceFixAll, protocol.QuickFix)
985 if applied == 0 {
986 return fmt.Errorf("no quick fixes were applied")
987 }
988 return err
989 }
990
991 // ApplyCodeAction applies the given code action.
992 func (e *Editor) ApplyCodeAction(ctx context.Context, action protocol.CodeAction) error {
993 // Resolve the code actions if necessary and supported.
994 if action.Edit == nil {
995 editSupport, err := e.EditResolveSupport()
996 if err != nil {
997 return err
998 }
999 if editSupport {
1000 ca, err := e.Server.ResolveCodeAction(ctx, &action)
1001 if err != nil {
1002 return err
1003 }
1004 action = *ca
1005 }
1006 }
1007
1008 if action.Edit != nil {
1009 for _, change := range action.Edit.DocumentChanges {
1010 if change.TextDocumentEdit != nil {
1011 path := e.sandbox.Workdir.URIToPath(change.TextDocumentEdit.TextDocument.URI)
1012 if int32(e.buffers[path].version) != change.TextDocumentEdit.TextDocument.Version {
1013 // Skip edits for old versions.
1014 continue
1015 }
1016 if err := e.EditBuffer(ctx, path, protocol.AsTextEdits(change.TextDocumentEdit.Edits)); err != nil {
1017 return fmt.Errorf("editing buffer %q: %w", path, err)
1018 }
1019 }
1020 }
1021 }
1022 // Execute any commands. The specification says that commands are
1023 // executed after edits are applied.
1024 if action.Command != nil {
1025 if err := e.ExecuteCommand(ctx, &protocol.ExecuteCommandParams{
1026 Command: action.Command.Command,
1027 Arguments: action.Command.Arguments,
1028 }, nil); err != nil {
1029 return err
1030 }
1031 }
1032 // Some commands may edit files on disk.
1033 return e.sandbox.Workdir.CheckForFileChanges(ctx)
1034 }
1035
1036 func (e *Editor) Diagnostics(ctx context.Context, path string) ([]protocol.Diagnostic, error) {
1037 if e.Server == nil {
1038 return nil, errors.New("not connected")
1039 }
1040 e.mu.Lock()
1041 capabilities := e.serverCapabilities.DiagnosticProvider
1042 e.mu.Unlock()
1043
1044 if capabilities == nil {
1045 return nil, errors.New("server does not support pull diagnostics")
1046 }
1047 switch capabilities.Value.(type) {
1048 case nil:
1049 return nil, errors.New("server does not support pull diagnostics")
1050 case protocol.DiagnosticOptions:
1051 case protocol.DiagnosticRegistrationOptions:
1052 // We could optionally check TextDocumentRegistrationOptions here to
1053 // see if any filters apply to path.
1054 default:
1055 panic(fmt.Sprintf("unknown DiagnosticsProvider type %T", capabilities.Value))
1056 }
1057
1058 params := &protocol.DocumentDiagnosticParams{
1059 TextDocument: e.TextDocumentIdentifier(path),
1060 }
1061 result, err := e.Server.Diagnostic(ctx, params)
1062 if err != nil {
1063 return nil, err
1064 }
1065 report, ok := result.Value.(protocol.RelatedFullDocumentDiagnosticReport)
1066 if !ok {
1067 return nil, fmt.Errorf("unexpected diagnostics report type %T", result)
1068 }
1069 return report.Items, nil
1070 }
1071
1072 // GetQuickFixes returns the available quick fix code actions.
1073 func (e *Editor) GetQuickFixes(ctx context.Context, loc protocol.Location, diagnostics []protocol.Diagnostic) ([]protocol.CodeAction, error) {
1074 return e.CodeActions(ctx, loc, diagnostics, protocol.QuickFix, protocol.SourceFixAll)
1075 }
1076
1077 func (e *Editor) applyCodeActions(ctx context.Context, loc protocol.Location, diagnostics []protocol.Diagnostic, only ...protocol.CodeActionKind) (int, error) {
1078 actions, err := e.CodeActions(ctx, loc, diagnostics, only...)
1079 if err != nil {
1080 return 0, err
1081 }
1082 applied := 0
1083 for _, action := range actions {
1084 if action.Title == "" {
1085 return 0, fmt.Errorf("empty title for code action")
1086 }
1087 applied++
1088 if err := e.ApplyCodeAction(ctx, action); err != nil {
1089 return 0, err
1090 }
1091 }
1092 return applied, nil
1093 }
1094
1095 // TODO(rfindley): add missing documentation to exported methods here.
1096
1097 func (e *Editor) CodeActions(ctx context.Context, loc protocol.Location, diagnostics []protocol.Diagnostic, only ...protocol.CodeActionKind) ([]protocol.CodeAction, error) {
1098 if e.Server == nil {
1099 return nil, nil
1100 }
1101 params := &protocol.CodeActionParams{}
1102 params.TextDocument.URI = loc.URI
1103 params.Context.Only = only
1104 params.Range = loc.Range // may be zero => whole file
1105 if diagnostics != nil {
1106 params.Context.Diagnostics = diagnostics
1107 }
1108 return e.Server.CodeAction(ctx, params)
1109 }
1110
1111 func (e *Editor) ExecuteCodeLensCommand(ctx context.Context, path string, cmd command.Command, result any) error {
1112 lenses, err := e.CodeLens(ctx, path)
1113 if err != nil {
1114 return err
1115 }
1116 var lens protocol.CodeLens
1117 var found bool
1118 for _, l := range lenses {
1119 if l.Command.Command == cmd.String() {
1120 lens = l
1121 found = true
1122 }
1123 }
1124 if !found {
1125 return fmt.Errorf("found no command with the ID %s", cmd)
1126 }
1127 return e.ExecuteCommand(ctx, &protocol.ExecuteCommandParams{
1128 Command: lens.Command.Command,
1129 Arguments: lens.Command.Arguments,
1130 }, result)
1131 }
1132
1133 // ExecuteCommand makes a workspace/executeCommand request to the connected LSP
1134 // server, if any.
1135 //
1136 // Result contains a pointer to a variable to be populated by json.Unmarshal.
1137 func (e *Editor) ExecuteCommand(ctx context.Context, params *protocol.ExecuteCommandParams, result any) error {
1138 if e.Server == nil {
1139 return nil
1140 }
1141 var match bool
1142 if e.serverCapabilities.ExecuteCommandProvider != nil {
1143 // Ensure that this command was actually listed as a supported command.
1144 if slices.Contains(e.serverCapabilities.ExecuteCommandProvider.Commands, params.Command) {
1145 match = true
1146 }
1147 }
1148 if !match {
1149 return fmt.Errorf("unsupported command %q", params.Command)
1150 }
1151 response, err := e.Server.ExecuteCommand(ctx, params)
1152 if err != nil {
1153 return err
1154 }
1155 // Some commands use the go command, which writes directly to disk.
1156 // For convenience, check for those changes.
1157 if err := e.sandbox.Workdir.CheckForFileChanges(ctx); err != nil {
1158 return fmt.Errorf("checking for file changes: %v", err)
1159 }
1160 if result != nil {
1161 // ExecuteCommand already unmarshalled the response without knowing
1162 // its schema, using the generic map[string]any representation.
1163 // Encode and decode again, this time into a typed variable.
1164 //
1165 // This could be improved by generating a jsonrpc2 command client from the
1166 // command.Interface, but that should only be done if we're consolidating
1167 // this part of the tsprotocol generation.
1168 //
1169 // TODO(hxjiang): we could also improve this by having ExecuteCommand return
1170 // a json.RawMessage, similar to what we do with arguments.
1171 data, err := json.Marshal(response)
1172 if err != nil {
1173 return bug.Errorf("marshalling response: %v", err)
1174 }
1175 if err := json.Unmarshal(data, result); err != nil {
1176 return fmt.Errorf("unmarshalling response: %v", err)
1177 }
1178 }
1179 return nil
1180 }
1181
1182 // FormatBuffer gofmts a Go file.
1183 func (e *Editor) FormatBuffer(ctx context.Context, path string) error {
1184 if e.Server == nil {
1185 return nil
1186 }
1187 e.mu.Lock()
1188 version := e.buffers[path].version
1189 e.mu.Unlock()
1190 params := &protocol.DocumentFormattingParams{}
1191 params.TextDocument.URI = e.sandbox.Workdir.URI(path)
1192 edits, err := e.Server.Formatting(ctx, params)
1193 if err != nil {
1194 return fmt.Errorf("textDocument/formatting: %w", err)
1195 }
1196 e.mu.Lock()
1197 defer e.mu.Unlock()
1198 if versionAfter := e.buffers[path].version; versionAfter != version {
1199 return fmt.Errorf("before receipt of formatting edits, buffer version changed from %d to %d", version, versionAfter)
1200 }
1201 if len(edits) == 0 {
1202 return nil
1203 }
1204 return e.editBufferLocked(ctx, path, edits)
1205 }
1206
1207 func (e *Editor) checkBufferLocation(loc protocol.Location) error {
1208 e.mu.Lock()
1209 defer e.mu.Unlock()
1210 path := e.sandbox.Workdir.URIToPath(loc.URI)
1211 buf, ok := e.buffers[path]
1212 if !ok {
1213 return fmt.Errorf("buffer %q is not open", path)
1214 }
1215
1216 _, _, err := buf.mapper.RangeOffsets(loc.Range)
1217 return err
1218 }
1219
1220 // RunGenerate runs `go generate` non-recursively in the workdir-relative dir
1221 // path. It does not report any resulting file changes as a watched file
1222 // change, so must be followed by a call to Workdir.CheckForFileChanges once
1223 // the generate command has completed.
1224 // TODO(rFindley): this shouldn't be necessary anymore. Delete it.
1225 func (e *Editor) RunGenerate(ctx context.Context, dir string) error {
1226 if e.Server == nil {
1227 return nil
1228 }
1229 absDir := e.sandbox.Workdir.AbsPath(dir)
1230 cmd := command.NewGenerateCommand("", command.GenerateArgs{
1231 Dir: protocol.URIFromPath(absDir),
1232 Recursive: false,
1233 })
1234 params := &protocol.ExecuteCommandParams{
1235 Command: cmd.Command,
1236 Arguments: cmd.Arguments,
1237 }
1238 if err := e.ExecuteCommand(ctx, params, nil); err != nil {
1239 return fmt.Errorf("running generate: %v", err)
1240 }
1241 // Unfortunately we can't simply poll the workdir for file changes here,
1242 // because server-side command may not have completed. In integration tests, we can
1243 // Await this state change, but here we must delegate that responsibility to
1244 // the caller.
1245 return nil
1246 }
1247
1248 // CodeLens executes a codelens request on the server.
1249 func (e *Editor) CodeLens(ctx context.Context, path string) ([]protocol.CodeLens, error) {
1250 if e.Server == nil {
1251 return nil, nil
1252 }
1253 e.mu.Lock()
1254 _, ok := e.buffers[path]
1255 e.mu.Unlock()
1256 if !ok {
1257 return nil, fmt.Errorf("buffer %q is not open", path)
1258 }
1259 params := &protocol.CodeLensParams{
1260 TextDocument: e.TextDocumentIdentifier(path),
1261 }
1262 lens, err := e.Server.CodeLens(ctx, params)
1263 if err != nil {
1264 return nil, err
1265 }
1266 return lens, nil
1267 }
1268
1269 // Completion executes a completion request on the server.
1270 func (e *Editor) Completion(ctx context.Context, loc protocol.Location) (*protocol.CompletionList, error) {
1271 if e.Server == nil {
1272 return nil, nil
1273 }
1274 path := e.sandbox.Workdir.URIToPath(loc.URI)
1275 e.mu.Lock()
1276 _, ok := e.buffers[path]
1277 e.mu.Unlock()
1278 if !ok {
1279 return nil, fmt.Errorf("buffer %q is not open", path)
1280 }
1281 params := &protocol.CompletionParams{
1282 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1283 }
1284 completions, err := e.Server.Completion(ctx, params)
1285 if err != nil {
1286 return nil, err
1287 }
1288 return completions, nil
1289 }
1290
1291 func (e *Editor) DidCreateFiles(ctx context.Context, files ...protocol.DocumentURI) error {
1292 if e.Server == nil {
1293 return nil
1294 }
1295 params := &protocol.CreateFilesParams{}
1296 for _, file := range files {
1297 params.Files = append(params.Files, protocol.FileCreate{
1298 URI: file,
1299 })
1300 }
1301 return e.Server.DidCreateFiles(ctx, params)
1302 }
1303
1304 func (e *Editor) SetSuggestionInsertReplaceMode(_ context.Context, useReplaceMode bool) {
1305 e.mu.Lock()
1306 defer e.mu.Unlock()
1307 e.suggestionUseReplaceMode = useReplaceMode
1308 }
1309
1310 // AcceptCompletion accepts a completion for the given item
1311 // at the given position based on the editor's suggestion insert mode.
1312 // The server provides separate insert/replace ranges only if the
1313 // Editor declares `InsertReplaceSupport` capability during initialization.
1314 // Otherwise, it returns a single range and the insert/replace mode is ignored.
1315 func (e *Editor) AcceptCompletion(ctx context.Context, loc protocol.Location, item protocol.CompletionItem) error {
1316 if e.Server == nil {
1317 return nil
1318 }
1319 e.mu.Lock()
1320 defer e.mu.Unlock()
1321 path := e.sandbox.Workdir.URIToPath(loc.URI)
1322 _, ok := e.buffers[path]
1323 if !ok {
1324 return fmt.Errorf("buffer %q is not open", path)
1325 }
1326 edit, err := protocol.SelectCompletionTextEdit(item, e.suggestionUseReplaceMode)
1327 if err != nil {
1328 return err
1329 }
1330 return e.editBufferLocked(ctx, path, append([]protocol.TextEdit{
1331 edit,
1332 }, item.AdditionalTextEdits...))
1333 }
1334
1335 // Symbols executes a workspace/symbols request on the server.
1336 func (e *Editor) Symbols(ctx context.Context, sym string) ([]protocol.SymbolInformation, error) {
1337 if e.Server == nil {
1338 return nil, nil
1339 }
1340 params := &protocol.WorkspaceSymbolParams{Query: sym}
1341 ans, err := e.Server.Symbol(ctx, params)
1342 return ans, err
1343 }
1344
1345 // InlayHint executes an inlay hint request on the server.
1346 func (e *Editor) InlayHint(ctx context.Context, path string) ([]protocol.InlayHint, error) {
1347 if e.Server == nil {
1348 return nil, nil
1349 }
1350 e.mu.Lock()
1351 _, ok := e.buffers[path]
1352 e.mu.Unlock()
1353 if !ok {
1354 return nil, fmt.Errorf("buffer %q is not open", path)
1355 }
1356 params := &protocol.InlayHintParams{
1357 TextDocument: e.TextDocumentIdentifier(path),
1358 }
1359 hints, err := e.Server.InlayHint(ctx, params)
1360 if err != nil {
1361 return nil, err
1362 }
1363 return hints, nil
1364 }
1365
1366 // References returns references to the object at loc, as returned by
1367 // the connected LSP server. If no server is connected, it returns (nil, nil).
1368 func (e *Editor) References(ctx context.Context, loc protocol.Location) ([]protocol.Location, error) {
1369 if e.Server == nil {
1370 return nil, nil
1371 }
1372 path := e.sandbox.Workdir.URIToPath(loc.URI)
1373 e.mu.Lock()
1374 _, ok := e.buffers[path]
1375 e.mu.Unlock()
1376 if !ok {
1377 return nil, fmt.Errorf("buffer %q is not open", path)
1378 }
1379 params := &protocol.ReferenceParams{
1380 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1381 Context: protocol.ReferenceContext{
1382 IncludeDeclaration: true,
1383 },
1384 }
1385 locations, err := e.Server.References(ctx, params)
1386 if err != nil {
1387 return nil, err
1388 }
1389 return locations, nil
1390 }
1391
1392 // Rename performs a rename of the object at loc to newName, using the
1393 // connected LSP server. If no server is connected, it returns nil.
1394 func (e *Editor) Rename(ctx context.Context, loc protocol.Location, newName string) error {
1395 if e.Server == nil {
1396 return nil
1397 }
1398
1399 // Verify that PrepareRename succeeds.
1400 prepareParams := &protocol.PrepareRenameParams{
1401 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1402 }
1403 if _, err := e.Server.PrepareRename(ctx, prepareParams); err != nil {
1404 return fmt.Errorf("preparing rename: %v", err)
1405 }
1406
1407 params := &protocol.RenameParams{
1408 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1409 NewName: newName,
1410 }
1411 wsedit, err := e.Server.Rename(ctx, params)
1412 if err != nil {
1413 return err
1414 }
1415 return e.applyWorkspaceEdit(ctx, wsedit)
1416 }
1417
1418 // Implementations returns implementations for the object at loc, as
1419 // returned by the connected LSP server. If no server is connected, it returns
1420 // (nil, nil).
1421 func (e *Editor) Implementations(ctx context.Context, loc protocol.Location) ([]protocol.Location, error) {
1422 if e.Server == nil {
1423 return nil, nil
1424 }
1425 path := e.sandbox.Workdir.URIToPath(loc.URI)
1426 e.mu.Lock()
1427 _, ok := e.buffers[path]
1428 e.mu.Unlock()
1429 if !ok {
1430 return nil, fmt.Errorf("buffer %q is not open", path)
1431 }
1432 params := &protocol.ImplementationParams{
1433 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1434 }
1435 return e.Server.Implementation(ctx, params)
1436 }
1437
1438 func (e *Editor) SignatureHelp(ctx context.Context, loc protocol.Location) (*protocol.SignatureHelp, error) {
1439 if e.Server == nil {
1440 return nil, nil
1441 }
1442 path := e.sandbox.Workdir.URIToPath(loc.URI)
1443 e.mu.Lock()
1444 _, ok := e.buffers[path]
1445 e.mu.Unlock()
1446 if !ok {
1447 return nil, fmt.Errorf("buffer %q is not open", path)
1448 }
1449 params := &protocol.SignatureHelpParams{
1450 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
1451 }
1452 return e.Server.SignatureHelp(ctx, params)
1453 }
1454
1455 func (e *Editor) RenameFile(ctx context.Context, oldPath, newPath string) error {
1456 closed, opened, err := e.renameBuffers(oldPath, newPath)
1457 if err != nil {
1458 return err
1459 }
1460
1461 for _, c := range closed {
1462 if err := e.sendDidClose(ctx, c); err != nil {
1463 return err
1464 }
1465 }
1466 for _, o := range opened {
1467 if err := e.sendDidOpen(ctx, o); err != nil {
1468 return err
1469 }
1470 }
1471
1472 // Finally, perform the renaming on disk.
1473 if err := e.sandbox.Workdir.RenameFile(ctx, oldPath, newPath); err != nil {
1474 return fmt.Errorf("renaming sandbox file: %w", err)
1475 }
1476 return nil
1477 }
1478
1479 // renameBuffers renames in-memory buffers affected by the renaming of
1480 // oldPath->newPath, returning the resulting text documents that must be closed
1481 // and opened over the LSP.
1482 func (e *Editor) renameBuffers(oldPath, newPath string) (closed []protocol.TextDocumentIdentifier, opened []protocol.TextDocumentItem, _ error) {
1483 e.mu.Lock()
1484 defer e.mu.Unlock()
1485
1486 // In case either oldPath or newPath is absolute, convert to absolute paths
1487 // before checking for containment.
1488 oldAbs := e.sandbox.Workdir.AbsPath(oldPath)
1489 newAbs := e.sandbox.Workdir.AbsPath(newPath)
1490
1491 // Collect buffers that are affected by the given file or directory renaming.
1492 buffersToRename := make(map[string]string) // old path -> new path
1493
1494 for path := range e.buffers {
1495 abs := e.sandbox.Workdir.AbsPath(path)
1496 if oldAbs == abs || pathutil.InDir(oldAbs, abs) {
1497 rel, err := filepath.Rel(oldAbs, abs)
1498 if err != nil {
1499 return nil, nil, fmt.Errorf("filepath.Rel(%q, %q): %v", oldAbs, abs, err)
1500 }
1501 nabs := filepath.Join(newAbs, rel)
1502 newPath := e.sandbox.Workdir.RelPath(nabs)
1503 buffersToRename[path] = newPath
1504 }
1505 }
1506
1507 // Update buffers, and build protocol changes.
1508 for old, new := range buffersToRename {
1509 buf := e.buffers[old]
1510 delete(e.buffers, old)
1511 buf.version = 1
1512 buf.path = new
1513 e.buffers[new] = buf
1514
1515 closed = append(closed, e.TextDocumentIdentifier(old))
1516 opened = append(opened, e.textDocumentItem(buf))
1517 }
1518
1519 return closed, opened, nil
1520 }
1521
1522 // applyWorkspaceEdit applies the sequence of document changes in
1523 // wsedit to the Editor.
1524 //
1525 // See also:
1526 // - changedFiles in ../../marker/marker_test.go for the
1527 // handler used by the marker test to intercept edits.
1528 // - client.applyWorkspaceEdit in ../../../cmd/cmd.go for the
1529 // CLI variant.
1530 func (e *Editor) applyWorkspaceEdit(ctx context.Context, wsedit *protocol.WorkspaceEdit) error {
1531 uriToPath := e.sandbox.Workdir.URIToPath
1532
1533 for _, change := range wsedit.DocumentChanges {
1534 switch {
1535 case change.TextDocumentEdit != nil:
1536 if err := e.applyTextDocumentEdit(ctx, *change.TextDocumentEdit); err != nil {
1537 return err
1538 }
1539
1540 case change.RenameFile != nil:
1541 old := uriToPath(change.RenameFile.OldURI)
1542 new := uriToPath(change.RenameFile.NewURI)
1543 if err := e.RenameFile(ctx, old, new); err != nil {
1544 return err
1545 }
1546
1547 case change.CreateFile != nil:
1548 path := uriToPath(change.CreateFile.URI)
1549 if err := e.CreateBuffer(ctx, path, ""); err != nil {
1550 return err // e.g. already exists
1551 }
1552
1553 case change.DeleteFile != nil:
1554 path := uriToPath(change.DeleteFile.URI)
1555 // The specified URI could be a file or a directory.
1556 files, err := e.sandbox.Workdir.ListFiles(path)
1557 if err != nil {
1558 return err
1559 }
1560 if len(files) > 0 {
1561 // Directory is not empty. If "Recursive" is true, we delete
1562 // every file in the folder. Otherwise, we continue without
1563 // deleting the directory.
1564 if change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {
1565 for _, f := range files {
1566 _ = e.CloseBuffer(ctx, f) // returns error if not open
1567 if err := e.sandbox.Workdir.RemoveFile(ctx, f); err != nil {
1568 return err // e.g. doesn't exist
1569 }
1570 }
1571 }
1572 continue
1573 }
1574 _ = e.CloseBuffer(ctx, path) // returns error if not open
1575 if err := e.sandbox.Workdir.RemoveFile(ctx, path); err != nil {
1576 return err // e.g. doesn't exist
1577 }
1578
1579 default:
1580 return bug.Errorf("invalid DocumentChange")
1581 }
1582 }
1583 return nil
1584 }
1585
1586 func (e *Editor) applyTextDocumentEdit(ctx context.Context, change protocol.TextDocumentEdit) error {
1587 path := e.sandbox.Workdir.URIToPath(change.TextDocument.URI)
1588 if ver := int32(e.BufferVersion(path)); ver != change.TextDocument.Version {
1589 return fmt.Errorf("buffer versions for %q do not match: have %d, editing %d", path, ver, change.TextDocument.Version)
1590 }
1591 if !e.HasBuffer(path) {
1592 err := e.OpenFile(ctx, path)
1593 if os.IsNotExist(err) {
1594 // TODO: it's unclear if this is correct. Here we create the buffer (with
1595 // version 1), then apply edits. Perhaps we should apply the edits before
1596 // sending the didOpen notification.
1597 err = e.CreateBuffer(ctx, path, "")
1598 }
1599 if err != nil {
1600 return err
1601 }
1602 }
1603 return e.EditBuffer(ctx, path, protocol.AsTextEdits(change.Edits))
1604 }
1605
1606 // Config returns the current editor configuration.
1607 func (e *Editor) Config() EditorConfig {
1608 e.mu.Lock()
1609 defer e.mu.Unlock()
1610 return e.config
1611 }
1612
1613 func (e *Editor) SetConfig(cfg EditorConfig) {
1614 e.mu.Lock()
1615 e.config = cfg
1616 e.mu.Unlock()
1617 }
1618
1619 // ChangeConfiguration sets the new editor configuration, and if applicable
1620 // sends a didChangeConfiguration notification.
1621 //
1622 // An error is returned if the change notification failed to send.
1623 func (e *Editor) ChangeConfiguration(ctx context.Context, newConfig EditorConfig) error {
1624 e.SetConfig(newConfig)
1625 if e.Server != nil {
1626 var params protocol.DidChangeConfigurationParams // empty: gopls ignores the Settings field
1627 if err := e.Server.DidChangeConfiguration(ctx, &params); err != nil {
1628 return err
1629 }
1630 e.callsMu.Lock()
1631 e.calls.DidChangeConfiguration++
1632 e.callsMu.Unlock()
1633 }
1634 return nil
1635 }
1636
1637 // ChangeWorkspaceFolders sets the new workspace folders, and sends a
1638 // didChangeWorkspaceFolders notification to the server.
1639 //
1640 // The given folders must all be unique.
1641 func (e *Editor) ChangeWorkspaceFolders(ctx context.Context, folders []string) error {
1642 config := e.Config()
1643
1644 // capture existing folders so that we can compute the change.
1645 oldFolders := makeWorkspaceFolders(e.sandbox, config.WorkspaceFolders, config.NoDefaultWorkspaceFiles)
1646 newFolders := makeWorkspaceFolders(e.sandbox, folders, config.NoDefaultWorkspaceFiles)
1647 config.WorkspaceFolders = folders
1648 e.SetConfig(config)
1649
1650 if e.Server == nil {
1651 return nil
1652 }
1653
1654 var params protocol.DidChangeWorkspaceFoldersParams
1655
1656 // Keep track of old workspace folders that must be removed.
1657 toRemove := make(map[protocol.URI]protocol.WorkspaceFolder)
1658 for _, folder := range oldFolders {
1659 toRemove[folder.URI] = folder
1660 }
1661
1662 // Sanity check: if we see a folder twice the algorithm below doesn't work,
1663 // so track seen folders to ensure that we panic in that case.
1664 seen := make(map[protocol.URI]protocol.WorkspaceFolder)
1665 for _, folder := range newFolders {
1666 if _, ok := seen[folder.URI]; ok {
1667 panic(fmt.Sprintf("folder %s seen twice", folder.URI))
1668 }
1669
1670 // If this folder already exists, we don't want to remove it.
1671 // Otherwise, we need to add it.
1672 if _, ok := toRemove[folder.URI]; ok {
1673 delete(toRemove, folder.URI)
1674 } else {
1675 params.Event.Added = append(params.Event.Added, folder)
1676 }
1677 }
1678
1679 for _, v := range toRemove {
1680 params.Event.Removed = append(params.Event.Removed, v)
1681 }
1682
1683 return e.Server.DidChangeWorkspaceFolders(ctx, &params)
1684 }
1685
1686 // ResolveCodeAction executes a codeAction/resolve request on the server.
1687 func (e *Editor) ResolveCodeAction(ctx context.Context, action *protocol.CodeAction) (*protocol.CodeAction, error) {
1688 if e.Server == nil {
1689 return nil, nil
1690 }
1691 return e.Server.ResolveCodeAction(ctx, action)
1692 }
1693
1694 // CodeAction executes a codeAction request on the server.
1695 // If loc.Range is zero, the whole file is implied.
1696 // To reduce distraction, the trigger action (unknown, automatic, invoked)
1697 // may affect what actions are offered.
1698 func (e *Editor) CodeAction(ctx context.Context, loc protocol.Location, diagnostics []protocol.Diagnostic, trigger protocol.CodeActionTriggerKind) ([]protocol.CodeAction, error) {
1699 if e.Server == nil {
1700 return nil, nil
1701 }
1702 path := e.sandbox.Workdir.URIToPath(loc.URI)
1703 e.mu.Lock()
1704 _, ok := e.buffers[path]
1705 e.mu.Unlock()
1706 if !ok {
1707 return nil, fmt.Errorf("buffer %q is not open", path)
1708 }
1709 params := &protocol.CodeActionParams{
1710 TextDocument: e.TextDocumentIdentifier(path),
1711 Context: protocol.CodeActionContext{
1712 Diagnostics: diagnostics,
1713 TriggerKind: &trigger,
1714 Only: []protocol.CodeActionKind{protocol.Empty}, // => all
1715 },
1716 Range: loc.Range, // may be zero
1717 }
1718 lens, err := e.Server.CodeAction(ctx, params)
1719 if err != nil {
1720 return nil, err
1721 }
1722 return lens, nil
1723 }
1724
1725 func (e *Editor) EditResolveSupport() (bool, error) {
1726 capabilities, err := clientCapabilities(e.Config())
1727 if err != nil {
1728 return false, err
1729 }
1730 return capabilities.TextDocument.CodeAction.ResolveSupport != nil && slices.Contains(capabilities.TextDocument.CodeAction.ResolveSupport.Properties, "edit"), nil
1731 }
1732
1733 // Hover triggers a hover at the given position in an open buffer.
1734 // It may return (nil, zero) if no symbol was selected.
1735 func (e *Editor) Hover(ctx context.Context, loc protocol.Location) (*protocol.MarkupContent, protocol.Location, error) {
1736 if err := e.checkBufferLocation(loc); err != nil {
1737 return nil, protocol.Location{}, err
1738 }
1739 params := &protocol.HoverParams{}
1740 params.TextDocument.URI = loc.URI
1741 params.Position = loc.Range.Start
1742 params.Range = loc.Range
1743
1744 resp, err := e.Server.Hover(ctx, params)
1745 if err != nil {
1746 return nil, protocol.Location{}, fmt.Errorf("hover: %w", err)
1747 }
1748 if resp == nil {
1749 return nil, protocol.Location{}, nil // e.g. no selected symbol
1750 }
1751 return &resp.Contents, loc.URI.Location(resp.Range), nil
1752 }
1753
1754 func (e *Editor) DocumentLink(ctx context.Context, path string) ([]protocol.DocumentLink, error) {
1755 if e.Server == nil {
1756 return nil, nil
1757 }
1758 params := &protocol.DocumentLinkParams{}
1759 params.TextDocument.URI = e.sandbox.Workdir.URI(path)
1760 return e.Server.DocumentLink(ctx, params)
1761 }
1762
1763 func (e *Editor) DocumentHighlight(ctx context.Context, loc protocol.Location) ([]protocol.DocumentHighlight, error) {
1764 if e.Server == nil {
1765 return nil, nil
1766 }
1767 if err := e.checkBufferLocation(loc); err != nil {
1768 return nil, err
1769 }
1770 params := &protocol.DocumentHighlightParams{}
1771 params.TextDocument.URI = loc.URI
1772 params.Position = loc.Range.Start
1773
1774 return e.Server.DocumentHighlight(ctx, params)
1775 }
1776
1777 // SemanticTokensFull invokes textDocument/semanticTokens/full, and interprets
1778 // its result.
1779 func (e *Editor) SemanticTokensFull(ctx context.Context, path string) ([]SemanticToken, error) {
1780 p := &protocol.SemanticTokensParams{
1781 TextDocument: protocol.TextDocumentIdentifier{
1782 URI: e.sandbox.Workdir.URI(path),
1783 },
1784 }
1785 resp, err := e.Server.SemanticTokensFull(ctx, p)
1786 if err != nil {
1787 return nil, err
1788 }
1789 m, err := e.Mapper(path)
1790 if err != nil {
1791 return nil, fmt.Errorf("can't get mapper for buffer %s: %v", path, err)
1792 }
1793 return e.interpretTokens(m, resp.Data)
1794 }
1795
1796 // SemanticTokensRange invokes textDocument/semanticTokens/range, and
1797 // interprets its result.
1798 func (e *Editor) SemanticTokensRange(ctx context.Context, loc protocol.Location) ([]SemanticToken, error) {
1799 p := &protocol.SemanticTokensRangeParams{
1800 TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI},
1801 Range: loc.Range,
1802 }
1803 resp, err := e.Server.SemanticTokensRange(ctx, p)
1804 if err != nil {
1805 return nil, err
1806 }
1807 path := e.sandbox.Workdir.URIToPath(loc.URI)
1808 // As noted above: buffers should be keyed by protocol.DocumentURI.
1809 m, err := e.Mapper(path)
1810 if err != nil {
1811 return nil, fmt.Errorf("can't get mapper for buffer %s: %v", path, err)
1812 }
1813 return e.interpretTokens(m, resp.Data)
1814 }
1815
1816 // A SemanticToken is an interpreted semantic token value.
1817 type SemanticToken struct {
1818 Token string
1819 TokenType string
1820 Mod string
1821 }
1822
1823 // Note: previously this function elided comment, string, and number tokens.
1824 // Instead, filtering of token types should be done by the caller.
1825 func (e *Editor) interpretTokens(m *protocol.Mapper, x []uint32) ([]SemanticToken, error) {
1826 var (
1827 legend = e.semTokOpts.Legend
1828 ans []SemanticToken
1829 line, char uint32 // zero-based UTF-16
1830 )
1831 for i := 0; i < len(x); i += 5 {
1832 deltaLine, deltaChar, length16, t, modifiers := x[i], x[i+1], x[i+2], x[i+3], x[i+4]
1833
1834 line += deltaLine
1835
1836 if deltaLine == 0 {
1837 char += deltaChar
1838 } else {
1839 char = deltaChar
1840 }
1841
1842 var mods []string
1843 for i, mod := range legend.TokenModifiers {
1844 if modifiers&(1<<i) != 0 {
1845 mods = append(mods, mod)
1846 }
1847 }
1848
1849 // Extract token text.
1850 start, err := m.PositionOffset(protocol.Position{Line: line, Character: char})
1851 if err != nil {
1852 return nil, fmt.Errorf("invalid line/char in semantic token: %v", err)
1853 }
1854 // Advance by 'length' UTF-16 code units.
1855 end := start + utf16IndexToBytes(m.Content[start:], int(length16))
1856 text := string(m.Content[start:end])
1857
1858 ans = append(ans, SemanticToken{
1859 Token: text,
1860 TokenType: legend.TokenTypes[t],
1861 Mod: strings.Join(mods, " "),
1862 })
1863 }
1864 return ans, nil
1865 }
1866
1867 // utf16IndexToBytes returns the length of the prefix of s whose
1868 // UTF-16 transcoding has length n.
1869 //
1870 // Inv: protocol.UTF16Len(UTF16Bytes(s, n)) == n.
1871 func utf16IndexToBytes(s []byte, n int) int {
1872 prefix := 0
1873 for i := 0; i < n; i++ {
1874 r, size := utf8.DecodeRune(s[prefix:])
1875 if r >= 0x10000 {
1876 i++ // surrogate pair
1877 }
1878 prefix += size
1879 }
1880 return prefix
1881 }