Path: blob/master/modules/gdscript/language_server/gdscript_language_protocol.cpp
20847 views
/**************************************************************************/1/* gdscript_language_protocol.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdscript_language_protocol.h"3132#include "core/config/project_settings.h"33#include "editor/doc/doc_tools.h"34#include "editor/doc/editor_help.h"35#include "editor/editor_log.h"36#include "editor/editor_node.h"37#include "editor/settings/editor_settings.h"38#include "modules/gdscript/language_server/godot_lsp.h"3940#define LSP_CLIENT_V(m_ret_val) \41ERR_FAIL_COND_V(latest_client_id == LSP_NO_CLIENT, m_ret_val); \42ERR_FAIL_COND_V(!clients.has(latest_client_id), m_ret_val); \43Ref<LSPeer> client = clients.get(latest_client_id); \44ERR_FAIL_COND_V(!client.is_valid(), m_ret_val);4546#define LSP_CLIENT \47ERR_FAIL_COND(latest_client_id == LSP_NO_CLIENT); \48ERR_FAIL_COND(!clients.has(latest_client_id)); \49Ref<LSPeer> client = clients.get(latest_client_id); \50ERR_FAIL_COND(!client.is_valid());5152GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;5354Error GDScriptLanguageProtocol::LSPeer::handle_data() {55int read = 0;56// Read headers57if (!has_header) {58while (true) {59if (req_pos >= LSP_MAX_BUFFER_SIZE) {60req_pos = 0;61ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");62}63Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);64if (err != OK) {65return FAILED;66} else if (read != 1) { // Busy, wait until next poll67return ERR_BUSY;68}69char *r = (char *)req_buf;70int l = req_pos;7172// End of headers73if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {74r[l - 3] = '\0'; // Null terminate to read string75String header = String::utf8(r);76content_length = header.substr(16).to_int();77has_header = true;78req_pos = 0;79break;80}81req_pos++;82}83}84if (has_header) {85while (req_pos < content_length) {86if (req_pos >= LSP_MAX_BUFFER_SIZE) {87req_pos = 0;88has_header = false;89ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");90}91Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);92if (err != OK) {93return FAILED;94} else if (read != 1) {95return ERR_BUSY;96}97req_pos++;98}99100// Parse data101String msg = String::utf8((const char *)req_buf, req_pos);102103// Reset to read again104req_pos = 0;105has_header = false;106107// Response108String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);109clear_stale_parsers();110if (!output.is_empty()) {111res_queue.push_back(output.utf8());112}113}114return OK;115}116117Error GDScriptLanguageProtocol::LSPeer::send_data() {118int sent = 0;119while (!res_queue.is_empty()) {120CharString c_res = res_queue[0];121if (res_sent < c_res.size()) {122Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);123if (err != OK) {124return err;125}126res_sent += sent;127}128// Response sent129if (res_sent >= c_res.size() - 1) {130res_sent = 0;131res_queue.remove_at(0);132}133}134return OK;135}136137Error GDScriptLanguageProtocol::on_client_connected() {138Ref<StreamPeerTCP> tcp_peer = server->take_connection();139ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");140Ref<LSPeer> peer = memnew(LSPeer);141peer->connection = tcp_peer;142clients.insert(next_client_id, peer);143next_client_id++;144EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);145return OK;146}147148void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {149clients.erase(p_client_id);150if (clients.is_empty()) {151scene_cache.clear();152}153EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);154}155156String GDScriptLanguageProtocol::process_message(const String &p_text) {157String ret = process_string(p_text);158if (ret.is_empty()) {159return ret;160} else {161return format_output(ret);162}163}164165String GDScriptLanguageProtocol::format_output(const String &p_text) {166String header = "Content-Length: ";167CharString charstr = p_text.utf8();168size_t len = charstr.length();169header += itos(len);170header += "\r\n\r\n";171172return header + p_text;173}174175void GDScriptLanguageProtocol::_bind_methods() {176ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);177ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);178ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);179ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);180ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));181ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);182ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);183ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);184ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);185}186187Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {188LSP::InitializeResult ret;189190{191// Warn if the workspace root does not match with the project that is currently open in Godot,192// since it might lead to unexpected behavior, like wrong warnings about duplicate class names.193194String root;195Variant root_uri_var = p_params["rootUri"];196Variant root_var = p_params.get("rootPath", Variant());197if (root_uri_var.is_string()) {198root = get_workspace()->get_file_path(root_uri_var);199} else if (root_var.is_string()) {200root = root_var;201}202203if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {204LSP::ShowMessageParams params{205LSP::MessageType::Warning,206"The GDScript Language Server might not work correctly with other projects than the one opened in Godot."207};208notify_client("window/showMessage", params.to_json());209}210}211212String root_uri = p_params["rootUri"];213String root = p_params.get("rootPath", "");214bool is_same_workspace;215#ifndef WINDOWS_ENABLED216is_same_workspace = root.to_lower() == workspace->root.to_lower();217#else218is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();219#endif220221if (root_uri.length() && is_same_workspace) {222workspace->root_uri = root_uri;223} else {224String r_root = workspace->root;225r_root = r_root.lstrip("/");226workspace->root_uri = "file:///" + r_root;227228Dictionary params;229params["path"] = workspace->root;230Dictionary request = make_notification("gdscript_client/changeWorkspace", params);231232ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),233vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));234Ref<LSPeer> peer = clients.get(latest_client_id);235if (peer.is_valid()) {236String msg = Variant(request).to_json_string();237msg = format_output(msg);238(*peer)->res_queue.push_back(msg.utf8());239}240}241242if (!_initialized) {243workspace->initialize();244_initialized = true;245}246247return ret.to_json();248}249250void GDScriptLanguageProtocol::initialized(const Variant &p_params) {251LSP::GodotCapabilities capabilities;252253DocTools *doc = EditorHelp::get_doc_data();254for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {255LSP::GodotNativeClassInfo gdclass;256gdclass.name = E.value.name;257gdclass.class_doc = &(E.value);258if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {259gdclass.class_info = ptr;260}261capabilities.native_classes.push_back(gdclass);262}263264notify_client("gdscript/capabilities", capabilities.to_json());265}266267void GDScriptLanguageProtocol::poll(int p_limit_usec) {268uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;269270if (server->is_connection_available()) {271on_client_connected();272}273274scene_cache.poll();275276HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();277while (E != clients.end()) {278Ref<LSPeer> peer = E->value;279peer->connection->poll();280StreamPeerTCP::Status status = peer->connection->get_status();281if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {282on_client_disconnected(E->key);283E = clients.begin();284continue;285} else {286Error err = OK;287while (peer->connection->get_available_bytes() > 0) {288latest_client_id = E->key;289err = peer->handle_data();290if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {291break;292}293}294295if (err != OK && err != ERR_BUSY) {296on_client_disconnected(E->key);297E = clients.begin();298continue;299}300301err = peer->send_data();302if (err != OK && err != ERR_BUSY) {303on_client_disconnected(E->key);304E = clients.begin();305continue;306}307}308++E;309}310}311312Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {313return server->listen(p_port, p_bind_ip);314}315316void GDScriptLanguageProtocol::stop() {317for (const KeyValue<int, Ref<LSPeer>> &E : clients) {318Ref<LSPeer> peer = clients.get(E.key);319peer->connection->disconnect_from_host();320}321322scene_cache.clear();323server->stop();324}325326void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {327#ifdef TESTS_ENABLED328if (clients.is_empty()) {329return;330}331#endif332if (p_client_id == -1) {333ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");334p_client_id = latest_client_id;335}336ERR_FAIL_COND(!clients.has(p_client_id));337Ref<LSPeer> peer = clients.get(p_client_id);338ERR_FAIL_COND(peer.is_null());339340Dictionary message = make_notification(p_method, p_params);341String msg = Variant(message).to_json_string();342msg = format_output(msg);343peer->res_queue.push_back(msg.utf8());344}345346void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {347#ifdef TESTS_ENABLED348if (clients.is_empty()) {349return;350}351#endif352if (p_client_id == -1) {353ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");354p_client_id = latest_client_id;355}356ERR_FAIL_COND(!clients.has(p_client_id));357Ref<LSPeer> peer = clients.get(p_client_id);358ERR_FAIL_COND(peer.is_null());359360Dictionary message = make_request(p_method, p_params, next_server_id);361next_server_id++;362String msg = Variant(message).to_json_string();363msg = format_output(msg);364peer->res_queue.push_back(msg.utf8());365}366367bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {368return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));369}370371bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {372return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));373}374375ExtendGDScriptParser *GDScriptLanguageProtocol::LSPeer::parse_script(const String &p_path) {376remove_cached_parser(p_path);377378String content;379const LSP::TextDocumentItem *document = managed_files.getptr(p_path);380if (document == nullptr) {381if (!p_path.has_extension("gd")) {382return nullptr;383}384Error err;385content = FileAccess::get_file_as_string(p_path, &err);386if (err != OK) {387return nullptr;388}389} else {390if (document->languageId != LSP::LanguageId::GDSCRIPT) {391return nullptr;392}393content = document->text;394}395396ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);397parse_results[p_path] = parser;398399parser->parse(content, p_path);400401if (document != nullptr) {402GDScriptLanguageProtocol::get_singleton()->get_workspace()->publish_diagnostics(p_path);403} else {404// Don't keep cached for further requests since we can't invalidate the cache properly.405stale_parsers.insert(p_path);406}407408return parser;409}410411void GDScriptLanguageProtocol::LSPeer::clear_stale_parsers() {412while (!stale_parsers.is_empty()) {413remove_cached_parser(*stale_parsers.begin());414}415}416417void GDScriptLanguageProtocol::LSPeer::remove_cached_parser(const String &p_path) {418HashMap<String, ExtendGDScriptParser *>::Iterator cached = parse_results.find(p_path);419if (cached) {420memdelete(cached->value);421parse_results.remove(cached);422}423424stale_parsers.erase(p_path);425}426427ExtendGDScriptParser *GDScriptLanguageProtocol::get_parse_result(const String &p_path) {428LSP_CLIENT_V(nullptr);429430ExtendGDScriptParser **cached_parser = client->parse_results.getptr(p_path);431if (cached_parser == nullptr) {432return client->parse_script(p_path);433}434return *cached_parser;435}436437void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {438LSP_CLIENT;439440LSP::TextDocumentItem document;441document.load(p_params["textDocument"]);442443// We keep track of non GDScript files that the client owns, but we are not interested in the content.444if (document.languageId != LSP::LanguageId::GDSCRIPT) {445document.text = "";446}447448String path = get_workspace()->get_file_path(document.uri);449450/// An open notification must not be sent more than once without a corresponding close notification send before.451ERR_FAIL_COND_MSG(client->managed_files.has(path), "LSP: Client is opening already opened file.");452453client->managed_files[path] = document;454client->parse_script(path);455456scene_cache.request_load(path);457}458459void GDScriptLanguageProtocol::lsp_did_change(const Dictionary &p_params) {460LSP_CLIENT;461462LSP::TextDocumentIdentifier identifier;463identifier.load(p_params["textDocument"]);464465String path = get_workspace()->get_file_path(identifier.uri);466LSP::TextDocumentItem *document = client->managed_files.getptr(path);467468/// Before a client can change a text document it must claim ownership of its content using the textDocument/didOpen notification.469ERR_FAIL_COND_MSG(document == nullptr, "LSP: Client is changing file without opening it.");470471if (document->languageId != LSP::LanguageId::GDSCRIPT) {472return;473}474475Array contentChanges = p_params["contentChanges"];476477if (contentChanges.is_empty()) {478return;479}480481// We only support TextDocumentSyncKind::Full. So only the last full text is relevant.482LSP::TextDocumentContentChangeEvent event;483event.load(contentChanges.back());484document->text = event.text;485486client->parse_script(path);487}488489void GDScriptLanguageProtocol::lsp_did_close(const Dictionary &p_params) {490LSP_CLIENT;491492LSP::TextDocumentIdentifier identifier;493identifier.load(p_params["textDocument"]);494495String path = get_workspace()->get_file_path(identifier.uri);496bool was_opened = client->managed_files.erase(path);497498client->remove_cached_parser(path);499500/// A close notification requires a previous open notification to be sent.501ERR_FAIL_COND_MSG(!was_opened, "LSP: Client is closing file without opening it.");502503scene_cache.unload(path);504}505506void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {507LSP_CLIENT;508509String path = workspace->get_file_path(p_doc_pos.textDocument.uri);510511const ExtendGDScriptParser *parser = get_parse_result(path);512if (!parser) {513return;514}515516String symbol_identifier;517LSP::Range range;518symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);519520for (const KeyValue<StringName, ClassMembers> &E : workspace->native_members) {521if (const LSP::DocumentSymbol *const *symbol = E.value.getptr(symbol_identifier)) {522r_list.push_back(*symbol);523}524}525526for (const KeyValue<String, ExtendGDScriptParser *> &E : client->parse_results) {527const ExtendGDScriptParser *scr = E.value;528const ClassMembers &members = scr->get_members();529if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {530r_list.push_back(*symbol);531}532533for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {534const ClassMembers *inner_class = &F.value;535if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {536r_list.push_back(*symbol);537}538}539}540}541542GDScriptLanguageProtocol::LSPeer::~LSPeer() {543while (!parse_results.is_empty()) {544String path = parse_results.begin()->key;545remove_cached_parser(path);546}547stale_parsers.clear();548}549550// clang-format off551#define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))552#define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))553#define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))554// clang-format on555556GDScriptLanguageProtocol::GDScriptLanguageProtocol() {557server.instantiate();558singleton = this;559workspace.instantiate();560text_document.instantiate();561562SET_DOCUMENT_METHOD(didOpen);563SET_DOCUMENT_METHOD(didClose);564SET_DOCUMENT_METHOD(didChange);565SET_DOCUMENT_METHOD(willSaveWaitUntil);566SET_DOCUMENT_METHOD(didSave);567568SET_DOCUMENT_METHOD(documentSymbol);569SET_DOCUMENT_METHOD(documentHighlight);570SET_DOCUMENT_METHOD(completion);571SET_DOCUMENT_METHOD(rename);572SET_DOCUMENT_METHOD(prepareRename);573SET_DOCUMENT_METHOD(references);574SET_DOCUMENT_METHOD(foldingRange);575SET_DOCUMENT_METHOD(codeLens);576SET_DOCUMENT_METHOD(documentLink);577SET_DOCUMENT_METHOD(colorPresentation);578SET_DOCUMENT_METHOD(hover);579SET_DOCUMENT_METHOD(definition);580SET_DOCUMENT_METHOD(declaration);581SET_DOCUMENT_METHOD(signatureHelp);582583SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.584585SET_COMPLETION_METHOD(resolve);586587set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));588set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));589590workspace->root = ProjectSettings::get_singleton()->get_resource_path();591}592593#undef SET_DOCUMENT_METHOD594#undef SET_COMPLETION_METHOD595#undef SET_WORKSPACE_METHOD596597#undef LSP_CLIENT598#undef LSP_CLIENT_V599600601