Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/language_server/gdscript_language_protocol.cpp
20847 views
1
/**************************************************************************/
2
/* gdscript_language_protocol.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "gdscript_language_protocol.h"
32
33
#include "core/config/project_settings.h"
34
#include "editor/doc/doc_tools.h"
35
#include "editor/doc/editor_help.h"
36
#include "editor/editor_log.h"
37
#include "editor/editor_node.h"
38
#include "editor/settings/editor_settings.h"
39
#include "modules/gdscript/language_server/godot_lsp.h"
40
41
#define LSP_CLIENT_V(m_ret_val) \
42
ERR_FAIL_COND_V(latest_client_id == LSP_NO_CLIENT, m_ret_val); \
43
ERR_FAIL_COND_V(!clients.has(latest_client_id), m_ret_val); \
44
Ref<LSPeer> client = clients.get(latest_client_id); \
45
ERR_FAIL_COND_V(!client.is_valid(), m_ret_val);
46
47
#define LSP_CLIENT \
48
ERR_FAIL_COND(latest_client_id == LSP_NO_CLIENT); \
49
ERR_FAIL_COND(!clients.has(latest_client_id)); \
50
Ref<LSPeer> client = clients.get(latest_client_id); \
51
ERR_FAIL_COND(!client.is_valid());
52
53
GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;
54
55
Error GDScriptLanguageProtocol::LSPeer::handle_data() {
56
int read = 0;
57
// Read headers
58
if (!has_header) {
59
while (true) {
60
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
61
req_pos = 0;
62
ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");
63
}
64
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
65
if (err != OK) {
66
return FAILED;
67
} else if (read != 1) { // Busy, wait until next poll
68
return ERR_BUSY;
69
}
70
char *r = (char *)req_buf;
71
int l = req_pos;
72
73
// End of headers
74
if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
75
r[l - 3] = '\0'; // Null terminate to read string
76
String header = String::utf8(r);
77
content_length = header.substr(16).to_int();
78
has_header = true;
79
req_pos = 0;
80
break;
81
}
82
req_pos++;
83
}
84
}
85
if (has_header) {
86
while (req_pos < content_length) {
87
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
88
req_pos = 0;
89
has_header = false;
90
ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
91
}
92
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
93
if (err != OK) {
94
return FAILED;
95
} else if (read != 1) {
96
return ERR_BUSY;
97
}
98
req_pos++;
99
}
100
101
// Parse data
102
String msg = String::utf8((const char *)req_buf, req_pos);
103
104
// Reset to read again
105
req_pos = 0;
106
has_header = false;
107
108
// Response
109
String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
110
clear_stale_parsers();
111
if (!output.is_empty()) {
112
res_queue.push_back(output.utf8());
113
}
114
}
115
return OK;
116
}
117
118
Error GDScriptLanguageProtocol::LSPeer::send_data() {
119
int sent = 0;
120
while (!res_queue.is_empty()) {
121
CharString c_res = res_queue[0];
122
if (res_sent < c_res.size()) {
123
Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
124
if (err != OK) {
125
return err;
126
}
127
res_sent += sent;
128
}
129
// Response sent
130
if (res_sent >= c_res.size() - 1) {
131
res_sent = 0;
132
res_queue.remove_at(0);
133
}
134
}
135
return OK;
136
}
137
138
Error GDScriptLanguageProtocol::on_client_connected() {
139
Ref<StreamPeerTCP> tcp_peer = server->take_connection();
140
ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
141
Ref<LSPeer> peer = memnew(LSPeer);
142
peer->connection = tcp_peer;
143
clients.insert(next_client_id, peer);
144
next_client_id++;
145
EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
146
return OK;
147
}
148
149
void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
150
clients.erase(p_client_id);
151
if (clients.is_empty()) {
152
scene_cache.clear();
153
}
154
EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
155
}
156
157
String GDScriptLanguageProtocol::process_message(const String &p_text) {
158
String ret = process_string(p_text);
159
if (ret.is_empty()) {
160
return ret;
161
} else {
162
return format_output(ret);
163
}
164
}
165
166
String GDScriptLanguageProtocol::format_output(const String &p_text) {
167
String header = "Content-Length: ";
168
CharString charstr = p_text.utf8();
169
size_t len = charstr.length();
170
header += itos(len);
171
header += "\r\n\r\n";
172
173
return header + p_text;
174
}
175
176
void GDScriptLanguageProtocol::_bind_methods() {
177
ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
178
ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
179
ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
180
ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
181
ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
182
ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
183
ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
184
ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
185
ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
186
}
187
188
Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
189
LSP::InitializeResult ret;
190
191
{
192
// Warn if the workspace root does not match with the project that is currently open in Godot,
193
// since it might lead to unexpected behavior, like wrong warnings about duplicate class names.
194
195
String root;
196
Variant root_uri_var = p_params["rootUri"];
197
Variant root_var = p_params.get("rootPath", Variant());
198
if (root_uri_var.is_string()) {
199
root = get_workspace()->get_file_path(root_uri_var);
200
} else if (root_var.is_string()) {
201
root = root_var;
202
}
203
204
if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
205
LSP::ShowMessageParams params{
206
LSP::MessageType::Warning,
207
"The GDScript Language Server might not work correctly with other projects than the one opened in Godot."
208
};
209
notify_client("window/showMessage", params.to_json());
210
}
211
}
212
213
String root_uri = p_params["rootUri"];
214
String root = p_params.get("rootPath", "");
215
bool is_same_workspace;
216
#ifndef WINDOWS_ENABLED
217
is_same_workspace = root.to_lower() == workspace->root.to_lower();
218
#else
219
is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();
220
#endif
221
222
if (root_uri.length() && is_same_workspace) {
223
workspace->root_uri = root_uri;
224
} else {
225
String r_root = workspace->root;
226
r_root = r_root.lstrip("/");
227
workspace->root_uri = "file:///" + r_root;
228
229
Dictionary params;
230
params["path"] = workspace->root;
231
Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
232
233
ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
234
vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
235
Ref<LSPeer> peer = clients.get(latest_client_id);
236
if (peer.is_valid()) {
237
String msg = Variant(request).to_json_string();
238
msg = format_output(msg);
239
(*peer)->res_queue.push_back(msg.utf8());
240
}
241
}
242
243
if (!_initialized) {
244
workspace->initialize();
245
_initialized = true;
246
}
247
248
return ret.to_json();
249
}
250
251
void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
252
LSP::GodotCapabilities capabilities;
253
254
DocTools *doc = EditorHelp::get_doc_data();
255
for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
256
LSP::GodotNativeClassInfo gdclass;
257
gdclass.name = E.value.name;
258
gdclass.class_doc = &(E.value);
259
if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
260
gdclass.class_info = ptr;
261
}
262
capabilities.native_classes.push_back(gdclass);
263
}
264
265
notify_client("gdscript/capabilities", capabilities.to_json());
266
}
267
268
void GDScriptLanguageProtocol::poll(int p_limit_usec) {
269
uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
270
271
if (server->is_connection_available()) {
272
on_client_connected();
273
}
274
275
scene_cache.poll();
276
277
HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
278
while (E != clients.end()) {
279
Ref<LSPeer> peer = E->value;
280
peer->connection->poll();
281
StreamPeerTCP::Status status = peer->connection->get_status();
282
if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
283
on_client_disconnected(E->key);
284
E = clients.begin();
285
continue;
286
} else {
287
Error err = OK;
288
while (peer->connection->get_available_bytes() > 0) {
289
latest_client_id = E->key;
290
err = peer->handle_data();
291
if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
292
break;
293
}
294
}
295
296
if (err != OK && err != ERR_BUSY) {
297
on_client_disconnected(E->key);
298
E = clients.begin();
299
continue;
300
}
301
302
err = peer->send_data();
303
if (err != OK && err != ERR_BUSY) {
304
on_client_disconnected(E->key);
305
E = clients.begin();
306
continue;
307
}
308
}
309
++E;
310
}
311
}
312
313
Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
314
return server->listen(p_port, p_bind_ip);
315
}
316
317
void GDScriptLanguageProtocol::stop() {
318
for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
319
Ref<LSPeer> peer = clients.get(E.key);
320
peer->connection->disconnect_from_host();
321
}
322
323
scene_cache.clear();
324
server->stop();
325
}
326
327
void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
328
#ifdef TESTS_ENABLED
329
if (clients.is_empty()) {
330
return;
331
}
332
#endif
333
if (p_client_id == -1) {
334
ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
335
p_client_id = latest_client_id;
336
}
337
ERR_FAIL_COND(!clients.has(p_client_id));
338
Ref<LSPeer> peer = clients.get(p_client_id);
339
ERR_FAIL_COND(peer.is_null());
340
341
Dictionary message = make_notification(p_method, p_params);
342
String msg = Variant(message).to_json_string();
343
msg = format_output(msg);
344
peer->res_queue.push_back(msg.utf8());
345
}
346
347
void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
348
#ifdef TESTS_ENABLED
349
if (clients.is_empty()) {
350
return;
351
}
352
#endif
353
if (p_client_id == -1) {
354
ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
355
p_client_id = latest_client_id;
356
}
357
ERR_FAIL_COND(!clients.has(p_client_id));
358
Ref<LSPeer> peer = clients.get(p_client_id);
359
ERR_FAIL_COND(peer.is_null());
360
361
Dictionary message = make_request(p_method, p_params, next_server_id);
362
next_server_id++;
363
String msg = Variant(message).to_json_string();
364
msg = format_output(msg);
365
peer->res_queue.push_back(msg.utf8());
366
}
367
368
bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
369
return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
370
}
371
372
bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
373
return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
374
}
375
376
ExtendGDScriptParser *GDScriptLanguageProtocol::LSPeer::parse_script(const String &p_path) {
377
remove_cached_parser(p_path);
378
379
String content;
380
const LSP::TextDocumentItem *document = managed_files.getptr(p_path);
381
if (document == nullptr) {
382
if (!p_path.has_extension("gd")) {
383
return nullptr;
384
}
385
Error err;
386
content = FileAccess::get_file_as_string(p_path, &err);
387
if (err != OK) {
388
return nullptr;
389
}
390
} else {
391
if (document->languageId != LSP::LanguageId::GDSCRIPT) {
392
return nullptr;
393
}
394
content = document->text;
395
}
396
397
ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
398
parse_results[p_path] = parser;
399
400
parser->parse(content, p_path);
401
402
if (document != nullptr) {
403
GDScriptLanguageProtocol::get_singleton()->get_workspace()->publish_diagnostics(p_path);
404
} else {
405
// Don't keep cached for further requests since we can't invalidate the cache properly.
406
stale_parsers.insert(p_path);
407
}
408
409
return parser;
410
}
411
412
void GDScriptLanguageProtocol::LSPeer::clear_stale_parsers() {
413
while (!stale_parsers.is_empty()) {
414
remove_cached_parser(*stale_parsers.begin());
415
}
416
}
417
418
void GDScriptLanguageProtocol::LSPeer::remove_cached_parser(const String &p_path) {
419
HashMap<String, ExtendGDScriptParser *>::Iterator cached = parse_results.find(p_path);
420
if (cached) {
421
memdelete(cached->value);
422
parse_results.remove(cached);
423
}
424
425
stale_parsers.erase(p_path);
426
}
427
428
ExtendGDScriptParser *GDScriptLanguageProtocol::get_parse_result(const String &p_path) {
429
LSP_CLIENT_V(nullptr);
430
431
ExtendGDScriptParser **cached_parser = client->parse_results.getptr(p_path);
432
if (cached_parser == nullptr) {
433
return client->parse_script(p_path);
434
}
435
return *cached_parser;
436
}
437
438
void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {
439
LSP_CLIENT;
440
441
LSP::TextDocumentItem document;
442
document.load(p_params["textDocument"]);
443
444
// We keep track of non GDScript files that the client owns, but we are not interested in the content.
445
if (document.languageId != LSP::LanguageId::GDSCRIPT) {
446
document.text = "";
447
}
448
449
String path = get_workspace()->get_file_path(document.uri);
450
451
/// An open notification must not be sent more than once without a corresponding close notification send before.
452
ERR_FAIL_COND_MSG(client->managed_files.has(path), "LSP: Client is opening already opened file.");
453
454
client->managed_files[path] = document;
455
client->parse_script(path);
456
457
scene_cache.request_load(path);
458
}
459
460
void GDScriptLanguageProtocol::lsp_did_change(const Dictionary &p_params) {
461
LSP_CLIENT;
462
463
LSP::TextDocumentIdentifier identifier;
464
identifier.load(p_params["textDocument"]);
465
466
String path = get_workspace()->get_file_path(identifier.uri);
467
LSP::TextDocumentItem *document = client->managed_files.getptr(path);
468
469
/// Before a client can change a text document it must claim ownership of its content using the textDocument/didOpen notification.
470
ERR_FAIL_COND_MSG(document == nullptr, "LSP: Client is changing file without opening it.");
471
472
if (document->languageId != LSP::LanguageId::GDSCRIPT) {
473
return;
474
}
475
476
Array contentChanges = p_params["contentChanges"];
477
478
if (contentChanges.is_empty()) {
479
return;
480
}
481
482
// We only support TextDocumentSyncKind::Full. So only the last full text is relevant.
483
LSP::TextDocumentContentChangeEvent event;
484
event.load(contentChanges.back());
485
document->text = event.text;
486
487
client->parse_script(path);
488
}
489
490
void GDScriptLanguageProtocol::lsp_did_close(const Dictionary &p_params) {
491
LSP_CLIENT;
492
493
LSP::TextDocumentIdentifier identifier;
494
identifier.load(p_params["textDocument"]);
495
496
String path = get_workspace()->get_file_path(identifier.uri);
497
bool was_opened = client->managed_files.erase(path);
498
499
client->remove_cached_parser(path);
500
501
/// A close notification requires a previous open notification to be sent.
502
ERR_FAIL_COND_MSG(!was_opened, "LSP: Client is closing file without opening it.");
503
504
scene_cache.unload(path);
505
}
506
507
void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
508
LSP_CLIENT;
509
510
String path = workspace->get_file_path(p_doc_pos.textDocument.uri);
511
512
const ExtendGDScriptParser *parser = get_parse_result(path);
513
if (!parser) {
514
return;
515
}
516
517
String symbol_identifier;
518
LSP::Range range;
519
symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
520
521
for (const KeyValue<StringName, ClassMembers> &E : workspace->native_members) {
522
if (const LSP::DocumentSymbol *const *symbol = E.value.getptr(symbol_identifier)) {
523
r_list.push_back(*symbol);
524
}
525
}
526
527
for (const KeyValue<String, ExtendGDScriptParser *> &E : client->parse_results) {
528
const ExtendGDScriptParser *scr = E.value;
529
const ClassMembers &members = scr->get_members();
530
if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
531
r_list.push_back(*symbol);
532
}
533
534
for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
535
const ClassMembers *inner_class = &F.value;
536
if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
537
r_list.push_back(*symbol);
538
}
539
}
540
}
541
}
542
543
GDScriptLanguageProtocol::LSPeer::~LSPeer() {
544
while (!parse_results.is_empty()) {
545
String path = parse_results.begin()->key;
546
remove_cached_parser(path);
547
}
548
stale_parsers.clear();
549
}
550
551
// clang-format off
552
#define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
553
#define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
554
#define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))
555
// clang-format on
556
557
GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
558
server.instantiate();
559
singleton = this;
560
workspace.instantiate();
561
text_document.instantiate();
562
563
SET_DOCUMENT_METHOD(didOpen);
564
SET_DOCUMENT_METHOD(didClose);
565
SET_DOCUMENT_METHOD(didChange);
566
SET_DOCUMENT_METHOD(willSaveWaitUntil);
567
SET_DOCUMENT_METHOD(didSave);
568
569
SET_DOCUMENT_METHOD(documentSymbol);
570
SET_DOCUMENT_METHOD(documentHighlight);
571
SET_DOCUMENT_METHOD(completion);
572
SET_DOCUMENT_METHOD(rename);
573
SET_DOCUMENT_METHOD(prepareRename);
574
SET_DOCUMENT_METHOD(references);
575
SET_DOCUMENT_METHOD(foldingRange);
576
SET_DOCUMENT_METHOD(codeLens);
577
SET_DOCUMENT_METHOD(documentLink);
578
SET_DOCUMENT_METHOD(colorPresentation);
579
SET_DOCUMENT_METHOD(hover);
580
SET_DOCUMENT_METHOD(definition);
581
SET_DOCUMENT_METHOD(declaration);
582
SET_DOCUMENT_METHOD(signatureHelp);
583
584
SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.
585
586
SET_COMPLETION_METHOD(resolve);
587
588
set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));
589
set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));
590
591
workspace->root = ProjectSettings::get_singleton()->get_resource_path();
592
}
593
594
#undef SET_DOCUMENT_METHOD
595
#undef SET_COMPLETION_METHOD
596
#undef SET_WORKSPACE_METHOD
597
598
#undef LSP_CLIENT
599
#undef LSP_CLIENT_V
600
601