forked from goplus/goxlsw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
375 lines (348 loc) · 12.1 KB
/
server.go
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package server
import (
"errors"
"fmt"
"maps"
"slices"
"strings"
gopast "github.com/goplus/gop/ast"
goptoken "github.com/goplus/gop/token"
"github.com/goplus/goxlsw/gop"
"github.com/goplus/goxlsw/internal/analysis"
"github.com/goplus/goxlsw/internal/vfs"
"github.com/goplus/goxlsw/jsonrpc2"
)
// MessageReplier is an interface for sending messages back to the client.
type MessageReplier interface {
// ReplyMessage sends a message back to the client.
//
// The message can be one of:
// - [jsonrpc2.Response]: sent in response to a call.
// - [jsonrpc2.Notification]: sent for server-initiated notifications.
ReplyMessage(m jsonrpc2.Message) error
}
// FileMapGetter is a function that returns a map of file names to [vfs.MapFile]s.
type FileMapGetter func() map[string]vfs.MapFile
// Server is the core language server implementation that handles LSP messages.
type Server struct {
workspaceRootURI DocumentURI
workspaceRootFS *vfs.MapFS
replier MessageReplier
analyzers []*analysis.Analyzer
fileMapGetter FileMapGetter // TODO(wyvern): Remove this field.
}
func (s *Server) getProj() *gop.Project {
return s.workspaceRootFS
}
// New creates a new Server instance.
func New(mapFS *vfs.MapFS, replier MessageReplier, fileMapGetter FileMapGetter) *Server {
return &Server{
// TODO(spxls): Initialize request should set workspaceRootURI value
workspaceRootURI: "file:///",
workspaceRootFS: mapFS,
replier: replier,
analyzers: initAnalyzers(true),
fileMapGetter: fileMapGetter,
}
}
// InitAnalyzers initializes the analyzers for the server.
func initAnalyzers(staticcheck bool) []*analysis.Analyzer {
analyzers := slices.Collect(maps.Values(analysis.DefaultAnalyzers))
if staticcheck {
analyzers = slices.AppendSeq(analyzers, maps.Values(analysis.StaticcheckAnalyzers))
}
return analyzers
}
// HandleMessage handles an incoming LSP message.
func (s *Server) HandleMessage(m jsonrpc2.Message) error {
switch m := m.(type) {
case *jsonrpc2.Call:
return s.handleCall(m)
case *jsonrpc2.Notification:
return s.handleNotification(m)
}
return fmt.Errorf("unsupported message type: %T", m)
}
// handleCall handles a call message.
func (s *Server) handleCall(c *jsonrpc2.Call) error {
switch c.Method() {
case "initialize":
var params InitializeParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
return errors.New("TODO")
case "shutdown":
s.runWithResponse(c.ID(), func() (any, error) {
return nil, nil // Protocol conformance only.
})
case "textDocument/hover":
var params HoverParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentHover(¶ms)
})
case "textDocument/completion":
var params CompletionParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentCompletion(¶ms)
})
case "textDocument/signatureHelp":
var params SignatureHelpParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentSignatureHelp(¶ms)
})
case "textDocument/declaration":
var params DeclarationParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentDeclaration(¶ms)
})
case "textDocument/definition":
var params DefinitionParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentDefinition(¶ms)
})
case "textDocument/typeDefinition":
var params TypeDefinitionParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentTypeDefinition(¶ms)
})
case "textDocument/implementation":
var params ImplementationParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentImplementation(¶ms)
})
case "textDocument/references":
var params ReferenceParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentReferences(¶ms)
})
case "textDocument/documentHighlight":
var params DocumentHighlightParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentDocumentHighlight(¶ms)
})
case "textDocument/documentLink":
var params DocumentLinkParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentDocumentLink(¶ms)
})
case "textDocument/diagnostic":
var params DocumentDiagnosticParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentDiagnostic(¶ms)
})
case "workspace/diagnostic":
var params WorkspaceDiagnosticParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.workspaceDiagnostic(¶ms)
})
case "textDocument/formatting":
var params DocumentFormattingParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentFormatting(¶ms)
})
case "textDocument/prepareRename":
var params PrepareRenameParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentPrepareRename(¶ms)
})
case "textDocument/rename":
var params RenameParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentRename(¶ms)
})
case "textDocument/semanticTokens/full":
var params SemanticTokensParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.textDocumentSemanticTokensFull(¶ms)
})
case "workspace/executeCommand":
var params ExecuteCommandParams
if err := UnmarshalJSON(c.Params(), ¶ms); err != nil {
return s.replyParseError(c.ID(), err)
}
s.runWithResponse(c.ID(), func() (any, error) {
return s.workspaceExecuteCommand(¶ms)
})
default:
return s.replyMethodNotFound(c.ID(), c.Method())
}
return nil
}
// handleNotification handles a notification message.
func (s *Server) handleNotification(n *jsonrpc2.Notification) error {
switch n.Method() {
case "initialized":
var params InitializedParams
if err := UnmarshalJSON(n.Params(), ¶ms); err != nil {
return fmt.Errorf("failed to parse initialized params: %w", err)
}
return errors.New("TODO")
case "exit":
return nil // Protocol conformance only.
case "textDocument/didOpen":
var params DidOpenTextDocumentParams
if err := UnmarshalJSON(n.Params(), ¶ms); err != nil {
return fmt.Errorf("failed to parse didOpen params: %w", err)
}
return s.didOpen(¶ms)
case "textDocument/didChange":
var params DidChangeTextDocumentParams
if err := UnmarshalJSON(n.Params(), ¶ms); err != nil {
return fmt.Errorf("failed to parse didChange params: %w", err)
}
return s.didChange(¶ms)
case "textDocument/didSave":
var params DidSaveTextDocumentParams
if err := UnmarshalJSON(n.Params(), ¶ms); err != nil {
return fmt.Errorf("failed to parse didSave params: %w", err)
}
return s.didSave(¶ms)
case "textDocument/didClose":
var params DidCloseTextDocumentParams
if err := UnmarshalJSON(n.Params(), ¶ms); err != nil {
return fmt.Errorf("failed to parse didClose params: %w", err)
}
return s.didClose(¶ms)
}
return nil
}
// publishDiagnostics sends diagnostic notifications to the client.
func (s *Server) publishDiagnostics(uri DocumentURI, diagnostics []Diagnostic) error {
params := &PublishDiagnosticsParams{
URI: uri,
Diagnostics: diagnostics,
}
n, err := jsonrpc2.NewNotification("textDocument/publishDiagnostics", params)
if err != nil {
return fmt.Errorf("failed to create diagnostic notification: %w", err)
}
return s.replier.ReplyMessage(n)
}
// run runs the given function in a goroutine and replies to the client with any
// errors.
func (s *Server) run(id jsonrpc2.ID, fn func() error) {
go func() {
if err := fn(); err != nil {
s.replyError(id, err)
}
}()
}
// runWithResponse runs the given function in a goroutine and handles the response.
func (s *Server) runWithResponse(id jsonrpc2.ID, fn func() (any, error)) {
s.run(id, func() error {
result, err := fn()
resp, err := jsonrpc2.NewResponse(id, result, err)
if err != nil {
return err
}
return s.replier.ReplyMessage(resp)
})
}
// replyError replies to the client with an error response.
func (s *Server) replyError(id jsonrpc2.ID, err error) error {
resp, err := jsonrpc2.NewResponse(id, nil, err)
if err != nil {
return err
}
return s.replier.ReplyMessage(resp)
}
// replyMethodNotFound replies to the client with a method not found error response.
func (s *Server) replyMethodNotFound(id jsonrpc2.ID, method string) error {
return s.replyError(id, fmt.Errorf("%w: %s", jsonrpc2.ErrMethodNotFound, method))
}
// replyParseError replies to the client with a parse error response.
func (s *Server) replyParseError(id jsonrpc2.ID, err error) error {
return s.replyError(id, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err))
}
// fromDocumentURI returns the relative path from a [DocumentURI].
func (s *Server) fromDocumentURI(documentURI DocumentURI) (string, error) {
uri := string(documentURI)
rootURI := string(s.workspaceRootURI)
if !strings.HasPrefix(uri, rootURI) {
return "", fmt.Errorf("document URI %q does not have workspace root URI %q as prefix", uri, rootURI)
}
return strings.TrimPrefix(uri, rootURI), nil
}
// toDocumentURI returns the [DocumentURI] for a relative path.
func (s *Server) toDocumentURI(path string) DocumentURI {
return DocumentURI(string(s.workspaceRootURI) + path)
}
// fromPosition converts a token.Position to an LSP Position.
func (s *Server) fromPosition(astFile *gopast.File, position goptoken.Position) Position {
tokenFile := s.getProj().Fset.File(astFile.Pos())
line := position.Line
lineStart := int(tokenFile.LineStart(line))
relLineStart := lineStart - tokenFile.Base()
lineContent := astFile.Code[relLineStart : relLineStart+position.Column-1]
utf16Offset := utf8OffsetToUTF16(string(lineContent), position.Column-1)
return Position{
Line: uint32(position.Line - 1),
Character: uint32(utf16Offset),
}
}
// rangeForASTFilePosition returns a [Range] for the given position in an AST file.
func (s *Server) rangeForASTFilePosition(astFile *gopast.File, position goptoken.Position) Range {
p := s.fromPosition(astFile, position)
return Range{Start: p, End: p}
}
// rangeForPos returns the [Range] for the given position.
func (s *Server) rangeForPos(pos goptoken.Pos) Range {
return s.rangeForASTFilePosition(s.posASTFile(pos), s.getProj().Fset.Position(pos))
}
// posASTFile returns the AST file for the given position.
func (s *Server) posASTFile(pos goptoken.Pos) *gopast.File {
return getASTPkg(s.getProj()).Files[s.posFilename(pos)]
}
// posFilename returns the filename for the given position.
func (s *Server) posFilename(pos goptoken.Pos) string {
return s.getProj().Fset.Position(pos).Filename
}