1
0
mirror of https://github.com/golang/go synced 2024-10-01 12:38:31 -06:00
go/internal/lsp/server.go

177 lines
5.0 KiB
Go
Raw Normal View History

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lsp implements LSP for gopls.
package lsp
import (
"context"
"fmt"
"sync"
"golang.org/x/tools/internal/jsonrpc2"
"golang.org/x/tools/internal/lsp/mod"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/span"
errors "golang.org/x/xerrors"
)
const concurrentAnalyses = 1
// NewServer creates an LSP server and binds it to handle incoming client
// messages on on the supplied stream.
internal/lsp: refactor LSP server instantiation Previously, the process of instantiating and running the LSP server was sharded across the lsp, protocol, and cmd packages, and this resulted in some APIs that are hard to work with. For example, it's hard to guess the difference between lsp.NewClientServer, lsp.NewServer, protocol.NewServer (which returns a client), and protocol.NewClient (which returns a server). This change reorganizes Server instantiation as follows: + The lsp.Server is now purely an implementation of the protocol.Server interface. It is no longer responsible for installing itself into the jsonrpc2 Stream, nor for running itself. + A new package 'lsprpc' is added, to implement the logic of binding an incoming connection to an LSP server session. This is put in a separate package for lack of a clear home: it didn't really philosophically belong in any of the lsp, cmd, or protocol packages. We can perhaps move it to cmd in the future, but I'd like to keep it as a separate package while I develop request forwarding. simplified import graph: jsonrpc2 ⭠ lsprpc ⭠ cmd ⭩ ⭦ lsp (t.b.d. client tests) ⭩ ⭨ protocol source + The jsonrpc2 package is extended to have a minimal API for running a 'StreamServer': something analogous to an HTTP server that listens for new connections and delegates to a handler (but we couldn't use the word 'Handler' for this delegate as it was already taken). After these changes, I hope that the concerns of "serving the LSP", "serving jsonrpc2", and "installing the LSP on jsonrpc2" are more logically organized, though one legitimate criticism is that the word 'Server' is still heavily overloaded. This change prepares a subsequent change which hijacks the jsonrpc2 connection when forwarding messages to a shared gopls instance. To test this change, the following improvements are made: + A servertest package is added to make it easier to run a test against an in-process jsonrpc2 server. For now, this uses TCP but it could easily be modified to use io.Pipe. + cmd tests are updated to use the servertest package. Unfortunately it wasn't yet possible to eliminate the concept of `remote=internal` in favor of just using multiple sessions, because view initialization involves calling both `go env` and `packages.Load`, which slow down session startup significantly. See also golang.org/issue/35968. Instead, the syntax for `-remote=internal` is modified to be `-remote=internal@127.0.0.1:12345`. + An additional test for request cancellation is added for the sessionserver package. This test uncovered a bug: when calling Canceller.Cancel, we were using id rather than &id, which resulted in incorrect json serialization (as only the pointer receiver implements the json.Marshaller interface). Updates golang/go#34111 Change-Id: I75c219df634348cdf53a9e57839b98588311a9ef Reviewed-on: https://go-review.googlesource.com/c/tools/+/215742 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-01-21 17:34:50 -07:00
func NewServer(session source.Session, client protocol.Client) *Server {
return &Server{
delivered: make(map[span.URI]sentDiagnostics),
session: session,
client: client,
diagnosticsSema: make(chan struct{}, concurrentAnalyses),
}
}
type serverState int
const (
serverCreated = serverState(iota)
serverInitializing // set once the server has received "initialize" request
serverInitialized // set once the server has received "initialized" request
serverShutDown
)
func (s serverState) String() string {
switch s {
case serverCreated:
return "created"
case serverInitializing:
return "initializing"
case serverInitialized:
return "initialized"
case serverShutDown:
return "shutDown"
}
return fmt.Sprintf("(unknown state: %d)", int(s))
}
internal/lsp: refactor LSP server instantiation Previously, the process of instantiating and running the LSP server was sharded across the lsp, protocol, and cmd packages, and this resulted in some APIs that are hard to work with. For example, it's hard to guess the difference between lsp.NewClientServer, lsp.NewServer, protocol.NewServer (which returns a client), and protocol.NewClient (which returns a server). This change reorganizes Server instantiation as follows: + The lsp.Server is now purely an implementation of the protocol.Server interface. It is no longer responsible for installing itself into the jsonrpc2 Stream, nor for running itself. + A new package 'lsprpc' is added, to implement the logic of binding an incoming connection to an LSP server session. This is put in a separate package for lack of a clear home: it didn't really philosophically belong in any of the lsp, cmd, or protocol packages. We can perhaps move it to cmd in the future, but I'd like to keep it as a separate package while I develop request forwarding. simplified import graph: jsonrpc2 ⭠ lsprpc ⭠ cmd ⭩ ⭦ lsp (t.b.d. client tests) ⭩ ⭨ protocol source + The jsonrpc2 package is extended to have a minimal API for running a 'StreamServer': something analogous to an HTTP server that listens for new connections and delegates to a handler (but we couldn't use the word 'Handler' for this delegate as it was already taken). After these changes, I hope that the concerns of "serving the LSP", "serving jsonrpc2", and "installing the LSP on jsonrpc2" are more logically organized, though one legitimate criticism is that the word 'Server' is still heavily overloaded. This change prepares a subsequent change which hijacks the jsonrpc2 connection when forwarding messages to a shared gopls instance. To test this change, the following improvements are made: + A servertest package is added to make it easier to run a test against an in-process jsonrpc2 server. For now, this uses TCP but it could easily be modified to use io.Pipe. + cmd tests are updated to use the servertest package. Unfortunately it wasn't yet possible to eliminate the concept of `remote=internal` in favor of just using multiple sessions, because view initialization involves calling both `go env` and `packages.Load`, which slow down session startup significantly. See also golang.org/issue/35968. Instead, the syntax for `-remote=internal` is modified to be `-remote=internal@127.0.0.1:12345`. + An additional test for request cancellation is added for the sessionserver package. This test uncovered a bug: when calling Canceller.Cancel, we were using id rather than &id, which resulted in incorrect json serialization (as only the pointer receiver implements the json.Marshaller interface). Updates golang/go#34111 Change-Id: I75c219df634348cdf53a9e57839b98588311a9ef Reviewed-on: https://go-review.googlesource.com/c/tools/+/215742 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-01-21 17:34:50 -07:00
// Server implements the protocol.Server interface.
type Server struct {
client protocol.Client
stateMu sync.Mutex
state serverState
session source.Session
// changedFiles tracks files for which there has been a textDocument/didChange.
changedFiles map[span.URI]struct{}
// folders is only valid between initialize and initialized, and holds the
// set of folders to build views for when we are ready
pendingFolders []protocol.WorkspaceFolder
// delivered is a cache of the diagnostics that the server has sent.
deliveredMu sync.Mutex
delivered map[span.URI]sentDiagnostics
// diagnosticsSema limits the concurrency of diagnostics runs, which can be expensive.
diagnosticsSema chan struct{}
// supportsWorkDoneProgress is set in the initializeRequest
// to determine if the client can support progress notifications
supportsWorkDoneProgress bool
inProgressMu sync.Mutex
inProgress map[string]*WorkDone
}
// sentDiagnostics is used to cache diagnostics that have been sent for a given file.
type sentDiagnostics struct {
version float64
identifier string
sorted []*source.Diagnostic
withAnalysis bool
snapshotID uint64
}
func (s *Server) codeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
snapshot, fh, ok, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
if !ok {
return nil, err
}
switch fh.Kind() {
case source.Mod:
return mod.CodeLens(ctx, snapshot, fh.URI())
case source.Go:
return source.CodeLens(ctx, snapshot, fh)
}
// Unsupported file kind for a code action.
return nil, nil
}
func (s *Server) nonstandardRequest(ctx context.Context, method string, params interface{}) (interface{}, error) {
paramMap := params.(map[string]interface{})
if method == "gopls/diagnoseFiles" {
for _, file := range paramMap["files"].([]interface{}) {
snapshot, fh, ok, err := s.beginFileRequest(ctx, protocol.DocumentURI(file.(string)), source.UnknownKind)
if !ok {
return nil, err
}
fileID, diagnostics, err := source.FileDiagnostics(ctx, snapshot, fh.URI())
if err != nil {
return nil, err
}
if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
URI: protocol.URIFromSpanURI(fh.URI()),
Diagnostics: toProtocolDiagnostics(diagnostics),
Version: fileID.Version,
}); err != nil {
return nil, err
}
}
if err := s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{
URI: "gopls://diagnostics-done",
}); err != nil {
return nil, err
}
return struct{}{}, nil
}
return nil, notImplemented(method)
}
func (s *Server) workDoneProgressCancel(ctx context.Context, params *protocol.WorkDoneProgressCancelParams) error {
token, ok := params.Token.(string)
if !ok {
return errors.Errorf("expected params.Token to be string but got %T", params.Token)
}
s.inProgressMu.Lock()
defer s.inProgressMu.Unlock()
wd, ok := s.inProgress[token]
if !ok {
return errors.Errorf("token %q not found in progress", token)
}
if wd.cancel == nil {
return errors.Errorf("work %q is not cancellable", token)
}
wd.cancel()
return nil
}
func (s *Server) addInProgress(wd *WorkDone) {
s.inProgressMu.Lock()
s.inProgress[wd.token] = wd
s.inProgressMu.Unlock()
}
func (s *Server) removeInProgress(token string) {
s.inProgressMu.Lock()
delete(s.inProgress, token)
s.inProgressMu.Unlock()
}
func notImplemented(method string) error {
return fmt.Errorf("%w: %q not yet implemented", jsonrpc2.ErrMethodNotFound, method)
}
//go:generate helper/helper -d protocol/tsserver.go -o server_gen.go -u .