-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathserver.lua
1662 lines (1477 loc) · 47.5 KB
/
server.lua
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Class in charge of establishing communication with an LSP server and
-- managing requests, notifications and responses from both the server
-- and the client that is establishing the connection.
--
-- @copyright Jefferson Gonzalez
-- @license MIT
-- @inspiration: https://github.com/orbitalquark/textadept-lsp
--
-- LSP Documentation:
-- https://microsoft.github.io/language-server-protocol/specifications/specification-3-17
local json = require "plugins.lsp.json"
local util = require "plugins.lsp.util"
local diagnostics = require "plugins.lsp.diagnostics"
local Object = require "core.object"
---@alias lsp.server.callback fun(server: lsp.server, ...)
---@alias lsp.server.timeoutcb fun(server: lsp.server, ...)
---@alias lsp.server.notificationcb fun(server: lsp.server, params: table)
---@alias lsp.server.responsecb fun(server: lsp.server, response: table, request?: lsp.server.request)
---@class lsp.server.languagematch
---@field id string
---@field pattern string
---@class lsp.server.request
---@field id integer
---@field method string
---@field data table|nil
---@field params table
---@field callback lsp.server.responsecb | nil
---@field overwritten boolean
---@field overwritten_callback lsp.server.responsecb | nil
---@field sending boolean
---@field raw_data string
---@field timeout number
---@field timeout_callback lsp.server.timeoutcb | nil
---@field timestamp number
---@field times_sent integer
---LSP Server communication library.
---@class lsp.server : core.object
---@field public name string
---@field public language string | lsp.server.languagematch[]
---@field public file_patterns table
---@field public current_request integer
---@field public init_options table
---@field public settings table | nil
---@field public event_listeners table
---@field public message_listeners table
---@field public request_listeners table
---@field public request_list lsp.server.request[]
---@field public response_list table
---@field public notification_list lsp.server.request[]
---@field public raw_list lsp.server.request[]
---@field public command table
---@field public write_fails integer
---@field public write_fails_before_shutdown integer
---@field public verbose boolean
---@field public initialized boolean
---@field public hitrate_list table
---@field public requests_per_second integer
---@field public proc process | nil
---@field public quit_timeout number
---@field public exit_timer lsp.timer | nil
---@field public capabilities table
---@field public custom_capabilities table
---@field public yield_on_reads boolean
---@field public running boolean
local Server = Object:extend()
---LSP Server constructor options
---@class lsp.server.options
---@field name string
---@field language string | lsp.server.languagematch[]
---@field file_patterns table<integer, string>
---@field command table<integer, string>
---@field quit_timeout number
---@field windows_skip_cmd boolean
---@field env table<string, string>
---@field settings table
---@field init_options table
---@field custom_capabilities table
---@field on_start? fun(server: lsp.server)
---@field requests_per_second number
---@field incremental_changes boolean
Server.options = {
---Name of the server
name = "",
---Programming language identifier.
---Can be a string or a table.
---If the table is empty, the file extension will be used instead.
---The table should be an array of tables containing `id` and `pattern`.
---The `pattern` will be matched with the file path.
---Will use the `id` of the first `pattern` that matches.
---If no pattern matches, the file extension will be used instead.
language = {},
---Patterns to match the language files
file_patterns = {},
---Command to launch LSP server and optional arguments
command = {},
---On Windows, avoid running the LSP server with cmd.exe
windows_skip_cmd = false,
---Enviroment variables to set for the server command
env = {},
---Seconds before closing the server when not needed anymore
quit_timeout = 60,
---Optional table of settings to pass into the LSP
---Note that also having a settings.json or settings.lua in
---your workspace directory is supported
settings = {},
---Optional table of initializationOptions for the LSP
init_options = {},
---Optional table of capabilities that will be merged with our default one
custom_capabilities = {},
---Function called when the server has been started
on_start = nil,
---Set by default to 16 should only be modified if having issues with a server
requests_per_second = 32,
---Some servers like bash language server support incremental changes
---which are more performant but don't advertise it, set to true to force
---incremental changes even if server doesn't advertise them
incremental_changes = false,
---True to debug the lsp client when developing it
verbose = false,
}
---Default timeout when sending a request to lsp server.
---@type integer Time in seconds
Server.DEFAULT_TIMEOUT = 10
---The maximum amount of data to retrieve when reading from server.
---@type integer Amount of bytes
Server.BUFFER_SIZE = 1024 * 10
---LSP Docs: /#errorCodes
Server.error_code = {
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
jsonrpcReservedErrorRangeStart = -32099,
serverErrorStart = -32099,
ServerNotInitialized = -32002,
UnknownErrorCode = -32001,
jsonrpcReservedErrorRangeEnd = -32000,
serverErrorEnd = -32000,
lspReservedErrorRangeStart = -32899,
ContentModified = -32801,
RequestCancelled = -32800,
lspReservedErrorRangeEnd = -32800,
}
---LSP Docs: /#completionTriggerKind
Server.completion_trigger_Kind = {
Invoked = 1,
TriggerCharacter = 2,
TriggerForIncompleteCompletions = 3
}
---LSP Docs: /#diagnosticSeverity
Server.diagnostic_severity = {
Error = 1,
Warning = 2,
Information = 3,
Hint = 4
}
---LSP Docs: /#textDocumentSyncKind
Server.text_document_sync_kind = {
None = 0,
Full = 1,
Incremental = 2
}
---LSP Docs: /#completionItemKind
Server.completion_item_kind = {
'Text', 'Method', 'Function', 'Constructor', 'Field', 'Variable', 'Class',
'Interface', 'Module', 'Property', 'Unit', 'Value', 'Enum', 'Keyword',
'Snippet', 'Color', 'File', 'Reference', 'Folder', 'EnumMember',
'Constant', 'Struct', 'Event', 'Operator', 'TypeParameter'
}
---LSP Docs: /#symbolKind
Server.symbol_kind = {
'File', 'Module', 'Namespace', 'Package', 'Class', 'Method', 'Property',
'Field', 'Constructor', 'Enum', 'Interface', 'Function', 'Variable',
'Constant', 'String', 'Number', 'Boolean', 'Array', 'Object', 'Key',
'Null', 'EnumMember', 'Struct', 'Event', 'Operator', 'TypeParameter'
}
---LSP Docs: /#insertTextFormat
Server.insert_text_format = {
PlainText = 1,
Snippet = 2
}
---LSP Docs: /#messageType
---@enum
Server.message_type = {
Error = 1,
Warning = 2,
Info = 3,
Log = 4,
Debug = 5
}
---LSP Docs: /#positionEncodingKind
---@enum
Server.position_encoding_kind = {
UTF8 = 'utf-8',
UTF16 = 'utf-16',
UTF32 = 'utf-32'
}
---@class lsp.server.requestoptions
---@field params? table<string,any>
---@field data? table @Optional data appended to request.
---@field callback? lsp.server.responsecb @Default callback executed when a response is received.
---@field overwrite? boolean @Substitute same previous request with new one if not sent.
---@field overwritten_callback? lsp.server.responsecb @Executed in place of original response callback if the request should have been overwritten but was already sent.
---@field raw_data? string @Request body used when sending a raw request.
---@field timeout? number @Timeout in seconds to consider the request unanswered.
---@field timeout_callback? lsp.server.timeoutcb @Callback executed when the request times out.
---Get a completion kind label from its id or empty string if not found.
---@param id integer
---@return string
function Server.get_completion_item_kind(id)
return Server.completion_item_kind[id] or ""
end
---Get list of completion kinds.
---@return table
function Server.get_completion_items_kind_list()
local list = {}
for i = 1, #Server.completion_item_kind do
if i ~= 15 then --Disable snippets
table.insert(list, i)
end
end
return list
end
---Get a symbol kind label from its id or empty string if not found.
---@param id integer
---@return string
function Server.get_symbol_kind(id)
return Server.symbol_kind[id] or ""
end
---Get list of symbol kinds.
---@return table
function Server.get_symbols_kind_list()
local list = {}
for i = 1, #Server.symbol_kind do
list[i] = i
end
return list
end
---Given a ServerCapabilities object, return a "normalized" version
---that simplifies capabilities checks.
---@param capabilities table
---returns table
function Server.normalize_server_capabilities(capabilities)
local cap = util.deep_merge({ }, capabilities)
local tds = {
openClose = false,
change = false,
willSave = false,
willSaveWaitUntil = false,
save = false
}
if cap.textDocumentSync then
if type(cap.textDocumentSync) ~= "table" then
-- Convert TextDocumentSyncKind into TextDocumentSyncOptions
tds = util.deep_merge(tds, {
openClose = true,
change = cap.textDocumentSync,
save = {
includeText = false
}
})
cap.textDocumentSync = nil
else
tds = util.deep_merge(tds, cap.textDocumentSync)
if type(tds.save) ~= "table" and tds.save then
tds.save = {
includeText = false
}
end
end
end
cap.textDocumentSync = util.deep_merge(cap.textDocumentSync, tds)
return cap
end
---Instantiates a new LSP server.
---@param options lsp.server.options
function Server:new(options)
Server.super.new(self)
self.name = options.name
self.language = options.language
self.file_patterns = options.file_patterns
self.current_request = 0
self.init_options = options.init_options or {}
self.settings = options.settings or nil
self.event_listeners = {}
self.message_listeners = {}
self.request_listeners = {}
self.request_list = {}
self.response_list = {}
self.notification_list = {}
self.raw_list = {}
self.command = options.command
self.write_fails = 0
self.fatal_error = false
self.snippets = options.snippets
self.fake_snippets = options.fake_snippets or false
-- TODO: We may need to lower this but tests so far show that some servers
-- may actually fail to write many of the request sent to it if it is
-- indexing the workspace source code or other heavy tasks.
self.write_fails_before_shutdown = 60
self.verbose = options.verbose or false
self.last_restart = system.get_time()
self.initialized = false
self.hitrate_list = {}
self.requests_per_second = options.requests_per_second or 16
self.proc = process.start(
options.command, {
stderr = process.REDIRECT_PIPE,
env = options.env
}
)
self.quit_timeout = options.quit_timeout or 60
self.exit_timer = nil
self.capabilities = nil
self.custom_capabilities = options.custom_capabilities
self.yield_on_reads = false
self.incremental_changes = options.incremental_changes or false
self.read_responses_coroutine = nil
if options.on_start then options.on_start(self) end
end
---Starts the LSP server process, any listeners should be registered before
---calling this method and this method should be called before any pushes.
---@param workspace string
---@param editor_name? string
---@param editor_version? string
function Server:initialize(workspace, editor_name, editor_version)
local root_uri = util.touri(workspace);
self.path = workspace or ""
self.editor_name = editor_name or "unknown"
self.editor_version = editor_version or "0.1"
self:push_request('initialize', {
timeout = 10,
params = {
processId = system["get_process_id"] and system.get_process_id() or nil,
clientInfo = {
name = editor_name or "unknown",
version = editor_version or "0.1"
},
-- TODO: locale
rootPath = workspace,
rootUri = root_uri,
workspaceFolders = {
{uri = root_uri, name = util.getpathname(workspace)}
},
initializationOptions = self.init_options,
capabilities = util.deep_merge({
workspace = {
configuration = true -- 'workspace/configuration' requests
},
textDocument = {
synchronization = {
-- willSave = true,
-- willSaveWaitUntil = true,
didSave = true,
-- dynamicRegistration = false -- not supported
},
completion = {
-- dynamicRegistration = false, -- not supported
completionItem = {
-- Snippets are required by css-languageserver
snippetSupport = self.snippets or self.fake_snippets,
-- commitCharactersSupport = true,
documentationFormat = {'plaintext'},
-- deprecatedSupport = false, -- simple autocompletion list
-- preselectSupport = true
-- tagSupport = {valueSet = {}},
insertReplaceSupport = true,
resolveSupport = {properties = {'documentation', 'detail', 'additionalTextEdits'}},
-- insertTextModeSupport = {valueSet = {}}
},
completionItemKind = {
valueSet = Server.get_completion_items_kind_list()
}
-- contextSupport = true
},
hover = {
-- dynamicRegistration = false, -- not supported
contentFormat = {'markdown', 'plaintext'}
},
signatureHelp = {
-- dynamicRegistration = false, -- not supported
signatureInformation = {
documentationFormat = {'plaintext'}
-- parameterInformation = {labelOffsetSupport = true},
-- activeParameterSupport = true
}
-- contextSupport = true
},
-- references = {dynamicRegistration = false}, -- not supported
-- documentHighlight = {dynamicRegistration = false}, -- not supported
documentSymbol = {
-- dynamicRegistration = false, -- not supported
symbolKind = {valueSet = Server.get_symbols_kind_list()}
-- hierarchicalDocumentSymbolSupport = true,
-- tagSupport = {valueSet = {}},
-- labelSupport = true
},
-- diagnostic = {
-- dynamicRegistration = true,
-- relatedDocumentSupport = false
-- },
-- formatting = {dynamicRegistration = false},-- not supported
-- rangeFormatting = {dynamicRegistration = false}, -- not supported
-- onTypeFormatting = {dynamicRegistration = false}, -- not supported
-- declaration = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- }
-- definition = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- typeDefinition = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- implementation = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- codeAction = {
-- dynamicRegistration = false, -- not supported
-- codeActionLiteralSupport = {valueSet = {}},
-- isPreferredSupport = true,
-- disabledSupport = true,
-- dataSupport = true,
-- resolveSupport = {properties = {}},
-- honorsChangeAnnotations = true
-- },
-- codeLens = {dynamicRegistration = false}, -- not supported
-- documentLink = {
-- dynamicRegistration = false, -- not supported
-- tooltipSupport = true
-- },
-- colorProvider = {dynamicRegistration = false}, -- not supported
-- rename = {
-- dynamicRegistration = false, -- not supported
-- prepareSupport = false
-- },
publishDiagnostics = {
relatedInformation = true,
tagSupport = {
valueSet = {
diagnostics.tag.UNNECESSARY,
diagnostics.tag.DEPRECATED
}
},
versionSupport = true,
codeDescriptionSupport = true,
dataSupport = false
},
-- foldingRange = {
-- dynamicRegistration = false, -- not supported
-- rangeLimit = ?,
-- lineFoldingOnly = true
-- },
-- selectionRange = {dynamicRegistration = false}, -- not supported
-- linkedEditingRange = {dynamicRegistration = false}, -- not supported
-- callHierarchy = {dynamicRegistration = false}, -- not supported
-- semanticTokens = {
-- dynamicRegistration = false, -- not supported
-- requests = {},
-- tokenTypes = {},
-- tokenModifiers = {},
-- formats = {},
-- overlappingTokenSupport = true,
-- multilineTokenSupport = true
-- },
-- moniker = {dynamicRegistration = false} -- not supported
},
window = {
-- workDoneProgress = true,
-- showMessage = {},
showDocument = { support = true }
},
general = {
-- regularExpressions = {},
-- markdown = {},
positionEncodings = {
Server.position_encoding_kind.UTF16
}
},
-- experimental = nil
}, self.custom_capabilities)
},
callback = function(server, response)
if server.verbose then
server:log(
"Processing initialization response:\n%s",
util.jsonprettify(json.encode(response))
)
end
local result = response.result
if result then
server.capabilities = Server.normalize_server_capabilities(result.capabilities)
server.info = result.serverInfo
if server.info then
server:log(
'Connected to %s %s',
server.info.name,
server.info.version or '(unknown version)'
)
end
while not server:notify('initialized') do end -- required by protocol
-- We wait a few seconds to prevent initialization issues
coroutine.yield(3)
server.initialized = true;
server:send_event_signal("initialized", server, result)
end
end
})
end
---Register an event listener.
---@param event_name string
---@param callback lsp.server.callback
function Server:add_event_listener(event_name, callback)
if self.verbose then
self:log(
"Listening for event '%s'",
event_name
)
end
if not self.event_listeners[event_name] then
self.event_listeners[event_name] = {}
end
table.insert(self.event_listeners[event_name], callback)
end
function Server:send_event_signal(event_name, ...)
if self.event_listeners[event_name] then
for _, l in ipairs(self.event_listeners[event_name]) do
l(self, ...)
end
else
self:on_event(event_name)
end
end
function Server:on_event(event_name)
if self.verbose then
self:log("Received event '%s'", event_name)
end
end
---Send a message to the server that doesn't needs a response.
---@param method string
---@param params? table
---@return boolean sent
function Server:notify(method, params)
local message = {
jsonrpc = '2.0',
method = method,
params = params or {}
}
local data = json.encode(message)
if self.verbose then
self:log("Sending notification:\n%s", util.jsonprettify(data))
end
local sent, errmsg = self:write_request(data)
if not sent and self.verbose then
self:log(
"Could not send '%s' notification with error: %s",
method,
errmsg or "unknown"
)
end
return sent
end
---Reply to a server request.
---@param id integer
---@param result table
---@return boolean sent
function Server:respond(id, result)
local message = {
jsonrpc = '2.0',
id = id,
result = result
}
local data = json.encode(message)
if self.verbose then
self:log("Responding to '%d':\n%s", id, util.jsonprettify(data))
end
local sent, errmsg = self:write_request(data)
if not sent and self.verbose then
self:log("Could not send response with error: %s", errmsg or "unknown")
end
return sent
end
---Respond to a an unknown server request with a method not found error code.
---@param id integer
---@param error_message? string
---@param error_code? integer
---@return boolean sent
function Server:respond_error(id, error_message, error_code)
local message = {
jsonrpc = '2.0',
id = id,
error = {
code = error_code or Server.error_code.MethodNotFound,
message = error_message or "method not found"
}
}
local data = json.encode(message)
if self.verbose then
self:log("Responding error to '%d':\n%s", id, util.jsonprettify(data))
end
local sent, errmsg = self:write_request(data)
if not sent and self.verbose then
self:log("Could not send response with error: %s", errmsg or "unknown")
end
return sent
end
---Sends one of the queued notifications.
function Server:process_notifications()
if not self.initialized then return end
-- Clone table as we remove elements while iterating it
local notifications = {}
for index, request in ipairs(self.notification_list) do
notifications[index] = request
end
for index, request in ipairs(notifications) do
request.sending = true
local message = {
jsonrpc = '2.0',
method = request.method,
params = request.params or {}
}
local data = json.encode(message)
if self.verbose then
self:log(
"Sending notification '%s':\n%s",
request.method,
util.jsonprettify(data)
)
end
local written, errmsg = self:write_request(data)
if self.verbose then
if not written then
self:log(
"Failed sending notification '%s' with error: %s",
request.method,
errmsg or "unknown"
)
end
end
if written then
if request.callback then
request.callback(self)
end
table.remove(self.notification_list, index)
self.write_fails = 0
return request
else
self:shutdown_if_needed()
return
end
end
end
---Sends one of the queued client requests.
function Server:process_requests()
if not self.proc then return end
local remove_request = nil
for index, request in ipairs(self.request_list) do
if request.timestamp < os.time() then
-- only process when initialized or the initialize request
-- which should be the first one.
if not self.initialized and request.id ~= 1 then
return nil
end
local message = {
jsonrpc = '2.0',
id = request.id,
method = request.method,
params = request.params or {}
}
local data = json.encode(message)
local written, errmsg = self:write_request(data)
if self.verbose then
if written then
self:log(
"Sent request '%s':\n%s",
request.method,
util.jsonprettify(data)
)
else
self:log(
"Failed sending request '%s' with error: %s\n%s",
request.method,
errmsg or "unknown",
util.jsonprettify(data)
)
end
end
if written then
local time = request.timeout or 1
request.timestamp = os.time() + time
self.write_fails = 0
-- if request has been sent more than 2 times remove them
request.times_sent = request.times_sent + 1
if
request.times_sent > 1
and
request.id ~= 1 -- Initialize request may take some time
then
remove_request = index
break
else
return request
end
else
request.timestamp = os.time() + 1
self:shutdown_if_needed()
return nil
end
end
end
if remove_request then
local request = table.remove(self.request_list, remove_request)
if self.verbose then
self:log("Request '%s' expired without response", remove_request)
end
if request.timeout_callback then
request.timeout_callback(request)
end
end
return nil
end
---Read the lsp server stdout, parse any responses, requests or
---notifications and properly dispatch signals to any listeners.
function Server:process_responses()
if not self.proc then return end
local responses = self:read_responses(0)
if type(responses) == "table" then
for _, response in pairs(responses) do
if self.verbose then
self:log(
"Processing Response:\n%s",
util.jsonprettify(json.encode(response))
)
end
if not response.id then
-- A notification, event or generic message was received
self:send_message_signal(response)
elseif
response.result
or
(not response.params and not response.method)
then
-- An actual request response was received
self:send_response_signal(response)
else
-- The server is making a request
self:send_request_signal(response)
end
end
end
return responses
end
---Sends all queued client responses to server.
function Server:process_client_responses()
if not self.initialized then return end
::send_responses::
for index, response in ipairs(self.response_list) do
local message = {
jsonrpc = '2.0',
id = response.id
}
if response.result then
message.result = response.result
else
message.error = response.error
end
local data = json.encode(message)
if self.verbose then
self:log("Sending client response:\n%s", util.jsonprettify(data))
end
local written, errmsg = self:write_request(data)
if self.verbose then
if not written then
self:log(
"Failed sending client response '%s' with error: %s",
response.id,
errmsg or "unknown"
)
end
end
if written then
self.write_fails = 0
table.remove(self.response_list, index)
-- restart loop after removing from table to prevent issues
goto send_responses
else
self:shutdown_if_needed()
return
end
end
end
---Should be called periodically to prevent the server from stalling
---because of not flushing the stderr (especially true of clangd).
---@param log_errors boolean
function Server:process_errors(log_errors)
if not self.proc then return end
local errors = self:read_errors(0)
if #errors > 0 and log_errors then
self:log("Error: \n'%s'", errors)
end
return errors
end
---Sends raw data to the server process and ensures that all of it is written
---if no errors occur, otherwise it returns false and the error message. Notice
---that this function can perform yielding when ran inside of a coroutine.
---@param data string
---@return boolean sent
---@return string? errmsg
function Server:send_data(data)
local proc = self.proc -- save current process to avoid it changing
if not proc then return false end
local failures, data_len = 0, #data
local written, errmsg = proc:write(data)
local total_written = written or 0
while total_written < data_len and not errmsg do
written, errmsg = proc:write(data:sub(total_written + 1))
total_written = total_written + (written or 0)
if (not written or written <= 0) and not errmsg and coroutine.running() then
-- with each consecutive fail the yield timeout is increased by 5ms
coroutine.yield((failures * 5) / 1000)
failures = failures + 1
if failures > 19 then -- after ~1000ms we error out
errmsg = "maximum amount of consecutive failures reached"
break
end
else
failures = 0
end
end
if errmsg then
self:log("Error sending data: '%s'\n%s", errmsg, data)
end
return total_written == data_len, errmsg
end
---Send one of the queued chunks of raw data to lsp server which are
---usually huge, like the textDocument/didOpen notification.
function Server:process_raw()
if not self.initialized then return end
-- Wait until everything else is processed to prevent initialization issues
if
#self.notification_list > 0
or
#self.request_list > 0
or
#self.response_list > 0
then
return
end
if not self.proc or not self.proc:running() then
self.raw_list = {}
return
end
local sent = false
for index, raw in ipairs(self.raw_list) do
raw.sending = true
-- first send the header
if
not self:send_data(string.format(
'Content-Length: %d\r\n\r\n', #raw.raw_data
))
then
break
end
if self.verbose then
self:log("Raw header written")
end
-- send content in chunks
local chunks = 10 * 1024
raw.raw_data = raw.raw_data
while #raw.raw_data > 0 do
if not self.proc or not self.proc:running() then
self.raw_list = {}
return
end
if #raw.raw_data > chunks then
-- TODO: perform proper error handling
self:send_data(raw.raw_data:sub(1, chunks))
raw.raw_data = raw.raw_data:sub(chunks+1)
else
-- TODO: perform proper error handling
self:send_data(raw.raw_data)
raw.raw_data = ""
end
self.write_fails = 0
coroutine.yield()