-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathclient.go
More file actions
276 lines (240 loc) · 7.8 KB
/
client.go
File metadata and controls
276 lines (240 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2025 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lsp
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/cloudwego/abcoder/lang/log"
"github.com/cloudwego/abcoder/lang/uniast"
lsp "github.com/sourcegraph/go-lsp"
"github.com/sourcegraph/jsonrpc2"
)
type LSPClient struct {
*jsonrpc2.Conn
*lspHandler
tokenTypes []string
tokenModifiers []string
files map[DocumentURI]*TextDocumentItem
provider LanguageServiceProvider
ClientOptions
LspOptions map[string]string
}
type ClientOptions struct {
Server string
uniast.Language
Verbose bool
InitializationOptions interface{}
}
func NewLSPClient(repo string, openfile string, wait time.Duration, opts ClientOptions) (*LSPClient, error) {
// launch golang LSP server
svr, err := startLSPSever(opts.Server, opts)
if err != nil {
return nil, err
}
cli, err := initLSPClient(context.Background(), svr, NewURI(repo), opts.Verbose, opts.Language, opts.InitializationOptions)
if err != nil {
return nil, err
}
cli.ClientOptions = opts
cli.files = make(map[DocumentURI]*TextDocumentItem)
cli.provider = GetProvider(opts.Language)
cli.Verbose = opts.Verbose
if openfile != "" {
_, err := cli.DidOpen(context.Background(), NewURI(openfile))
if err != nil {
return nil, err
}
}
time.Sleep(wait)
return cli, nil
}
func (c *LSPClient) Close() error {
c.lspHandler.Close()
return c.Conn.Close()
}
// Extra wrapper around json rpc to
// 1. implement a transparent, generic cache
func (cli *LSPClient) Call(ctx context.Context, method string, params, result interface{}, opts ...jsonrpc2.CallOption) error {
var raw json.RawMessage
if err := cli.Conn.Call(ctx, method, params, &raw); err != nil {
return err
}
if err := json.Unmarshal(raw, result); err != nil {
return err
}
return nil
}
type initializeParams struct {
ProcessID int `json:"processId,omitempty"`
// RootPath is DEPRECATED in favor of the RootURI field.
RootPath string `json:"rootPath,omitempty"`
RootURI lsp.DocumentURI `json:"rootUri,omitempty"`
ClientInfo lsp.ClientInfo `json:"clientInfo,omitempty"`
Trace lsp.Trace `json:"trace,omitempty"`
InitializationOptions interface{} `json:"initializationOptions,omitempty"`
Capabilities interface{} `json:"capabilities"`
WorkDoneToken string `json:"workDoneToken,omitempty"`
}
type initializeResult struct {
Capabilities interface{} `json:"capabilities,omitempty"`
}
func (c *LSPClient) InitFiles() {
if c.files == nil {
c.files = make(map[DocumentURI]*TextDocumentItem)
}
}
func initLSPClient(ctx context.Context, svr io.ReadWriteCloser, dir DocumentURI, verbose bool, language uniast.Language, InitializationOptions interface{}) (*LSPClient, error) {
h := newLSPHandler()
stream := jsonrpc2.NewBufferedStream(svr, jsonrpc2.VSCodeObjectCodec{})
conn := jsonrpc2.NewConn(ctx, stream, h)
cli := &LSPClient{Conn: conn, lspHandler: h}
// Initialize the LSP server
trace := "off"
if verbose {
trace = "verbose"
}
// NOTICE: some features need to be enabled explicitly
cs := map[string]interface{}{
"workspace": map[string]interface{}{
"symbol": map[string]interface{}{
"dynamicRegistration": true,
},
},
"textDocument": map[string]interface{}{
"documentSymbol": map[string]interface{}{
// Java uses tree-sitter instead of hierarchical symbols
// Golang stays the same as older versions. ABCoder do not use gopls, so don't play with it.
"hierarchicalDocumentSymbolSupport": (language != uniast.Java && language != uniast.Golang),
},
},
}
initParams := initializeParams{
ProcessID: os.Getpid(),
RootURI: lsp.DocumentURI(dir),
Capabilities: cs,
Trace: lsp.Trace(trace),
ClientInfo: lsp.ClientInfo{Name: "vscode"},
InitializationOptions: InitializationOptions,
}
var initResult initializeResult
if err := conn.Call(ctx, "initialize", initParams, &initResult); err != nil {
return nil, err
}
vs, ok := initResult.Capabilities.(map[string]interface{})
if !ok || vs == nil {
return nil, fmt.Errorf("invalid server capabilities: %v", initResult.Capabilities)
}
// check server's capabilities
definitionProvider, ok := vs["definitionProvider"].(bool)
if !ok || !definitionProvider {
return nil, fmt.Errorf("server did not provide Definition")
}
typeDefinitionProvider, ok := vs["typeDefinitionProvider"].(bool)
if !ok || !typeDefinitionProvider {
return nil, fmt.Errorf("server did not provide TypeDefinition")
}
documentSymbolProvider, ok := vs["documentSymbolProvider"].(bool)
if !ok || !documentSymbolProvider {
return nil, fmt.Errorf("server did not provide DocumentSymbol")
}
referencesProvider, ok := vs["referencesProvider"].(bool)
if !ok || !referencesProvider {
return nil, fmt.Errorf("server did not provide References")
}
// SemanticTokensLegend
semanticTokensProvider, ok := vs["semanticTokensProvider"].(map[string]interface{})
if !ok || semanticTokensProvider == nil {
return nil, fmt.Errorf("server did not provide SemanticTokensProvider")
}
legend, ok := semanticTokensProvider["legend"].(map[string]interface{})
if !ok || legend == nil {
return nil, fmt.Errorf("server did not provide SemanticTokensProvider.legend")
}
tokenTypes, ok := legend["tokenTypes"].([]interface{})
if !ok || tokenTypes == nil {
return nil, fmt.Errorf("server did not provide SemanticTokensProvider.legend.tokenTypes")
}
tokenModifiers, ok := legend["tokenModifiers"].([]interface{})
if !ok || tokenModifiers == nil {
return nil, fmt.Errorf("server did not provide SemanticTokensProvider.legend.tokenModifiers")
}
// store to global
for _, t := range tokenTypes {
cli.tokenTypes = append(cli.tokenTypes, t.(string))
}
for _, m := range tokenModifiers {
cli.tokenModifiers = append(cli.tokenModifiers, m.(string))
}
// notify the server that we have initialized
if err := conn.Notify(ctx, "initialized", lsp.InitializeParams{}); err != nil {
return nil, err
}
return cli, nil
}
type rwc struct {
io.ReadCloser
io.WriteCloser
cmd *exec.Cmd
}
func (rwc rwc) Close() error {
if err := rwc.WriteCloser.Close(); err != nil {
return err
}
if rc, ok := rwc.ReadCloser.(io.Closer); ok {
return rc.Close()
}
return rwc.cmd.Wait()
}
// start a LSP process and return its io
func startLSPSever(path string, opts ClientOptions) (io.ReadWriteCloser, error) {
var cmd *exec.Cmd
if uniast.Java == opts.Language {
parts := strings.Fields(path)
cmd = exec.Command(parts[0], parts[1:]...)
} else {
// Launch rust-analyzer
cmd = exec.Command(path)
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, fmt.Errorf("Failed to get stdin pipe: %v", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("Failed to get stdout pipe: %v", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("Failed to get stderr pipe: %v", err)
}
// Read stderr in a separate goroutine
go func() {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
log.Error("LSP server stderr: %s\n", scanner.Text())
// os.Exit(2)
}
}()
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("Failed to start LSP server: %v", err)
}
return rwc{stdout, stdin, cmd}, nil
}