-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlanguageserverclient.cpp
More file actions
1400 lines (1184 loc) · 35.8 KB
/
Copy pathlanguageserverclient.cpp
File metadata and controls
1400 lines (1184 loc) · 35.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
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
#include "codeedit.h"
#include <chrono>
#ifdef _WIN32
#include "languageserverclient.h"
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#include "languageserverclient.h"
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <poll.h>
#endif
#include <algorithm>
#include <cctype>
// Global variables (keeping same structure as original)
std::string langID;
std::string missingNext;
std::string currentExecution;
std::string fileRootURI;
struct LspIdCompare {
bool operator()(const LspId& a, const LspId& b) const {
if (a.index() != b.index()) {
return a.index() < b.index();
}
if (std::holds_alternative<std::nullptr_t>(a)) {
return false; // null == null
}
if (std::holds_alternative<int>(a)) {
return std::get<int>(a) < std::get<int>(b);
}
if (std::holds_alternative<std::string>(a)) {
return std::get<std::string>(a) < std::get<std::string>(b);
}
return false;
}
};
std::map<LspId, std::string, LspIdCompare> requestsMap;
json diagnostics;
bool quitting = false;
int shutdownId = -999;
bool alreadyDoneShutdownLoop = false;
bool failedToStart = false;
int initializeRequestId = -999;
#ifdef _WIN32
static std::wstring Utf8ToWide(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
std::wstring w(n, L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), n);
return w;
}
static std::wstring QuoteIfNeeded(const std::wstring& s) {
if (s.empty()) return L"\"\"";
bool need = s.find_first_of(L" \t\"") != std::wstring::npos;
if (!need) return s;
std::wstring out; out.reserve(s.size()+2);
out.push_back(L'"');
for (wchar_t ch : s) {
if (ch == L'"') out += L"\\\"";
else out.push_back(ch);
}
out.push_back(L'"');
return out;
}
#endif
// Process implementation
class Process::ProcessImpl {
public:
#ifdef _WIN32
HANDLE hChildStdInRd = nullptr;
HANDLE hChildStdInWr = nullptr;
HANDLE hChildStdOutRd = nullptr;
HANDLE hChildStdOutWr = nullptr;
PROCESS_INFORMATION piProcInfo{};
STARTUPINFO siStartInfo{};
#else
pid_t pid = -1;
int stdin_pipe[2] = {-1, -1};
int stdout_pipe[2] = {-1, -1};
#endif
std::string errorStr;
std::atomic<bool> running{false};
std::thread readerThread;
std::string buffer;
std::mutex bufferMutex;
};
Process::Process() : impl(std::make_unique<ProcessImpl>()) {}
Process::~Process() {
terminate();
if (impl->readerThread.joinable()) {
impl->readerThread.join();
}
}
bool Process::start(const std::string& program, const std::vector<std::string>& arguments) {
#ifdef _WIN32
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = nullptr;
if (!CreatePipe(&impl->hChildStdOutRd, &impl->hChildStdOutWr, &saAttr, 0)) {
impl->errorStr = "Failed to create stdout pipe";
return false;
}
if (!CreatePipe(&impl->hChildStdInRd, &impl->hChildStdInWr, &saAttr, 0)) {
impl->errorStr = "Failed to create stdin pipe";
return false;
}
SetHandleInformation(impl->hChildStdOutRd, HANDLE_FLAG_INHERIT, 0);
SetHandleInformation(impl->hChildStdInWr, HANDLE_FLAG_INHERIT, 0);
ZeroMemory(&impl->piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&impl->siStartInfo, sizeof(STARTUPINFOW));
impl->siStartInfo.cb = sizeof(STARTUPINFOW);
impl->siStartInfo.hStdError = impl->hChildStdOutWr;
impl->siStartInfo.hStdOutput = impl->hChildStdOutWr;
impl->siStartInfo.hStdInput = impl->hChildStdInRd;
impl->siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
impl->siStartInfo.wShowWindow = SW_HIDE;
// Build a PROPER, WRITABLE wide command-line buffer with quoting
std::wstring cmdW = QuoteIfNeeded(Utf8ToWide(program));
for (const auto& a : arguments) {
cmdW.push_back(L' ');
cmdW += QuoteIfNeeded(Utf8ToWide(a));
}
std::vector<wchar_t> cmdBuf(cmdW.begin(), cmdW.end());
cmdBuf.push_back(L'\0');
DWORD creationFlags = CREATE_NO_WINDOW;
// Only the child-ends must be inheritable.
// (You already cleared inheritance on the parent-ends above; good.)
BOOL ok = CreateProcessW(
/*lpApplicationName*/ nullptr, // we’re using the parsed command line
/*lpCommandLine */ cmdBuf.data(), // MUST be mutable
/*proc attrs */ nullptr,
/*thread attrs */ nullptr,
/*inherit handles */ TRUE, // we want the child to inherit our pipe ends
/*creation flags */ creationFlags,
/*environment */ nullptr,
/*current dir */ nullptr,
/*startup info */ &impl->siStartInfo,
/*process info */ &impl->piProcInfo);
if (!ok) {
DWORD err = GetLastError();
wchar_t* msg = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, err, 0, (LPWSTR)&msg, 0, nullptr);
std::wstring w = L"CreateProcessW failed: " + std::to_wstring(err) + L" ";
if (msg) { w += msg; LocalFree(msg); }
std::string u8 = std::string(w.begin(), w.end());
impl->errorStr = u8;
return false;
}
CloseHandle(impl->hChildStdOutWr);
CloseHandle(impl->hChildStdInRd);
impl->running = true;
// Start reader thread
impl->readerThread = std::thread([this]() {
char buffer[4096];
DWORD bytesRead;
while (impl->running && ReadFile(impl->hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, nullptr) && bytesRead > 0) {
{
std::lock_guard<std::mutex> lock(impl->bufferMutex);
impl->buffer.append(buffer, bytesRead);
}
if (readyReadCallback) {
readyReadCallback();
}
}
if (impl->running) {
impl->running = false;
DWORD exitCode = 0;
if (GetExitCodeProcess(impl->piProcInfo.hProcess, &exitCode)) {
if (finishedCallback) finishedCallback((int)exitCode, NormalExit);
} else {
if (finishedCallback) finishedCallback(-1, CrashExit);
}
}
});
return true;
#else
if (pipe(impl->stdin_pipe) == -1 || pipe(impl->stdout_pipe) == -1) {
impl->errorStr = "Failed to create pipes";
return false;
}
impl->pid = fork();
if (impl->pid == -1) {
impl->errorStr = "Failed to fork process";
return false;
}
if (impl->pid == 0) {
// Child process
::close(impl->stdin_pipe[1]);
::close(impl->stdout_pipe[0]);
dup2(impl->stdin_pipe[0], STDIN_FILENO);
dup2(impl->stdout_pipe[1], STDOUT_FILENO);
dup2(impl->stdout_pipe[1], STDERR_FILENO);
::close(impl->stdin_pipe[0]);
::close(impl->stdout_pipe[1]);
std::vector<char*> args;
args.push_back(const_cast<char*>(program.c_str()));
for (const auto& arg : arguments) {
args.push_back(const_cast<char*>(arg.c_str()));
}
args.push_back(nullptr);
execvp(program.c_str(), args.data());
exit(1);
} else {
// Parent process
::close(impl->stdin_pipe[0]);
::close(impl->stdout_pipe[1]);
// Make stdout non-blocking
int flags = fcntl(impl->stdout_pipe[0], F_GETFL, 0);
fcntl(impl->stdout_pipe[0], F_SETFL, flags | O_NONBLOCK);
impl->running = true;
// Start reader thread
impl->readerThread = std::thread([this]() {
char buffer[4096];
while (impl->running) {
pollfd pfd = {impl->stdout_pipe[0], POLLIN, 0};
int result = poll(&pfd, 1, 100); // 100ms timeout
if (result > 0 && (pfd.revents & POLLIN)) {
ssize_t bytesRead = read(impl->stdout_pipe[0], buffer, sizeof(buffer));
if (bytesRead > 0) {
{
std::lock_guard<std::mutex> lock(impl->bufferMutex);
impl->buffer.append(buffer, bytesRead);
}
if (readyReadCallback) {
readyReadCallback();
}
} else if (bytesRead == 0) {
break; // EOF
}
}
}
if (impl->running) {
impl->running = false;
int status;
int exitCode = -1;
ExitStatus exitStatus = CrashExit;
if (waitpid(impl->pid, &status, WNOHANG) >= 0) {
if (WIFEXITED(status)) {
exitCode = WEXITSTATUS(status);
exitStatus = NormalExit;
} else if (WIFSIGNALED(status)) {
exitCode = WTERMSIG(status);
exitStatus = CrashExit;
}
}
if (finishedCallback) finishedCallback(exitCode, exitStatus);
}
});
}
return true;
#endif
}
void Process::write(const std::string& data) {
#ifdef _WIN32
DWORD bytesWritten;
WriteFile(impl->hChildStdInWr, data.c_str(), data.length(), &bytesWritten, nullptr);
#else
::write(impl->stdin_pipe[1], data.c_str(), data.length());
#endif
}
std::string Process::readAll() {
std::lock_guard<std::mutex> lock(impl->bufferMutex);
std::string result = impl->buffer;
impl->buffer.clear();
return result;
}
int Process::bytesAvailable() {
std::lock_guard<std::mutex> lock(impl->bufferMutex);
return impl->buffer.length();
}
void Process::terminate() {
impl->running = false;
#ifdef _WIN32
if (impl->piProcInfo.hProcess) {
TerminateProcess(impl->piProcInfo.hProcess, 0);
}
#else
if (impl->pid > 0) {
::kill(impl->pid, SIGTERM);
}
#endif
}
void Process::kill() {
#ifdef _WIN32
if (impl->piProcInfo.hProcess) {
TerminateProcess(impl->piProcInfo.hProcess, 9);
}
#else
if (impl->pid > 0) {
::kill(impl->pid, SIGKILL);
}
#endif
}
bool Process::waitForStarted(int timeout) {
// Simple implementation - just check if process started
return impl->running;
}
bool Process::waitForFinished(int timeout) {
#ifdef _WIN32
if (impl->piProcInfo.hProcess) {
DWORD result = WaitForSingleObject(impl->piProcInfo.hProcess, timeout);
return result == WAIT_OBJECT_0;
}
#else
if (impl->pid > 0) {
int status;
pid_t result = waitpid(impl->pid, &status, WNOHANG);
return result == impl->pid;
}
#endif
return false;
}
void Process::close() {
#ifdef _WIN32
if (impl->hChildStdInWr) CloseHandle(impl->hChildStdInWr);
if (impl->hChildStdOutRd) CloseHandle(impl->hChildStdOutRd);
if (impl->piProcInfo.hProcess) CloseHandle(impl->piProcInfo.hProcess);
if (impl->piProcInfo.hThread) CloseHandle(impl->piProcInfo.hThread);
#else
if (impl->stdin_pipe[1] != -1) ::close(impl->stdin_pipe[1]);
if (impl->stdout_pipe[0] != -1) ::close(impl->stdout_pipe[0]);
#endif
}
std::string Process::errorString() const {
return impl->errorStr;
}
// URL conversion functions
std::string LanguageServerClient::fromLocalFile(const std::string& path) {
#ifdef _WIN32
std::string result = "file:///" + path;
std::replace(result.begin(), result.end(), '\\', '/');
return result;
#else
return "file://" + path;
#endif
}
// LanguageServerClient implementation
LanguageServerClient::LanguageServerClient(const std::string &serverPath, std::function<void(const std::string&)> lg)
: requestId(0), documentVersion(1)
{
logCallback = lg;
lspPath = serverPath;
langID = "";
missingNext = "";
currentExecution = "";
fileRootURI = "";
requestsMap.clear();
diagnostics = json::array();
quitting = false;
shutdownId = -999;
alreadyDoneShutdownLoop = false;
initializeRequestId = -999;
failedToStart = false;
stopWriter = false;
writerThread = std::thread([this] {
writerLoop();
});
serverProcess.readyReadCallback = [this]() { onServerReadyRead(); };
serverProcess.errorCallback = [this](Process::ProcessError error) { onServerErrorOccurred(error); };
serverProcess.finishedCallback = [this](int exitCode, Process::ExitStatus exitStatus) { onServerFinished(exitCode, exitStatus); };
#ifdef _WIN32
if (!serverProcess.start("cmd", {"/c", serverPath})) {
#else
if (!serverProcess.start("/bin/sh", {"-c", serverPath})) {
#endif
failedToStart = true;
if (logCallback) {
App::displayToast(icu::UnicodeString::fromUTF8("Failed to start language server at: " + serverPath + "\nError: " + serverProcess.errorString()));
logCallback("Failed to start language server at: " + serverPath + "\nError: " + serverProcess.errorString());
}
}
}
void LanguageServerClient::onServerErrorOccurred(Process::ProcessError error)
{
if (logCallback) {
logCallback("Server error occurred: " + std::to_string(static_cast<int>(error)) + "\nError String: " + serverProcess.errorString());
}
initializeComplete = true;
initializeCondition.notify_all();
failedToStart = true;
}
void LanguageServerClient::onServerFinished(int exitCode, Process::ExitStatus exitStatus)
{
if (logCallback) {
logCallback("Server process finished with exit code: " + std::to_string(exitCode) + " and status: " + std::to_string(static_cast<int>(exitStatus)));
}
initializeComplete = true;
initializeCondition.notify_all();
failedToStart = true;
}
LanguageServerClient::~LanguageServerClient()
{
{
std::lock_guard<std::mutex> lk(queueMutex);
stopWriter = true;
}
queueCond.notify_all();
if (writerThread.joinable()) writerThread.join();
shutdown();
}
void LanguageServerClient::initialize(const std::string &rootUri)
{
fileRootURI = fromLocalFile(rootUri);
json capabilities = {
{"textDocument", {
{"completion", {
{"completionItem", {
{"snippetSupport", true},
{"resolveSupport", {
{"properties", {"documentation", "detail", "additionalTextEdits"}}
}}
}}
}},
{"synchronization", {
{"dynamicRegistration", true},
{"didSave", true},
{"didChange", true},
{"willSave", false}
}},
{"publishDiagnostics", {
{"enabled", true},
{"relatedInformation", true}
}}
}},
{"completionProvider", {
{"resolveProvider", true},
{"triggerCharacters", {".", ":", ">", "<", "/", "@", "*", "(", "[", "{", "'", "\"", "#"}}
}},
{"workspace", {
{"workspaceFolders", true},
{"configuration", true}
}}
};
json params = {
{"rootUri", fileRootURI},
{"capabilities", capabilities},
{"clientInfo", {
{"name", "CodeWizardLSP"},
{"version", "1.0.0"}
}},
{"workspaceFolders", {{
{"uri", fileRootURI},
{"name", "workspace"}
}}}
};
initializeRequestId = requestId++;
json message = {
{"jsonrpc", "2.0"},
{"id", initializeRequestId},
{"method", "initialize"},
{"params", params}
};
sendMessage(message);
if (failedToStart) {
if (logCallback) {
App::displayToast(icu::UnicodeString::fromUTF8("Failed to start LSP - Ensure it's accessible via the command given."));
logCallback("Failed to start LSP - Ensure it's accessible via the command given.");
}
return;
}
// Wait for initialization (max 10 seconds)
std::unique_lock<std::mutex> lock(initializeMutex);
if (!initializeCondition.wait_for(lock, std::chrono::seconds(10), [this] { return initializeComplete.load(); })) {
failedToStart = true;
if (logCallback) {
App::displayToast(icu::UnicodeString::fromUTF8("LSP initialization timed out."));
logCallback("LSP initialization timed out.");
}
}
if (failedToStart) {
if (logCallback) {
App::displayToast(icu::UnicodeString::fromUTF8("Failed to start LSP - Ensure it's accessible via the command given."));
logCallback("Failed to start LSP - Ensure it's accessible via the command given.");
}
return;
}
json initializedMessage = {
{"jsonrpc", "2.0"},
{"method", "initialized"},
{"params", json::object()}
};
sendMessage(initializedMessage);
json params2 = {
{"settings", {
{"python", {
{"analysis", {
{"diagnosticMode", "openFilesOnly"},
{"typeCheckingMode", "basic"},
{"useLibraryCodeForTypes", false},
{"indexing", false},
{"inlayHints", {
{"variableTypes", false},
{"functionReturnTypes", false},
{"callArgumentNames", "off"}
}},
{"memory", {
{"keepLibraryAst", false}
}}
}}
}}
}}
};
json workspaceChanged = {
{"jsonrpc", "2.0"},
{"method", "workspace/didChangeConfiguration"},
{"params", params2}
};
sendMessage(workspaceChanged);
isInitialized = true;
}
void LanguageServerClient::shutdown()
{
if (failedToStart) {
return;
}
std::cout << serverProcess.bytesAvailable() << "\n";
serverProcess.close();
serverProcess.terminate();
if (!serverProcess.waitForFinished(500)) {
serverProcess.kill();
serverProcess.waitForFinished();
}
}
void LanguageServerClient::openDocument(const std::string &uri, const std::string &languageId, const std::string &content)
{
langID = languageId;
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI},
{"languageId", languageId},
{"version", documentVersion},
{"text", content}
};
json params = {
{"textDocument", textDocument}
};
json message = {
{"jsonrpc", "2.0"},
{"method", "textDocument/didOpen"},
{"params", params}
};
sendMessage(message);
}
void LanguageServerClient::closeDocument(const std::string &uri)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json params = {
{"textDocument", textDocument}
};
json message = {
{"jsonrpc", "2.0"},
{"method", "textDocument/didClose"},
{"params", params}
};
sendMessage(message);
}
void LanguageServerClient::updateDocument(const std::string &uri, const std::string &content)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI},
{"version", ++documentVersion}
};
json contentChanges = json::array();
contentChanges.push_back({{"text", content}});
json params = {
{"textDocument", textDocument},
{"contentChanges", contentChanges}
};
json message = {
{"jsonrpc", "2.0"},
{"method", "textDocument/didChange"},
{"params", params}
};
sendMessage(message);
}
void LanguageServerClient::applyDocumentEdit(const std::string &uri, const LineEditType &type, const std::string &newtext, int index)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI},
{"version", ++documentVersion} // Increment version for any change
};
json range;
std::string newText;
// NOTE: This implementation makes a critical assumption:
// For InsertLine and ChangeLine, the 'edit.newtext' contains ONLY the
// line content, not the newline character. We add '\n' to ensure
// it's treated as a full line.
// For DeleteLine and ChangeLine, we replace the *entire line range*,
// from the start of line 'index' to the start of line 'index + 1'.
switch (type)
{
case LineEditType::InsertLine:
// Insert *before* the specified line index.
// The range is zero-length at the start of the line.
range = {
{"start", {{"line", index}, {"character", 0}}},
{"end", {{"line", index}, {"character", 0}}}
};
newText = newtext + "\n";
break;
case LineEditType::DeleteLine:
// Delete the entire line, including its newline character.
// The range spans from the start of line 'index'
// to the start of line 'index + 1'.
range = {
{"start", {{"line", index}, {"character", 0}}},
{"end", {{"line", index + 1}, {"character", 0}}}
};
newText = ""; // Per your spec, newtext is "" for delete
break;
case LineEditType::ChangeLine:
// Replace the entire line. This is functionally a delete
// of the line range, followed by an insert.
// The range spans from the start of line 'index'
// to the start of line 'index + 1'.
range = {
{"start", {{"line", index}, {"character", 0}}},
{"end", {{"line", index + 1}, {"character", 0}}}
};
newText = newtext + "\n";
break;
}
// Create the incremental content change object
json contentChanges = json::array();
contentChanges.push_back({
{"range", range},
{"text", newText}
// Note: 'rangeLength' is deprecated in LSP and not needed.
});
json params = {
{"textDocument", textDocument},
{"contentChanges", contentChanges}
};
json message = {
{"jsonrpc", "2.0"},
{"method", "textDocument/didChange"},
{"params", params}
};
sendMessage(message);
}
void LanguageServerClient::documentSaved(const std::string& uri, const std::string& text)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI},
{"languageId", langID},
{"version", ++documentVersion}
};
json params = {
{"textDocument", textDocument},
{"text", text}
};
json message = {
{"jsonrpc", "2.0"},
{"method", "textDocument/didSave"},
{"params", params}
};
sendMessage(message);
}
int LanguageServerClient::requestCompletion(const std::string& uri, int line, int character)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json position = {
{"line", line},
{"character", character}
};
json context = {
{"triggerKind", 1}
};
json params = {
{"textDocument", textDocument},
{"position", position},
{"context", context}
};
json message = {
{"jsonrpc", "2.0"},
{"id", requestId},
{"method", "textDocument/completion"},
{"params", params}
};
requestsMap[requestId++] = "textDocument/completion";
sendMessage(message);
return requestId-1;
}
int LanguageServerClient::requestHover(const std::string& uri, int line, int character)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json position = {
{"line", line},
{"character", character}
};
json params = {
{"textDocument", textDocument},
{"position", position}
};
json message = {
{"jsonrpc", "2.0"},
{"id", requestId},
{"method", "textDocument/hover"},
{"params", params}
};
requestsMap[requestId++] = "textDocument/hover";
sendMessage(message);
return requestId-1;
}
int LanguageServerClient::requestActions(const std::string& uri, int line, int character, int line2, int character2)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json range = {
{"start", {{"line", line}, {"character", character}}},
{"end", {{"line", line2}, {"character", character2}}}
};
json context = {
{"diagnostics", filterDiagnostics(diagnostics, line, character, line2, character2)}
};
json params = {
{"textDocument", textDocument},
{"range", range},
{"context", context}
};
json message = {
{"jsonrpc", "2.0"},
{"id", requestId},
{"method", "textDocument/codeAction"},
{"params", params}
};
requestsMap[requestId++] = "textDocument/codeAction";
sendMessage(message);
return requestId-1;
}
int LanguageServerClient::requestRename(const std::string& uri, int line, int character, const std::string& newName)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json position = {
{"line", line},
{"character", character}
};
json params = {
{"textDocument", textDocument},
{"position", position},
{"newName", newName}
};
json message = {
{"jsonrpc", "2.0"},
{"id", requestId},
{"method", "textDocument/rename"},
{"params", params}
};
requestsMap[requestId++] = "textDocument/rename";
sendMessage(message);
return requestId-1;
}
json LanguageServerClient::filterDiagnostics(const json &diagnostics, int lineStart, int columnStart, int lineEnd, int columnEnd)
{
json filteredDiagnostics = json::array();
for (const auto &diagnostic : diagnostics) {
if (diagnostic.contains("range")) {
auto range = diagnostic["range"];
auto start = range["start"];
auto end = range["end"];
int diagStartLine = start["line"];
int diagStartColumn = start["character"];
int diagEndLine = end["line"];
int diagEndColumn = end["character"];
if ((diagEndLine >= lineStart && diagStartLine <= lineEnd) &&
(diagEndColumn >= columnStart && diagStartColumn <= columnEnd)) {
filteredDiagnostics.push_back(diagnostic);
}
}
}
return filteredDiagnostics;
}
int LanguageServerClient::requestGotoDefinition(const std::string& uri, int line, int character)
{
std::string fileURI = fromLocalFile(uri);
json textDocument = {
{"uri", fileURI}
};
json position = {
{"line", line},
{"character", character}
};
json params = {
{"textDocument", textDocument},
{"position", position}
};
json message = {
{"jsonrpc", "2.0"},
{"id", requestId},
{"method", "textDocument/definition"},
{"params", params}
};
requestsMap[requestId++] = "textDocument/definition";
sendMessage(message);
return requestId-1;
}
void LanguageServerClient::onServerReadyRead()
{
while (serverProcess.bytesAvailable() > 0 || currentExecution.find("\r\n") != std::string::npos || currentExecution.find("Content-Length") != std::string::npos) {
json response = readMessage();
if (response.is_null() || response.empty()) {
continue;
}
if (response.contains("method") && response["method"] == "window/logMessage") {
continue;
}
LspId id = std::nullptr_t{};
if (response.contains("id")) {
if (response["id"].is_number_integer()) {
id = response["id"].get<int>();
} else if (response["id"].is_string()) {
id = response["id"].get<std::string>();
}
}
auto LspId_to_int = [](const LspId& id) -> int {
if (std::holds_alternative<int>(id)) {
return std::get<int>(id);
}
return -1; // Or some other default/error value
};
int int_id = LspId_to_int(id);
if (int_id == shutdownId && (!response.contains("method") || response["method"].is_null())) {
alreadyDoneShutdownLoop = true;
shutdownComplete = true;
shutdownCondition.notify_all();
continue;
}
// Handle initialize response
if (!isInitialized && response.contains("result") && response["result"].contains("capabilities")) {
auto serverCapabilities = response["result"]["capabilities"];
triggerChars.clear();