| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 35 |
|
| 36 |
type Editor struct { |
| 37 |
|
| 38 |
|
| 39 |
Server protocol.Server |
| 40 |
cancelConn func() |
| 41 |
serverConn jsonrpc2.Conn |
| 42 |
client *Client |
| 43 |
sandbox *Sandbox |
| 44 |
|
| 45 |
|
| 46 |
mu sync.Mutex |
| 47 |
config EditorConfig |
| 48 |
buffers map[string]buffer |
| 49 |
watchPatterns []*glob.Glob |
| 50 |
suggestionUseReplaceMode bool |
| 51 |
|
| 52 |
|
| 53 |
serverCapabilities protocol.ServerCapabilities |
| 54 |
semTokOpts protocol.SemanticTokensOptions |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
callsMu sync.Mutex |
| 61 |
calls CallCounts |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
type CallCounts struct { |
| 66 |
DidOpen, DidChange, DidSave, DidChangeWatchedFiles, DidClose, DidChangeConfiguration uint64 |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
type buffer struct { |
| 71 |
version int |
| 72 |
path string |
| 73 |
mapper *protocol.Mapper |
| 74 |
dirty bool |
| 75 |
} |
| 76 |
|
| 77 |
func (b buffer) text() string { |
| 78 |
return string(b.mapper.Content) |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
type EditorConfig struct { |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
ClientName string |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
Env map[string]string |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
WorkspaceFolders []string |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
NoDefaultWorkspaceFiles bool |
| 115 |
|
| 116 |
|
| 117 |
RelRootPath string |
| 118 |
|
| 119 |
|
| 120 |
WindowsLineEndings bool |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
FileAssociations map[protocol.LanguageKind]string |
| 130 |
|
| 131 |
|
| 132 |
Settings map[string]any |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
FolderSettings map[string]map[string]any |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
CapabilitiesJSON []byte |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
MessageResponder func(params *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) |
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
MaxMessageDelay time.Duration |
| 154 |
} |
| 155 |
|
| 156 |
|
| 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 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 222 |
func (e *Editor) Exit(ctx context.Context) error { |
| 223 |
if e.Server != nil { |
| 224 |
|
| 225 |
|
| 226 |
if err := e.Server.Exit(ctx); err != nil { |
| 227 |
return fmt.Errorf("Exit: %w", err) |
| 228 |
} |
| 229 |
} |
| 230 |
return nil |
| 231 |
} |
| 232 |
|
| 233 |
|
| 234 |
|
| 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 |
|
| 247 |
select { |
| 248 |
case <-e.serverConn.Done(): |
| 249 |
|
| 250 |
return nil |
| 251 |
case <-ctx.Done(): |
| 252 |
return fmt.Errorf("connection not closed: %w", ctx.Err()) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
|
| 257 |
func (e *Editor) Client() *Client { |
| 258 |
return e.client |
| 259 |
} |
| 260 |
|
| 261 |
|
| 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 |
|
| 275 |
|
| 276 |
"verboseWorkDoneProgress": true, |
| 277 |
|
| 278 |
|
| 279 |
|
| 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 |
|
| 291 |
|
| 292 |
if scopeURI != nil { |
| 293 |
var ( |
| 294 |
scopePath = protocol.DocumentURI(*scopeURI).Path() |
| 295 |
closestDir string |
| 296 |
closestSettings map[string]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) { |
| 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 |
|
| 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 |
|
| 360 |
return nil |
| 361 |
} |
| 362 |
|
| 363 |
func clientCapabilities(cfg EditorConfig) (protocol.ClientCapabilities, error) { |
| 364 |
var capabilities protocol.ClientCapabilities |
| 365 |
|
| 366 |
capabilities.Workspace.Configuration = true |
| 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 |
| 373 |
capabilities.Window.ShowDocument = &protocol.ShowDocumentClientCapabilities{Support: true} |
| 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 |
|
| 380 |
"label", |
| 381 |
} |
| 382 |
capabilities.TextDocument.SemanticTokens.TokenModifiers = []string{ |
| 383 |
"declaration", "definition", "readonly", "static", |
| 384 |
"deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary", |
| 385 |
|
| 386 |
"interface", "struct", "signature", "pointer", "array", "map", "slice", "chan", "string", "number", "bool", "invalid", |
| 387 |
} |
| 388 |
|
| 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}, |
| 397 |
}, |
| 398 |
}, |
| 399 |
} |
| 400 |
|
| 401 |
|
| 402 |
capabilities.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport = true |
| 403 |
|
| 404 |
capabilities.Workspace.DidChangeWatchedFiles.DynamicRegistration = true |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
capabilities.Workspace.WorkspaceEdit = &protocol.WorkspaceEditClientCapabilities{ |
| 409 |
ResourceOperations: []protocol.ResourceOperationKind{ |
| 410 |
"rename", |
| 411 |
}, |
| 412 |
} |
| 413 |
|
| 414 |
|
| 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 |
|
| 424 |
|
| 425 |
func (e *Editor) ServerCapabilities() protocol.ServerCapabilities { |
| 426 |
return e.serverCapabilities |
| 427 |
} |
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 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 |
|
| 443 |
func (e *Editor) HasCommand(cmd command.Command) bool { |
| 444 |
return slices.Contains(e.serverCapabilities.ExecuteCommandProvider.Commands, cmd.String()) |
| 445 |
} |
| 446 |
|
| 447 |
|
| 448 |
var uriRE = regexp.MustCompile(`^[a-z][a-z0-9+\-.]*://\S+`) |
| 449 |
|
| 450 |
|
| 451 |
|
| 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) { |
| 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 |
|
| 475 |
|
| 476 |
func (e *Editor) onFileChanges(ctx context.Context, evts []protocol.FileEvent) { |
| 477 |
if e.Server == nil { |
| 478 |
return |
| 479 |
} |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
e.callsMu.Lock() |
| 485 |
e.calls.DidChangeWatchedFiles++ |
| 486 |
e.callsMu.Unlock() |
| 487 |
|
| 488 |
|
| 489 |
go func() { |
| 490 |
e.mu.Lock() |
| 491 |
defer e.mu.Unlock() |
| 492 |
for _, evt := range evts { |
| 493 |
|
| 494 |
|
| 495 |
path := e.sandbox.Workdir.URIToPath(evt.URI) |
| 496 |
if buf, ok := e.buffers[path]; ok { |
| 497 |
|
| 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 |
| 505 |
} |
| 506 |
|
| 507 |
if string(content) == buf.text() { |
| 508 |
continue |
| 509 |
} |
| 510 |
|
| 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 |
|
| 526 |
e.Server.DidChangeWatchedFiles(ctx, &protocol.DidChangeWatchedFilesParams{ |
| 527 |
Changes: matchedEvts, |
| 528 |
}) |
| 529 |
}() |
| 530 |
} |
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 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 |
|
| 550 |
|
| 551 |
|
| 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 |
|
| 574 |
|
| 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 |
|
| 603 |
|
| 604 |
|
| 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$`), |
| 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 |
|
| 638 |
|
| 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 |
|
| 656 |
|
| 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 |
|
| 695 |
|
| 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 |
|
| 754 |
var ( |
| 755 |
ErrNoMatch = errors.New("no match") |
| 756 |
ErrUnknownBuffer = errors.New("unknown buffer") |
| 757 |
) |
| 758 |
|
| 759 |
|
| 760 |
|
| 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 |
|
| 774 |
start, end = indexes[0], indexes[1] |
| 775 |
case 4: |
| 776 |
|
| 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 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 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 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 850 |
|
| 851 |
|
| 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 |
|
| 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 |
|
| 874 |
|
| 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 |
|
| 904 |
|
| 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 |
|
| 931 |
|
| 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 |
|
| 944 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 992 |
func (e *Editor) ApplyCodeAction(ctx context.Context, action protocol.CodeAction) error { |
| 993 |
|
| 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 |
|
| 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 |
|
| 1023 |
|
| 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 |
|
| 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 |
|
| 1053 |
|
| 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 |
|
| 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 |
|
| 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 |
| 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 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 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 |
|
| 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 |
|
| 1156 |
|
| 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 |
|
| 1162 |
|
| 1163 |
|
| 1164 |
|
| 1165 |
|
| 1166 |
|
| 1167 |
|
| 1168 |
|
| 1169 |
|
| 1170 |
|
| 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 |
|
| 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 |
|
| 1221 |
|
| 1222 |
|
| 1223 |
|
| 1224 |
|
| 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 |
|
| 1242 |
|
| 1243 |
|
| 1244 |
|
| 1245 |
return nil |
| 1246 |
} |
| 1247 |
|
| 1248 |
|
| 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 |
|
| 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 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1367 |
|
| 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 |
|
| 1393 |
|
| 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 |
|
| 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 |
|
| 1419 |
|
| 1420 |
|
| 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 |
|
| 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 |
|
| 1480 |
|
| 1481 |
|
| 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 |
|
| 1487 |
|
| 1488 |
oldAbs := e.sandbox.Workdir.AbsPath(oldPath) |
| 1489 |
newAbs := e.sandbox.Workdir.AbsPath(newPath) |
| 1490 |
|
| 1491 |
|
| 1492 |
buffersToRename := make(map[string]string) |
| 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 |
|
| 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 |
|
| 1523 |
|
| 1524 |
|
| 1525 |
|
| 1526 |
|
| 1527 |
|
| 1528 |
|
| 1529 |
|
| 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 |
| 1551 |
} |
| 1552 |
|
| 1553 |
case change.DeleteFile != nil: |
| 1554 |
path := uriToPath(change.DeleteFile.URI) |
| 1555 |
|
| 1556 |
files, err := e.sandbox.Workdir.ListFiles(path) |
| 1557 |
if err != nil { |
| 1558 |
return err |
| 1559 |
} |
| 1560 |
if len(files) > 0 { |
| 1561 |
|
| 1562 |
|
| 1563 |
|
| 1564 |
if change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive { |
| 1565 |
for _, f := range files { |
| 1566 |
_ = e.CloseBuffer(ctx, f) |
| 1567 |
if err := e.sandbox.Workdir.RemoveFile(ctx, f); err != nil { |
| 1568 |
return err |
| 1569 |
} |
| 1570 |
} |
| 1571 |
} |
| 1572 |
continue |
| 1573 |
} |
| 1574 |
_ = e.CloseBuffer(ctx, path) |
| 1575 |
if err := e.sandbox.Workdir.RemoveFile(ctx, path); err != nil { |
| 1576 |
return err |
| 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 |
|
| 1595 |
|
| 1596 |
|
| 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 |
|
| 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 |
|
| 1620 |
|
| 1621 |
|
| 1622 |
|
| 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 |
| 1627 |
if err := e.Server.DidChangeConfiguration(ctx, ¶ms); 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 |
|
| 1638 |
|
| 1639 |
|
| 1640 |
|
| 1641 |
func (e *Editor) ChangeWorkspaceFolders(ctx context.Context, folders []string) error { |
| 1642 |
config := e.Config() |
| 1643 |
|
| 1644 |
|
| 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 |
|
| 1657 |
toRemove := make(map[protocol.URI]protocol.WorkspaceFolder) |
| 1658 |
for _, folder := range oldFolders { |
| 1659 |
toRemove[folder.URI] = folder |
| 1660 |
} |
| 1661 |
|
| 1662 |
|
| 1663 |
|
| 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 |
|
| 1671 |
|
| 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, ¶ms) |
| 1684 |
} |
| 1685 |
|
| 1686 |
|
| 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 |
|
| 1695 |
|
| 1696 |
|
| 1697 |
|
| 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}, |
| 1715 |
}, |
| 1716 |
Range: loc.Range, |
| 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 |
|
| 1734 |
|
| 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 |
| 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 |
|
| 1778 |
|
| 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 |
|
| 1797 |
|
| 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 |
|
| 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 |
|
| 1817 |
type SemanticToken struct { |
| 1818 |
Token string |
| 1819 |
TokenType string |
| 1820 |
Mod string |
| 1821 |
} |
| 1822 |
|
| 1823 |
|
| 1824 |
|
| 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 |
| 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 |
|
| 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 |
|
| 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 |
|
| 1868 |
|
| 1869 |
|
| 1870 |
|
| 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++ |
| 1877 |
} |
| 1878 |
prefix += size |
| 1879 |
} |
| 1880 |
return prefix |
| 1881 |
} |