Debian Codegraph @

modules/gdscript/language_server/gdscript_language_protocol.cpp

raw symbols SCIP
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 EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
152 }
153
154 String GDScriptLanguageProtocol::process_message(const String &p_text) {
155 String ret = process_string(p_text);
156 if (ret.is_empty()) {
157 return ret;
158 } else {
159 return format_output(ret);
160 }
161 }
162
163 String GDScriptLanguageProtocol::format_output(const String &p_text) {
164 String header = "Content-Length: ";
165 CharString charstr = p_text.utf8();
166 size_t len = charstr.length();
167 header += itos(len);
168 header += "\r\n\r\n";
169
170 return header + p_text;
171 }
172
173 void GDScriptLanguageProtocol::_bind_methods() {
174 ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
175 ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
176 ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
177 ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
178 ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
179 ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
180 ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
181 ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
182 ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
183 }
184
185 Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
186 LSP::InitializeResult ret;
187
188 {
189 // Warn if the workspace root does not match with the project that is currently open in Godot,
190 // since it might lead to unexpected behavior, like wrong warnings about duplicate class names.
191
192 String root;
193 Variant root_uri_var = p_params["rootUri"];
194 Variant root_var = p_params.get("rootPath", Variant());
195 if (root_uri_var.is_string()) {
196 root = get_workspace()->get_file_path(root_uri_var);
197 } else if (root_var.is_string()) {
198 root = root_var;
199 }
200
201 if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
202 LSP::ShowMessageParams params{
203 LSP::MessageType::Warning,
204 "The GDScript Language Server might not work correctly with other projects than the one opened in Godot."
205 };
206 notify_client("window/showMessage", params.to_json());
207 }
208 }
209
210 String root_uri = p_params["rootUri"];
211 String root = p_params.get("rootPath", "");
212 bool is_same_workspace;
213 #ifndef WINDOWS_ENABLED
214 is_same_workspace = root.to_lower() == workspace->root.to_lower();
215 #else
216 is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();
217 #endif
218
219 if (root_uri.length() && is_same_workspace) {
220 workspace->root_uri = root_uri;
221 } else {
222 String r_root = workspace->root;
223 r_root = r_root.lstrip("/");
224 workspace->root_uri = "file:///" + r_root;
225
226 Dictionary params;
227 params["path"] = workspace->root;
228 Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
229
230 ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
231 vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
232 Ref<LSPeer> peer = clients.get(latest_client_id);
233 if (peer.is_valid()) {
234 String msg = Variant(request).to_json_string();
235 msg = format_output(msg);
236 (*peer)->res_queue.push_back(msg.utf8());
237 }
238 }
239
240 if (!_initialized) {
241 workspace->initialize();
242 text_document->initialize();
243 _initialized = true;
244 }
245
246 return ret.to_json();
247 }
248
249 void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
250 LSP::GodotCapabilities capabilities;
251
252 DocTools *doc = EditorHelp::get_doc_data();
253 for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
254 LSP::GodotNativeClassInfo gdclass;
255 gdclass.name = E.value.name;
256 gdclass.class_doc = &(E.value);
257 if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
258 gdclass.class_info = ptr;
259 }
260 capabilities.native_classes.push_back(gdclass);
261 }
262
263 notify_client("gdscript/capabilities", capabilities.to_json());
264 }
265
266 void GDScriptLanguageProtocol::poll(int p_limit_usec) {
267 uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
268
269 if (server->is_connection_available()) {
270 on_client_connected();
271 }
272
273 HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
274 while (E != clients.end()) {
275 Ref<LSPeer> peer = E->value;
276 peer->connection->poll();
277 StreamPeerTCP::Status status = peer->connection->get_status();
278 if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
279 on_client_disconnected(E->key);
280 E = clients.begin();
281 continue;
282 } else {
283 Error err = OK;
284 while (peer->connection->get_available_bytes() > 0) {
285 latest_client_id = E->key;
286 err = peer->handle_data();
287 if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
288 break;
289 }
290 }
291
292 if (err != OK && err != ERR_BUSY) {
293 on_client_disconnected(E->key);
294 E = clients.begin();
295 continue;
296 }
297
298 err = peer->send_data();
299 if (err != OK && err != ERR_BUSY) {
300 on_client_disconnected(E->key);
301 E = clients.begin();
302 continue;
303 }
304 }
305 ++E;
306 }
307 }
308
309 Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
310 return server->listen(p_port, p_bind_ip);
311 }
312
313 void GDScriptLanguageProtocol::stop() {
314 for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
315 Ref<LSPeer> peer = clients.get(E.key);
316 peer->connection->disconnect_from_host();
317 }
318
319 server->stop();
320 }
321
322 void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
323 #ifdef TESTS_ENABLED
324 if (clients.is_empty()) {
325 return;
326 }
327 #endif
328 if (p_client_id == -1) {
329 ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
330 p_client_id = latest_client_id;
331 }
332 ERR_FAIL_COND(!clients.has(p_client_id));
333 Ref<LSPeer> peer = clients.get(p_client_id);
334 ERR_FAIL_COND(peer.is_null());
335
336 Dictionary message = make_notification(p_method, p_params);
337 String msg = Variant(message).to_json_string();
338 msg = format_output(msg);
339 peer->res_queue.push_back(msg.utf8());
340 }
341
342 void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
343 #ifdef TESTS_ENABLED
344 if (clients.is_empty()) {
345 return;
346 }
347 #endif
348 if (p_client_id == -1) {
349 ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
350 p_client_id = latest_client_id;
351 }
352 ERR_FAIL_COND(!clients.has(p_client_id));
353 Ref<LSPeer> peer = clients.get(p_client_id);
354 ERR_FAIL_COND(peer.is_null());
355
356 Dictionary message = make_request(p_method, p_params, next_server_id);
357 next_server_id++;
358 String msg = Variant(message).to_json_string();
359 msg = format_output(msg);
360 peer->res_queue.push_back(msg.utf8());
361 }
362
363 bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
364 return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
365 }
366
367 bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
368 return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
369 }
370
371 ExtendGDScriptParser *GDScriptLanguageProtocol::LSPeer::parse_script(const String &p_path) {
372 remove_cached_parser(p_path);
373
374 String content;
375 const LSP::TextDocumentItem *document = managed_files.getptr(p_path);
376 if (document == nullptr) {
377 if (!p_path.has_extension("gd")) {
378 return nullptr;
379 }
380 Error err;
381 content = FileAccess::get_file_as_string(p_path, &err);
382 if (err != OK) {
383 return nullptr;
384 }
385 } else {
386 if (document->languageId != LSP::LanguageId::GDSCRIPT) {
387 return nullptr;
388 }
389 content = document->text;
390 }
391
392 ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
393 parse_results[p_path] = parser;
394
395 parser->parse(content, p_path);
396
397 if (document != nullptr) {
398 GDScriptLanguageProtocol::get_singleton()->get_workspace()->publish_diagnostics(p_path);
399 } else {
400 // Don't keep cached for further requests since we can't invalidate the cache properly.
401 stale_parsers.insert(p_path);
402 }
403
404 return parser;
405 }
406
407 void GDScriptLanguageProtocol::LSPeer::clear_stale_parsers() {
408 while (!stale_parsers.is_empty()) {
409 remove_cached_parser(*stale_parsers.begin());
410 }
411 }
412
413 void GDScriptLanguageProtocol::LSPeer::remove_cached_parser(const String &p_path) {
414 HashMap<String, ExtendGDScriptParser *>::Iterator cached = parse_results.find(p_path);
415 if (cached) {
416 memdelete(cached->value);
417 parse_results.remove(cached);
418 }
419
420 stale_parsers.erase(p_path);
421 }
422
423 ExtendGDScriptParser *GDScriptLanguageProtocol::get_parse_result(const String &p_path) {
424 LSP_CLIENT_V(nullptr);
425
426 ExtendGDScriptParser **cached_parser = client->parse_results.getptr(p_path);
427 if (cached_parser == nullptr) {
428 return client->parse_script(p_path);
429 }
430 return *cached_parser;
431 }
432
433 void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {
434 LSP_CLIENT;
435
436 LSP::TextDocumentItem document;
437 document.load(p_params["textDocument"]);
438
439 // We keep track of non GDScript files that the client owns, but we are not interested in the content.
440 if (document.languageId != LSP::LanguageId::GDSCRIPT) {
441 document.text = "";
442 }
443
444 String path = get_workspace()->get_file_path(document.uri);
445
446 /// An open notification must not be sent more than once without a corresponding close notification send before.
447 ERR_FAIL_COND_MSG(client->managed_files.has(path), "LSP: Client is opening already opened file.");
448
449 client->managed_files[path] = document;
450 client->parse_script(path);
451 }
452
453 void GDScriptLanguageProtocol::lsp_did_change(const Dictionary &p_params) {
454 LSP_CLIENT;
455
456 LSP::TextDocumentIdentifier identifier;
457 identifier.load(p_params["textDocument"]);
458
459 String path = get_workspace()->get_file_path(identifier.uri);
460 LSP::TextDocumentItem *document = client->managed_files.getptr(path);
461
462 /// Before a client can change a text document it must claim ownership of its content using the textDocument/didOpen notification.
463 ERR_FAIL_COND_MSG(document == nullptr, "LSP: Client is changing file without opening it.");
464
465 if (document->languageId != LSP::LanguageId::GDSCRIPT) {
466 return;
467 }
468
469 Array contentChanges = p_params["contentChanges"];
470
471 if (contentChanges.is_empty()) {
472 return;
473 }
474
475 // We only support TextDocumentSyncKind::Full. So only the last full text is relevant.
476 LSP::TextDocumentContentChangeEvent event;
477 event.load(contentChanges.back());
478 document->text = event.text;
479
480 client->parse_script(path);
481 }
482
483 void GDScriptLanguageProtocol::lsp_did_close(const Dictionary &p_params) {
484 LSP_CLIENT;
485
486 LSP::TextDocumentIdentifier identifier;
487 identifier.load(p_params["textDocument"]);
488
489 String path = get_workspace()->get_file_path(identifier.uri);
490 bool was_opened = client->managed_files.erase(path);
491
492 client->remove_cached_parser(path);
493
494 /// A close notification requires a previous open notification to be sent.
495 ERR_FAIL_COND_MSG(!was_opened, "LSP: Client is closing file without opening it.");
496 }
497
498 void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
499 LSP_CLIENT;
500
501 String path = workspace->get_file_path(p_doc_pos.textDocument.uri);
502
503 const ExtendGDScriptParser *parser = get_parse_result(path);
504 if (!parser) {
505 return;
506 }
507
508 String symbol_identifier;
509 LSP::Range range;
510 symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
511
512 for (const KeyValue<StringName, ClassMembers> &E : workspace->native_members) {
513 if (const LSP::DocumentSymbol *const *symbol = E.value.getptr(symbol_identifier)) {
514 r_list.push_back(*symbol);
515 }
516 }
517
518 for (const KeyValue<String, ExtendGDScriptParser *> &E : client->parse_results) {
519 const ExtendGDScriptParser *scr = E.value;
520 const ClassMembers &members = scr->get_members();
521 if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
522 r_list.push_back(*symbol);
523 }
524
525 for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
526 const ClassMembers *inner_class = &F.value;
527 if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
528 r_list.push_back(*symbol);
529 }
530 }
531 }
532 }
533
534 GDScriptLanguageProtocol::LSPeer::~LSPeer() {
535 while (!parse_results.is_empty()) {
536 String path = parse_results.begin()->key;
537 remove_cached_parser(path);
538 }
539 stale_parsers.clear();
540 }
541
542 // clang-format off
543 #define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
544 #define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
545 #define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))
546 // clang-format on
547
548 GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
549 server.instantiate();
550 singleton = this;
551 workspace.instantiate();
552 text_document.instantiate();
553
554 SET_DOCUMENT_METHOD(didOpen);
555 SET_DOCUMENT_METHOD(didClose);
556 SET_DOCUMENT_METHOD(didChange);
557 SET_DOCUMENT_METHOD(willSaveWaitUntil);
558 SET_DOCUMENT_METHOD(didSave);
559
560 SET_DOCUMENT_METHOD(documentSymbol);
561 SET_DOCUMENT_METHOD(completion);
562 SET_DOCUMENT_METHOD(rename);
563 SET_DOCUMENT_METHOD(prepareRename);
564 SET_DOCUMENT_METHOD(references);
565 SET_DOCUMENT_METHOD(foldingRange);
566 SET_DOCUMENT_METHOD(codeLens);
567 SET_DOCUMENT_METHOD(documentLink);
568 SET_DOCUMENT_METHOD(colorPresentation);
569 SET_DOCUMENT_METHOD(hover);
570 SET_DOCUMENT_METHOD(definition);
571 SET_DOCUMENT_METHOD(declaration);
572 SET_DOCUMENT_METHOD(signatureHelp);
573
574 SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.
575
576 SET_COMPLETION_METHOD(resolve);
577
578 set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));
579 set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));
580
581 workspace->root = ProjectSettings::get_singleton()->get_resource_path();
582 }
583
584 #undef SET_DOCUMENT_METHOD
585 #undef SET_COMPLETION_METHOD
586 #undef SET_WORKSPACE_METHOD
587
588 #undef LSP_CLIENT
589 #undef LSP_CLIENT_V