feat: updated engine

This commit is contained in:
Sara Gerretsen 2026-07-10 17:04:34 +02:00
parent cbe99774ff
commit f4cf6b3999
6607 changed files with 910135 additions and 430025 deletions

View file

@ -32,97 +32,30 @@
#include "../gdscript.h"
#include "../gdscript_analyzer.h"
#include "editor/settings/editor_settings.h"
#include "gdscript_language_protocol.h"
#include "gdscript_workspace.h"
int get_indent_size() {
if (EditorSettings::get_singleton()) {
return EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
} else {
return 4;
}
}
LSP::Position GodotPosition::to_lsp(const Vector<String> &p_lines) const {
LSP::Position GodotPosition::to_lsp() const {
LSP::Position res;
// Special case: `line = 0` -> root class (range covers everything).
if (line <= 0) {
return res;
}
// Special case: `line = p_lines.size() + 1` -> root class (range covers everything).
if (line >= p_lines.size() + 1) {
res.line = p_lines.size();
return res;
}
res.line = line - 1;
// Special case: `column = 0` -> Starts at beginning of line.
if (column <= 0) {
return res;
}
// Note: character outside of `pos_line.length()-1` is valid.
res.character = column - 1;
String pos_line = p_lines[res.line];
if (pos_line.contains_char('\t')) {
int tab_size = get_indent_size();
int in_col = 1;
int res_char = 0;
while (res_char < pos_line.size() && in_col < column) {
if (pos_line[res_char] == '\t') {
in_col += tab_size;
res_char++;
} else {
in_col++;
res_char++;
}
}
res.character = res_char;
}
return res;
}
GodotPosition GodotPosition::from_lsp(const LSP::Position p_pos, const Vector<String> &p_lines) {
GodotPosition res(p_pos.line + 1, p_pos.character + 1);
// Line outside of actual text is valid (-> pos/cursor at end of text).
if (res.line > p_lines.size()) {
return res;
}
String line = p_lines[p_pos.line];
int tabs_before_char = 0;
for (int i = 0; i < p_pos.character && i < line.length(); i++) {
if (line[i] == '\t') {
tabs_before_char++;
}
}
if (tabs_before_char > 0) {
int tab_size = get_indent_size();
res.column += tabs_before_char * (tab_size - 1);
}
return res;
GodotPosition GodotPosition::from_lsp(const LSP::Position p_pos) {
return GodotPosition(p_pos.line + 1, p_pos.character + 1);
}
LSP::Range GodotRange::to_lsp(const Vector<String> &p_lines) const {
LSP::Range GodotRange::to_lsp() const {
LSP::Range res;
res.start = start.to_lsp(p_lines);
res.end = end.to_lsp(p_lines);
res.start = start.to_lsp();
res.end = end.to_lsp();
return res;
}
GodotRange GodotRange::from_lsp(const LSP::Range &p_range, const Vector<String> &p_lines) {
GodotPosition start = GodotPosition::from_lsp(p_range.start, p_lines);
GodotPosition end = GodotPosition::from_lsp(p_range.end, p_lines);
GodotRange GodotRange::from_lsp(const LSP::Range &p_range) {
GodotPosition start = GodotPosition::from_lsp(p_range.start);
GodotPosition end = GodotPosition::from_lsp(p_range.end);
return GodotRange(start, end);
}
@ -135,18 +68,12 @@ void ExtendGDScriptParser::update_diagnostics() {
diagnostic.severity = LSP::DiagnosticSeverity::Error;
diagnostic.message = error.message;
diagnostic.source = "gdscript";
diagnostic.code = -1;
LSP::Range range;
LSP::Position pos;
const PackedStringArray line_array = get_lines();
int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, line_array.size() - 1);
const String &line_text = line_array[line];
pos.line = line;
pos.character = line_text.length() - line_text.strip_edges(true, false).length();
range.start = pos;
range.end = range.start;
range.end.character = line_text.strip_edges(false).length();
diagnostic.range = range;
GodotRange godot_range(
GodotPosition(error.start_line, error.start_column),
GodotPosition(error.end_line, error.end_column));
diagnostic.range = godot_range.to_lsp();
diagnostics.push_back(diagnostic);
}
@ -156,17 +83,12 @@ void ExtendGDScriptParser::update_diagnostics() {
diagnostic.severity = LSP::DiagnosticSeverity::Warning;
diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message();
diagnostic.source = "gdscript";
diagnostic.code = warning.code;
LSP::Range range;
LSP::Position pos;
int line = LINE_NUMBER_TO_INDEX(warning.start_line);
const String &line_text = get_lines()[line];
pos.line = line;
pos.character = line_text.length() - line_text.strip_edges(true, false).length();
range.start = pos;
range.end = pos;
range.end.character = line_text.strip_edges(false).length();
diagnostic.range = range;
GodotRange godot_range(
GodotPosition(warning.start_line, warning.start_column),
GodotPosition(warning.end_line, warning.end_column));
diagnostic.range = godot_range.to_lsp();
diagnostics.push_back(diagnostic);
}
}
@ -217,7 +139,7 @@ void ExtendGDScriptParser::update_document_links(const String &p_code) {
String value = const_val;
LSP::DocumentLink link;
link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(scr_path);
link.range = GodotRange(GodotPosition(token.start_line, token.start_column), GodotPosition(token.end_line, token.end_column)).to_lsp(lines);
link.range = GodotRange(GodotPosition(token.start_line, token.start_column), GodotPosition(token.end_line, token.end_column)).to_lsp();
document_links.push_back(link);
}
}
@ -228,7 +150,7 @@ void ExtendGDScriptParser::update_document_links(const String &p_code) {
LSP::Range ExtendGDScriptParser::range_of_node(const GDScriptParser::Node *p_node) const {
GodotPosition start(p_node->start_line, p_node->start_column);
GodotPosition end(p_node->end_line, p_node->end_column);
return GodotRange(start, end).to_lsp(lines);
return GodotRange(start, end).to_lsp();
}
void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, LSP::DocumentSymbol &r_symbol) {
@ -333,8 +255,8 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p
symbol.script_path = path;
symbol.detail = "const " + symbol.name;
if (m.constant->get_datatype().is_hard_type()) {
symbol.detail += ": " + m.constant->get_datatype().to_string();
if (m.constant->type_constraint.is_hard_type()) {
symbol.detail += ": " + m.constant->type_constraint.to_string();
}
const Variant &default_value = m.constant->initializer->reduced_value;
@ -391,8 +313,8 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p
param_symbol.uri = uri;
param_symbol.script_path = path;
param_symbol.detail = "var " + param_symbol.name;
if (param->get_datatype().is_hard_type()) {
param_symbol.detail += ": " + param->get_datatype().to_string();
if (param->type_constraint.is_hard_type()) {
param_symbol.detail += ": " + param->type_constraint.to_string();
}
symbol.children.push_back(param_symbol);
}
@ -404,8 +326,8 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p
symbol.name = m.enum_value.identifier->name;
symbol.kind = LSP::SymbolKind::EnumMember;
symbol.deprecated = false;
symbol.range.start = GodotPosition(m.enum_value.line, m.enum_value.start_column).to_lsp(lines);
symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.end_column).to_lsp(lines);
symbol.range.start = GodotPosition(m.enum_value.line, m.enum_value.start_column).to_lsp();
symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.end_column).to_lsp();
symbol.selectionRange = range_of_node(m.enum_value.identifier);
symbol.documentation = m.enum_value.doc_data.description;
symbol.uri = uri;
@ -440,8 +362,8 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p
child.name = value.identifier->name;
child.kind = LSP::SymbolKind::EnumMember;
child.deprecated = false;
child.range.start = GodotPosition(value.line, value.start_column).to_lsp(lines);
child.range.end = GodotPosition(value.line, value.end_column).to_lsp(lines);
child.range.start = GodotPosition(value.line, value.start_column).to_lsp();
child.range.end = GodotPosition(value.line, value.end_column).to_lsp();
child.selectionRange = range_of_node(value.identifier);
child.documentation = value.doc_data.description;
child.uri = uri;
@ -502,8 +424,8 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN
parameters += ", ";
}
parameters += String(parameter->identifier->name);
if (parameter->get_datatype().is_hard_type()) {
parameters += ": " + parameter->get_datatype().to_string();
if (parameter->type_constraint.is_hard_type()) {
parameters += ": " + parameter->type_constraint.to_string();
}
if (parameter->initializer != nullptr) {
parameters += " = " + parameter->initializer->reduced_value.to_json_string();
@ -514,11 +436,11 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN
parameters += ", ";
}
const ParameterNode *rest_param = p_func->rest_parameter;
parameters += "..." + rest_param->identifier->name + ": " + rest_param->get_datatype().to_string();
parameters += "..." + rest_param->identifier->name + ": " + rest_param->type_constraint.to_string();
}
r_symbol.detail += parameters + ")";
const DataType return_type = p_func->get_datatype();
const DataType return_type = p_func->return_type_constraint;
if (return_type.is_hard_type()) {
if (return_type.kind == DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
r_symbol.detail += " -> void";
@ -615,8 +537,8 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN
break;
default:
// Fallback.
symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp(get_lines());
symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp(get_lines());
symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp();
symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp();
symbol.selectionRange = symbol.range;
break;
}
@ -710,14 +632,29 @@ String ExtendGDScriptParser::get_text_for_lookup_symbol(const LSP::Position &p_c
return longthing;
}
String ExtendGDScriptParser::get_identifier_under_position(const LSP::Position &p_position, LSP::Range &r_range) const {
String ExtendGDScriptParser::get_symbol_name_under_position(const LSP::Position &p_position, LSP::Range &r_range) const {
r_range = LSP::Range(p_position, p_position); // Default for error macros.
ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
String line = lines[p_position.line];
if (line.is_empty()) {
return "";
}
// Checks against line.size(), which includes a terminating NUL. This is to allow a cursor after the last character.
ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
LSP::Position pos = p_position;
// Cursor after last character.
if (pos.character >= line.length()) {
pos.character--;
}
// If on the start of an annotation move the position into the identifier part. We account for "@" at the end.
if (line[pos.character] == '@' && pos.character + 1 < line.size() && is_unicode_identifier_start(line[pos.character + 1])) {
pos.character++;
}
// `p_position` cursor is BETWEEN chars, not ON chars.
// ->
// ```gdscript
@ -729,51 +666,54 @@ String ExtendGDScriptParser::get_identifier_under_position(const LSP::Position &
// |
// | cursor on `member`, pos on ` ` (space)
// ```
// -> Move position to previous character if:
// * Position not on valid identifier char.
// * Prev position is valid identifier char.
LSP::Position pos = p_position;
if (
pos.character >= line.length() // Cursor at end of line.
|| (!is_unicode_identifier_continue(line[pos.character]) // Not on valid identifier char.
&& (pos.character > 0 // Not line start -> there is a prev char.
&& is_unicode_identifier_continue(line[pos.character - 1]) // Prev is valid identifier char.
))) {
if (!is_unicode_identifier_continue(line[pos.character])) {
if (pos.character == 0 || !is_unicode_identifier_continue(line[pos.character - 1])) {
// In between two non-identifier chars.
return "";
}
// Move position to previous character if not on valid char and the previous char is valid.
pos.character--;
}
int start_pos = pos.character;
// Iterate forward till we have a start. Symbol starts require lookahead, so we save the latest valid start and track back to it once we can stop looking.
// E.g. ?0nly
// ^
// | could be an identifier start (since 0 can't start identifiers), but if there was another symbol in front of 0 the identifier would be longer.
int last_valid_start_pos = -1;
for (int c = pos.character; c >= 0; c--) {
start_pos = c;
char32_t ch = line[c];
bool valid_char = is_unicode_identifier_continue(ch);
if (!valid_char) {
if (is_unicode_identifier_start(ch)) {
last_valid_start_pos = c;
}
if (!is_unicode_identifier_continue(ch)) {
break;
}
}
int end_pos = pos.character;
// Iterate backwards till we have an end. No lookahead required. Uses +1 since the end of a range is exclusive.
int end_pos = pos.character + 1;
for (int c = pos.character; c < line.length(); c++) {
char32_t ch = line[c];
bool valid_char = is_unicode_identifier_continue(ch);
if (!valid_char) {
if (!is_unicode_identifier_continue(ch)) {
break;
}
end_pos = c;
end_pos = c + 1;
}
if (!is_unicode_identifier_start(line[start_pos + 1])) {
if (last_valid_start_pos == -1) {
return "";
}
if (start_pos < end_pos) {
r_range.start.line = r_range.end.line = pos.line;
r_range.start.character = start_pos + 1;
r_range.end.character = end_pos + 1;
return line.substr(start_pos + 1, end_pos - start_pos);
// For annotations we include the @, since it is included in the symbol name used by other parts of the LSP code.
int start_pos = last_valid_start_pos;
if (start_pos > 0 && line[start_pos - 1] == '@') {
start_pos -= 1;
}
return "";
r_range.start.character = start_pos;
r_range.end.character = end_pos;
return line.substr(start_pos, end_pos - start_pos);
}
String ExtendGDScriptParser::get_uri() const {
@ -870,41 +810,17 @@ const List<LSP::DocumentLink> &ExtendGDScriptParser::get_document_links() const
return document_links;
}
const Array &ExtendGDScriptParser::get_member_completions() {
if (member_completions.is_empty()) {
for (const KeyValue<String, const LSP::DocumentSymbol *> &E : members) {
const LSP::DocumentSymbol *symbol = E.value;
LSP::CompletionItem item = symbol->make_completion_item();
item.data = JOIN_SYMBOLS(path, E.key);
member_completions.push_back(item.to_json());
}
for (const KeyValue<String, ClassMembers> &E : inner_classes) {
const ClassMembers *inner_class = &E.value;
for (const KeyValue<String, const LSP::DocumentSymbol *> &F : *inner_class) {
const LSP::DocumentSymbol *symbol = F.value;
LSP::CompletionItem item = symbol->make_completion_item();
item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(E.key, F.key));
member_completions.push_back(item.to_json());
}
}
}
return member_completions;
}
Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
ERR_FAIL_NULL_V(p_func, Dictionary());
Dictionary func;
func["name"] = p_func->identifier->name;
func["return_type"] = p_func->get_datatype().to_string();
func["return_type"] = p_func->return_type_constraint.to_string();
func["rpc_config"] = p_func->rpc_config;
Array parameters;
for (int i = 0; i < p_func->parameters.size(); i++) {
Dictionary arg;
arg["name"] = p_func->parameters[i]->identifier->name;
arg["type"] = p_func->parameters[i]->get_datatype().to_string();
arg["type"] = p_func->parameters[i]->type_constraint.to_string();
if (p_func->parameters[i]->initializer != nullptr) {
arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
}
@ -954,7 +870,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode
Dictionary api;
api["name"] = m.constant->identifier->name;
api["value"] = m.constant->initializer->reduced_value;
api["data_type"] = m.constant->get_datatype().to_string();
api["data_type"] = m.constant->type_constraint.to_string();
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
api["signature"] = symbol->detail;
api["description"] = symbol->documentation;
@ -991,7 +907,7 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode
case ClassNode::Member::VARIABLE: {
Dictionary api;
api["name"] = m.variable->identifier->name;
api["data_type"] = m.variable->get_datatype().to_string();
api["data_type"] = m.variable->type_constraint.to_string();
api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());

View file

@ -42,14 +42,6 @@
#define COLUMN_NUMBER_TO_INDEX(p_column) ((p_column) - 1)
#endif
#ifndef SYMBOL_SEPARATOR
#define SYMBOL_SEPARATOR "::"
#endif
#ifndef JOIN_SYMBOLS
#define JOIN_SYMBOLS(p_path, name) ((p_path) + SYMBOL_SEPARATOR + (name))
#endif
typedef HashMap<String, const LSP::DocumentSymbol *> ClassMembers;
/**
@ -79,8 +71,8 @@ struct GodotPosition {
GodotPosition(int p_line, int p_column) :
line(p_line), column(p_column) {}
LSP::Position to_lsp(const Vector<String> &p_lines) const;
static GodotPosition from_lsp(const LSP::Position p_pos, const Vector<String> &p_lines);
LSP::Position to_lsp() const;
static GodotPosition from_lsp(const LSP::Position p_pos);
bool operator==(const GodotPosition &p_other) const {
return line == p_other.line && column == p_other.column;
@ -98,8 +90,8 @@ struct GodotRange {
GodotRange(GodotPosition p_start, GodotPosition p_end) :
start(p_start), end(p_end) {}
LSP::Range to_lsp(const Vector<String> &p_lines) const;
static GodotRange from_lsp(const LSP::Range &p_range, const Vector<String> &p_lines);
LSP::Range to_lsp() const;
static GodotRange from_lsp(const LSP::Range &p_range);
bool operator==(const GodotRange &p_other) const {
return start == p_other.start && end == p_other.end;
@ -134,8 +126,6 @@ class ExtendGDScriptParser : public GDScriptParser {
const LSP::DocumentSymbol *search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name = "") const;
Array member_completions;
public:
_FORCE_INLINE_ const String &get_path() const { return path; }
_FORCE_INLINE_ const Vector<String> &get_lines() const { return lines; }
@ -149,7 +139,13 @@ public:
String get_text_for_completion(const LSP::Position &p_cursor) const;
String get_text_for_lookup_symbol(const LSP::Position &p_cursor, const String &p_symbol = "", bool p_func_required = false) const;
String get_identifier_under_position(const LSP::Position &p_position, LSP::Range &r_range) const;
/**
* Parses the symbol name at the given position. Returns that name and its full range.
*
* The returned name might be a false positive and not translate to an actual symbol e.g. it might be a language keyword.
* The results of this method are not equivalent to identifier AST nodes. Instead it returns results that are compatible with `LSP::DocumentSymbol::name` i.e. includes `@` for annotations.
*/
String get_symbol_name_under_position(const LSP::Position &p_position, LSP::Range &r_range) const;
String get_uri() const;
/**

View file

@ -30,23 +30,27 @@
#include "gdscript_language_protocol.h"
#include "godot_lsp.h"
#include "core/config/project_settings.h"
#include "core/object/callable_mp.h"
#include "core/object/class_db.h"
#include "core/os/os.h"
#include "editor/doc/doc_tools.h"
#include "editor/doc/editor_help.h"
#include "editor/editor_log.h"
#include "editor/editor_node.h"
#include "editor/settings/editor_settings.h"
#include "modules/gdscript/language_server/godot_lsp.h"
#define LSP_CLIENT_V(m_ret_val) \
#define LSP_CLIENT_V(m_ret_val) \
ERR_FAIL_COND_V(latest_client_id == LSP_NO_CLIENT, m_ret_val); \
ERR_FAIL_COND_V(!clients.has(latest_client_id), m_ret_val); \
Ref<LSPeer> client = clients.get(latest_client_id); \
ERR_FAIL_COND_V(!clients.has(latest_client_id), m_ret_val); \
Ref<LSPeer> client = clients.get(latest_client_id); \
ERR_FAIL_COND_V(!client.is_valid(), m_ret_val);
#define LSP_CLIENT \
ERR_FAIL_COND(latest_client_id == LSP_NO_CLIENT); \
ERR_FAIL_COND(!clients.has(latest_client_id)); \
#define LSP_CLIENT \
ERR_FAIL_COND(latest_client_id == LSP_NO_CLIENT); \
ERR_FAIL_COND(!clients.has(latest_client_id)); \
Ref<LSPeer> client = clients.get(latest_client_id); \
ERR_FAIL_COND(!client.is_valid());
@ -148,6 +152,9 @@ Error GDScriptLanguageProtocol::on_client_connected() {
void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
clients.erase(p_client_id);
if (clients.is_empty()) {
scene_cache.clear();
}
EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
}
@ -171,18 +178,40 @@ String GDScriptLanguageProtocol::format_output(const String &p_text) {
}
void GDScriptLanguageProtocol::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
#ifndef DISABLE_DEPRECATED
ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
ClassDB::bind_method(D_METHOD("on_client_disconnected", "client_id"), &GDScriptLanguageProtocol::on_client_disconnected);
ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
#endif // !DISABLE_DEPRECATED
}
Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
template <typename T>
Variant get_deep(Variant p_dict, Variant p_default, T p_key) {
if (p_dict.get_type() != Variant::DICTIONARY) {
return p_default;
}
return p_dict.operator Dictionary().get(p_key, p_default);
}
template <typename T1, typename... T2>
Variant get_deep(Variant p_dict, Variant p_default, T1 p_key1, T2... p_key2) {
if (p_dict.get_type() != Variant::DICTIONARY || !p_dict.operator Dictionary().has(p_key1)) {
return p_default;
}
return get_deep(p_dict.operator Dictionary()[p_key1], p_default, p_key2...);
}
Variant GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
LSP_CLIENT_V(Variant());
LSP::InitializeResult ret;
{
@ -199,50 +228,35 @@ Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
}
if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
// Show a general warning, which works for all clients.
LSP::ShowMessageParams params{
LSP::MessageType::Warning,
"The GDScript Language Server might not work correctly with other projects than the one opened in Godot."
};
notify_client("window/showMessage", params.to_json());
}
}
String root_uri = p_params["rootUri"];
String root = p_params.get("rootPath", "");
bool is_same_workspace;
#ifndef WINDOWS_ENABLED
is_same_workspace = root.to_lower() == workspace->root.to_lower();
#else
is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();
#endif
if (root_uri.length() && is_same_workspace) {
workspace->root_uri = root_uri;
} else {
String r_root = workspace->root;
r_root = r_root.lstrip("/");
workspace->root_uri = "file:///" + r_root;
Dictionary params;
params["path"] = workspace->root;
Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
Ref<LSPeer> peer = clients.get(latest_client_id);
if (peer.is_valid()) {
String msg = Variant(request).to_json_string();
msg = format_output(msg);
(*peer)->res_queue.push_back(msg.utf8());
// Send gdscript_client/changeWorkspace to prompt client side handling, where supported. (Currently known users: VSCode extension, Rider extension).
notify_client("gdscript_client/changeWorkspace", Dictionary({ { "path", ProjectSettings::get_singleton()->get_resource_path() } }));
}
}
if (!_initialized) {
workspace->initialize();
text_document->initialize();
_initialized = true;
}
// Handle client capabilities.
Dictionary capabilities = p_params["capabilities"];
client->behavior.use_snippets_for_brace_completion = get_deep(capabilities, false,
"textDocument", "completion", "completionItem", "snippetSupport");
Array allowed_tags = get_deep(capabilities, Array(), "general", "markdown", "allowedTags");
for (const Variant &tag : allowed_tags) {
if (tag.is_string()) {
client->behavior.markdown_allowed_html_tags.insert(tag);
}
}
return ret.to_json();
}
@ -270,6 +284,8 @@ void GDScriptLanguageProtocol::poll(int p_limit_usec) {
on_client_connected();
}
scene_cache.poll();
HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
while (E != clients.end()) {
Ref<LSPeer> peer = E->value;
@ -316,6 +332,7 @@ void GDScriptLanguageProtocol::stop() {
peer->connection->disconnect_from_host();
}
scene_cache.clear();
server->stop();
}
@ -339,7 +356,7 @@ void GDScriptLanguageProtocol::notify_client(const String &p_method, const Varia
peer->res_queue.push_back(msg.utf8());
}
void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id, const Callable &p_response_handler) {
#ifdef TESTS_ENABLED
if (clients.is_empty()) {
return;
@ -354,6 +371,7 @@ void GDScriptLanguageProtocol::request_client(const String &p_method, const Vari
ERR_FAIL_COND(peer.is_null());
Dictionary message = make_request(p_method, p_params, next_server_id);
set_response_handler(next_client_id, p_response_handler);
next_server_id++;
String msg = Variant(message).to_json_string();
msg = format_output(msg);
@ -430,6 +448,12 @@ ExtendGDScriptParser *GDScriptLanguageProtocol::get_parse_result(const String &p
return *cached_parser;
}
const HashSet<String> &GDScriptLanguageProtocol::get_client_markdown_allowed_html_tags() const {
static const HashSet<String> default_tags = {};
LSP_CLIENT_V(default_tags);
return client->behavior.markdown_allowed_html_tags;
}
void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {
LSP_CLIENT;
@ -448,6 +472,8 @@ void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {
client->managed_files[path] = document;
client->parse_script(path);
scene_cache.request_load(path);
}
void GDScriptLanguageProtocol::lsp_did_change(const Dictionary &p_params) {
@ -493,6 +519,92 @@ void GDScriptLanguageProtocol::lsp_did_close(const Dictionary &p_params) {
/// A close notification requires a previous open notification to be sent.
ERR_FAIL_COND_MSG(!was_opened, "LSP: Client is closing file without opening it.");
scene_cache.unload(path);
}
Array GDScriptLanguageProtocol::lsp_completion(const Dictionary &p_params) {
Array arr;
LSP_CLIENT_V(arr);
LSP::CompletionParams params;
params.load(p_params);
Dictionary request_data = params.to_json();
List<ScriptLanguage::CodeCompletionOption> options;
get_workspace()->completion(params, &options);
if (!options.is_empty()) {
int i = 0;
arr.resize(options.size());
for (const ScriptLanguage::CodeCompletionOption &option : options) {
LSP::CompletionItem item;
item.label = option.display;
item.data = request_data;
item.insertText = option.insert_text;
// LSP clients won't autoclose brackets.
if (client->behavior.use_snippets_for_brace_completion) {
// Use snippet insert mode to insert closing brace as well.
if (item.insertText.ends_with("(")) {
item.insertText += "$1)";
item.insertTextFormat = LSP::InsertTextFormat::Snippet;
}
} else {
// Trim braces.
item.insertText = item.insertText.trim_suffix("(");
}
if (option.text_edit.is_set()) {
GodotRange range(GodotPosition(option.text_edit.start_line, option.text_edit.start_column), GodotPosition(option.text_edit.end_line, option.text_edit.end_column));
item.textEdit.newText = option.text_edit.new_text;
item.textEdit.range = range.to_lsp();
}
switch (option.kind) {
case ScriptLanguage::CODE_COMPLETION_KIND_ENUM:
item.kind = LSP::CompletionItemKind::Enum;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_CLASS:
item.kind = LSP::CompletionItemKind::Class;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_MEMBER:
item.kind = LSP::CompletionItemKind::Property;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION:
item.kind = LSP::CompletionItemKind::Method;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_SIGNAL:
item.kind = LSP::CompletionItemKind::Event;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT:
item.kind = LSP::CompletionItemKind::Constant;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_VARIABLE:
item.kind = LSP::CompletionItemKind::Variable;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_FILE_PATH:
item.kind = LSP::CompletionItemKind::File;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_NODE_PATH:
item.kind = LSP::CompletionItemKind::Snippet;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT:
item.kind = LSP::CompletionItemKind::Text;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_KEYWORD:
item.kind = LSP::CompletionItemKind::Keyword;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_MAX: {
}
}
arr[i] = item.to_json();
i++;
}
}
return arr;
}
void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
@ -505,12 +617,12 @@ void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPo
return;
}
String symbol_identifier;
String symbol_name;
LSP::Range range;
symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
symbol_name = parser->get_symbol_name_under_position(p_doc_pos.position, range);
for (const KeyValue<StringName, ClassMembers> &E : workspace->native_members) {
if (const LSP::DocumentSymbol *const *symbol = E.value.getptr(symbol_identifier)) {
if (const LSP::DocumentSymbol *const *symbol = E.value.getptr(symbol_name)) {
r_list.push_back(*symbol);
}
}
@ -518,13 +630,13 @@ void GDScriptLanguageProtocol::resolve_related_symbols(const LSP::TextDocumentPo
for (const KeyValue<String, ExtendGDScriptParser *> &E : client->parse_results) {
const ExtendGDScriptParser *scr = E.value;
const ClassMembers &members = scr->get_members();
if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_name)) {
r_list.push_back(*symbol);
}
for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
const ClassMembers *inner_class = &F.value;
if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_name)) {
r_list.push_back(*symbol);
}
}
@ -558,14 +670,12 @@ GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
SET_DOCUMENT_METHOD(didSave);
SET_DOCUMENT_METHOD(documentSymbol);
SET_DOCUMENT_METHOD(documentHighlight);
SET_DOCUMENT_METHOD(completion);
SET_DOCUMENT_METHOD(rename);
SET_DOCUMENT_METHOD(prepareRename);
SET_DOCUMENT_METHOD(references);
SET_DOCUMENT_METHOD(foldingRange);
SET_DOCUMENT_METHOD(codeLens);
SET_DOCUMENT_METHOD(documentLink);
SET_DOCUMENT_METHOD(colorPresentation);
SET_DOCUMENT_METHOD(hover);
SET_DOCUMENT_METHOD(definition);
SET_DOCUMENT_METHOD(declaration);
@ -577,8 +687,6 @@ GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));
set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));
workspace->root = ProjectSettings::get_singleton()->get_resource_path();
}
#undef SET_DOCUMENT_METHOD

View file

@ -32,6 +32,7 @@
#include "gdscript_text_document.h"
#include "gdscript_workspace.h"
#include "scene_cache.h"
#include "core/io/stream_peer_tcp.h"
#include "core/io/tcp_server.h"
@ -46,9 +47,15 @@
class GDScriptLanguageProtocol : public JSONRPC {
GDCLASS(GDScriptLanguageProtocol, JSONRPC)
#ifdef TESTS_ENABLED
friend class TestGDScriptLanguageProtocolInitializer;
#endif
public:
struct ClientBehavior {
/** If `true` use snippet insert mode to position the cursor between braces of completion options. If `false` strip braces from completion options since we can't provide good UX for them. */
bool use_snippets_for_brace_completion = false;
/** HTML tags, e.g. `span`, which the client is capable of rendering inside Markdown content. Assumes full support for attributes e.g. `style`. */
HashSet<String> markdown_allowed_html_tags;
};
private:
struct LSPeer : RefCounted {
@ -65,6 +72,12 @@ private:
Error handle_data();
Error send_data();
/**
* Represents how the server should behave towards this client in certain situations.
* This gets derived from client capabilities so the configured behavior is guaranteed to be supported by the client.
*/
ClientBehavior behavior;
/**
* Tracks all files that the client claimed, however for files deemed not relevant
* to the server the `text` might not be persisted.
@ -92,6 +105,7 @@ private:
static GDScriptLanguageProtocol *singleton;
HashMap<int, Ref<LSPeer>> clients;
SceneCache scene_cache;
Ref<TCPServer> server;
int latest_client_id = LSP_NO_CLIENT;
int next_client_id = 0;
@ -112,13 +126,15 @@ private:
protected:
static void _bind_methods();
Dictionary initialize(const Dictionary &p_params);
Variant initialize(const Dictionary &p_params);
void initialized(const Variant &p_params);
public:
_FORCE_INLINE_ static GDScriptLanguageProtocol *get_singleton() { return singleton; }
_FORCE_INLINE_ Ref<GDScriptWorkspace> get_workspace() { return workspace; }
_FORCE_INLINE_ Ref<GDScriptTextDocument> get_text_document() { return text_document; }
_FORCE_INLINE_ SceneCache *get_scene_cache() { return &scene_cache; }
_FORCE_INLINE_ bool is_initialized() const { return _initialized; }
void poll(int p_limit_usec);
@ -126,7 +142,7 @@ public:
void stop();
void notify_client(const String &p_method, const Variant &p_params = Variant(), int p_client_id = -1);
void request_client(const String &p_method, const Variant &p_params = Variant(), int p_client_id = -1);
void request_client(const String &p_method, const Variant &p_params = Variant(), int p_client_id = -1, const Callable &p_response_handler = Callable());
bool is_smart_resolve_enabled() const;
bool is_goto_native_symbols_enabled() const;
@ -136,6 +152,9 @@ public:
void lsp_did_change(const Dictionary &p_params);
void lsp_did_close(const Dictionary &p_params);
// Completion
Array lsp_completion(const Dictionary &p_params);
/**
* Returns a list of symbols that might be related to the document position.
*
@ -150,6 +169,14 @@ public:
*/
ExtendGDScriptParser *get_parse_result(const String &p_path);
/**
* Returns the HTML tags the client can render inside Markdown content, e.g. `span`.
* Defaults to an empty set if no client is connected.
*
* TODO: Remove after moving endpoints into unified class. Access non-null client directly.
*/
const HashSet<String> &get_client_markdown_allowed_html_tags() const;
GDScriptLanguageProtocol();
~GDScriptLanguageProtocol() {
clients.clear();

View file

@ -30,6 +30,8 @@
#include "gdscript_language_server.h"
#include "gdscript_language_protocol.h"
#include "core/os/os.h"
#include "editor/editor_log.h"
#include "editor/editor_node.h"
@ -38,14 +40,6 @@
int GDScriptLanguageServer::port_override = -1;
GDScriptLanguageServer::GDScriptLanguageServer() {
// TODO: Move to editor_settings.cpp
_EDITOR_DEF("network/language_server/remote_host", host);
_EDITOR_DEF("network/language_server/remote_port", port);
_EDITOR_DEF("network/language_server/enable_smart_resolve", true);
_EDITOR_DEF("network/language_server/show_native_symbols_in_editor", false);
_EDITOR_DEF("network/language_server/use_thread", use_thread);
_EDITOR_DEF("network/language_server/poll_limit_usec", poll_limit_usec);
set_process_internal(true);
}
@ -62,7 +56,7 @@ void GDScriptLanguageServer::_notification(int p_what) {
}
if (started && !use_thread) {
protocol.poll(poll_limit_usec);
GDScriptLanguageProtocol::get_singleton()->poll(poll_limit_usec);
}
} break;
@ -88,7 +82,7 @@ void GDScriptLanguageServer::thread_main(void *p_userdata) {
GDScriptLanguageServer *self = static_cast<GDScriptLanguageServer *>(p_userdata);
while (self->thread_running) {
// Poll 20 times per second
self->protocol.poll(self->poll_limit_usec);
GDScriptLanguageProtocol::get_singleton()->poll(self->poll_limit_usec);
OS::get_singleton()->delay_usec(50000);
}
}
@ -98,15 +92,18 @@ void GDScriptLanguageServer::start() {
port = (GDScriptLanguageServer::port_override > -1) ? GDScriptLanguageServer::port_override : (int)_EDITOR_GET("network/language_server/remote_port");
use_thread = (bool)_EDITOR_GET("network/language_server/use_thread");
poll_limit_usec = (int)_EDITOR_GET("network/language_server/poll_limit_usec");
if (protocol.start(port, IPAddress(host)) == OK) {
EditorNode::get_log()->add_message("--- GDScript language server started on port " + itos(port) + " ---", EditorLog::MSG_TYPE_EDITOR);
if (use_thread) {
thread_running = true;
thread.start(GDScriptLanguageServer::thread_main, this);
}
set_process_internal(!use_thread);
started = true;
const Error status = GDScriptLanguageProtocol::get_singleton()->start(port, IPAddress(host));
if (status != OK) {
EditorNode::get_log()->add_message("--- Failed to start GDScript language server on port " + itos(port) + ": " + error_names[status] + " ---", EditorLog::MSG_TYPE_EDITOR);
return;
}
EditorNode::get_log()->add_message("--- GDScript language server started on port " + itos(port) + " ---", EditorLog::MSG_TYPE_EDITOR);
if (use_thread) {
thread_running = true;
thread.start(GDScriptLanguageServer::thread_main, this);
}
set_process_internal(!use_thread);
started = true;
}
void GDScriptLanguageServer::stop() {
@ -115,7 +112,7 @@ void GDScriptLanguageServer::stop() {
thread_running = false;
thread.wait_to_finish();
}
protocol.stop();
GDScriptLanguageProtocol::get_singleton()->stop();
started = false;
EditorNode::get_log()->add_message("--- GDScript language server stopped ---", EditorLog::MSG_TYPE_EDITOR);
}

View file

@ -30,24 +30,23 @@
#pragma once
#include "gdscript_language_protocol.h"
#include "editor/plugins/editor_plugin.h"
class GDScriptLanguageServer : public EditorPlugin {
GDCLASS(GDScriptLanguageServer, EditorPlugin);
GDScriptLanguageProtocol protocol;
GDSOFTCLASS(GDScriptLanguageServer, EditorPlugin);
Thread thread;
bool thread_running = false;
// There is no notification when the editor is initialized. We need to poll till we attempted to start the server.
bool start_attempted = false;
bool started = false;
// Defaults located in editor_settings.cpp
bool use_thread = false;
String host = "127.0.0.1";
int port = 6005;
int poll_limit_usec = 100000;
String host;
int port = 0;
int poll_limit_usec = 0;
static void thread_main(void *p_userdata);
private:

View file

@ -34,32 +34,35 @@
#include "gdscript_extend_parser.h"
#include "gdscript_language_protocol.h"
#include "editor/script/script_text_editor.h"
#include "core/io/resource_loader.h"
#include "core/object/callable_mp.h"
#include "core/object/class_db.h"
#include "editor/script/script_editor_plugin.h"
#include "editor/settings/editor_settings.h"
#include "servers/display/display_server.h"
void GDScriptTextDocument::_bind_methods() {
ClassDB::bind_method(D_METHOD("didOpen"), &GDScriptTextDocument::didOpen);
ClassDB::bind_method(D_METHOD("didClose"), &GDScriptTextDocument::didClose);
ClassDB::bind_method(D_METHOD("didChange"), &GDScriptTextDocument::didChange);
ClassDB::bind_method(D_METHOD("willSaveWaitUntil"), &GDScriptTextDocument::willSaveWaitUntil);
ClassDB::bind_method(D_METHOD("didSave"), &GDScriptTextDocument::didSave);
ClassDB::bind_method(D_METHOD("nativeSymbol"), &GDScriptTextDocument::nativeSymbol);
ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol);
ClassDB::bind_method(D_METHOD("completion"), &GDScriptTextDocument::completion);
ClassDB::bind_method(D_METHOD("resolve"), &GDScriptTextDocument::resolve);
ClassDB::bind_method(D_METHOD("rename"), &GDScriptTextDocument::rename);
ClassDB::bind_method(D_METHOD("prepareRename"), &GDScriptTextDocument::prepareRename);
ClassDB::bind_method(D_METHOD("references"), &GDScriptTextDocument::references);
ClassDB::bind_method(D_METHOD("foldingRange"), &GDScriptTextDocument::foldingRange);
ClassDB::bind_method(D_METHOD("codeLens"), &GDScriptTextDocument::codeLens);
ClassDB::bind_method(D_METHOD("documentLink"), &GDScriptTextDocument::documentLink);
ClassDB::bind_method(D_METHOD("colorPresentation"), &GDScriptTextDocument::colorPresentation);
ClassDB::bind_method(D_METHOD("hover"), &GDScriptTextDocument::hover);
ClassDB::bind_method(D_METHOD("definition"), &GDScriptTextDocument::definition);
ClassDB::bind_method(D_METHOD("declaration"), &GDScriptTextDocument::declaration);
ClassDB::bind_method(D_METHOD("signatureHelp"), &GDScriptTextDocument::signatureHelp);
ClassDB::bind_method(D_METHOD("show_native_symbol_in_editor"), &GDScriptTextDocument::show_native_symbol_in_editor);
ClassDB::bind_method(D_METHOD("show_native_symbol_in_editor", "symbol_id"), &GDScriptTextDocument::show_native_symbol_in_editor);
#ifndef DISABLE_DEPRECATED
ClassDB::bind_method(D_METHOD("didOpen", "params"), &GDScriptTextDocument::didOpen);
ClassDB::bind_method(D_METHOD("didClose", "params"), &GDScriptTextDocument::didClose);
ClassDB::bind_method(D_METHOD("didChange", "params"), &GDScriptTextDocument::didChange);
ClassDB::bind_method(D_METHOD("willSaveWaitUntil", "params"), &GDScriptTextDocument::willSaveWaitUntil);
ClassDB::bind_method(D_METHOD("didSave", "params"), &GDScriptTextDocument::didSave);
ClassDB::bind_method(D_METHOD("nativeSymbol", "params"), &GDScriptTextDocument::nativeSymbol);
ClassDB::bind_method(D_METHOD("documentSymbol", "params"), &GDScriptTextDocument::documentSymbol);
ClassDB::bind_method(D_METHOD("completion", "params"), &GDScriptTextDocument::completion);
ClassDB::bind_method(D_METHOD("resolve", "params"), &GDScriptTextDocument::resolve);
ClassDB::bind_method(D_METHOD("rename", "params"), &GDScriptTextDocument::rename);
ClassDB::bind_method(D_METHOD("prepareRename", "params"), &GDScriptTextDocument::prepareRename);
ClassDB::bind_method(D_METHOD("references", "params"), &GDScriptTextDocument::references);
ClassDB::bind_method(D_METHOD("documentLink", "params"), &GDScriptTextDocument::documentLink);
ClassDB::bind_method(D_METHOD("hover", "params"), &GDScriptTextDocument::hover);
ClassDB::bind_method(D_METHOD("definition", "params"), &GDScriptTextDocument::definition);
ClassDB::bind_method(D_METHOD("declaration", "params"), &GDScriptTextDocument::declaration);
ClassDB::bind_method(D_METHOD("signatureHelp", "params"), &GDScriptTextDocument::signatureHelp);
#endif // !DISABLE_DEPRECATED
}
void GDScriptTextDocument::didOpen(const Variant &p_param) {
@ -122,21 +125,6 @@ void GDScriptTextDocument::notify_client_show_symbol(const LSP::DocumentSymbol *
GDScriptLanguageProtocol::get_singleton()->notify_client("gdscript/show_native_symbol", symbol->to_json(true));
}
void GDScriptTextDocument::initialize() {
if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
for (const KeyValue<StringName, ClassMembers> &E : GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members) {
const ClassMembers &members = E.value;
for (const KeyValue<String, const LSP::DocumentSymbol *> &F : members) {
const LSP::DocumentSymbol *symbol = members.get(F.key);
LSP::CompletionItem item = symbol->make_completion_item();
item.data = JOIN_SYMBOLS(String(E.key), F.key);
native_member_completions.push_back(item.to_json());
}
}
}
}
Variant GDScriptTextDocument::nativeSymbol(const Dictionary &p_params) {
Variant ret;
@ -165,68 +153,29 @@ Array GDScriptTextDocument::documentSymbol(const Dictionary &p_params) {
return arr;
}
Array GDScriptTextDocument::completion(const Dictionary &p_params) {
Array GDScriptTextDocument::documentHighlight(const Dictionary &p_params) {
Array arr;
LSP::CompletionParams params;
LSP::TextDocumentPositionParams params;
params.load(p_params);
Dictionary request_data = params.to_json();
List<ScriptLanguage::CodeCompletionOption> options;
GDScriptLanguageProtocol::get_singleton()->get_workspace()->completion(params, &options);
const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
if (symbol) {
String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(params.textDocument.uri);
Vector<LSP::Location> usages = GDScriptLanguageProtocol::get_singleton()->get_workspace()->find_usages_in_file(*symbol, path);
if (!options.is_empty()) {
int i = 0;
arr.resize(options.size());
for (const ScriptLanguage::CodeCompletionOption &option : options) {
LSP::CompletionItem item;
item.label = option.display;
item.data = request_data;
item.insertText = option.insert_text;
switch (option.kind) {
case ScriptLanguage::CODE_COMPLETION_KIND_ENUM:
item.kind = LSP::CompletionItemKind::Enum;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_CLASS:
item.kind = LSP::CompletionItemKind::Class;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_MEMBER:
item.kind = LSP::CompletionItemKind::Property;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION:
item.kind = LSP::CompletionItemKind::Method;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_SIGNAL:
item.kind = LSP::CompletionItemKind::Event;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT:
item.kind = LSP::CompletionItemKind::Constant;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_VARIABLE:
item.kind = LSP::CompletionItemKind::Variable;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_FILE_PATH:
item.kind = LSP::CompletionItemKind::File;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_NODE_PATH:
item.kind = LSP::CompletionItemKind::Snippet;
break;
case ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT:
item.kind = LSP::CompletionItemKind::Text;
break;
default: {
}
}
arr[i] = item.to_json();
i++;
for (const LSP::Location &usage : usages) {
LSP::DocumentHighlight highlight;
highlight.range = usage.range;
arr.push_back(highlight.to_json());
}
}
return arr;
}
Array GDScriptTextDocument::completion(const Dictionary &p_params) {
return GDScriptLanguageProtocol::get_singleton()->lsp_completion(p_params);
}
Dictionary GDScriptTextDocument::rename(const Dictionary &p_params) {
LSP::TextDocumentPositionParams params;
params.load(p_params);
@ -289,37 +238,11 @@ Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
if (data.get_type() == Variant::DICTIONARY) {
params.load(p_params["data"]);
symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params, item.label, item.kind == LSP::CompletionItemKind::Method || item.kind == LSP::CompletionItemKind::Function);
} else if (data.is_string()) {
String query = data;
Vector<String> param_symbols = query.split(SYMBOL_SEPARATOR, false);
if (param_symbols.size() >= 2) {
StringName class_name = param_symbols[0];
const String &member_name = param_symbols[param_symbols.size() - 1];
String inner_class_name;
if (param_symbols.size() >= 3) {
inner_class_name = param_symbols[1];
}
if (const ClassMembers *members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members.getptr(class_name)) {
if (const LSP::DocumentSymbol *const *member = members->getptr(member_name)) {
symbol = *member;
}
}
if (!symbol) {
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(class_name);
if (parser) {
symbol = parser->get_member_symbol(member_name, inner_class_name);
}
}
}
}
if (symbol) {
item.documentation = symbol->render();
const HashSet<String> &allowed_tags = GDScriptLanguageProtocol::get_singleton()->get_client_markdown_allowed_html_tags();
item.documentation = symbol->render(allowed_tags);
}
if (item.kind == LSP::CompletionItemKind::Event) {
@ -341,14 +264,6 @@ Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
return item.to_json(true);
}
Array GDScriptTextDocument::foldingRange(const Dictionary &p_params) {
return Array();
}
Array GDScriptTextDocument::codeLens(const Dictionary &p_params) {
return Array();
}
Array GDScriptTextDocument::documentLink(const Dictionary &p_params) {
Array ret;
@ -363,10 +278,6 @@ Array GDScriptTextDocument::documentLink(const Dictionary &p_params) {
return ret;
}
Array GDScriptTextDocument::colorPresentation(const Dictionary &p_params) {
return Array();
}
Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
LSP::TextDocumentPositionParams params;
params.load(p_params);
@ -374,7 +285,8 @@ Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
if (symbol) {
LSP::Hover hover;
hover.contents = symbol->render();
const HashSet<String> &allowed_tags = GDScriptLanguageProtocol::get_singleton()->get_client_markdown_allowed_html_tags();
hover.contents = symbol->render(allowed_tags);
hover.range.start = params.position;
hover.range.end = params.position;
return hover.to_json();
@ -384,9 +296,10 @@ Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
Array contents;
List<const LSP::DocumentSymbol *> list;
GDScriptLanguageProtocol::get_singleton()->resolve_related_symbols(params, list);
const HashSet<String> &allowed_tags = GDScriptLanguageProtocol::get_singleton()->get_client_markdown_allowed_html_tags();
for (const LSP::DocumentSymbol *&E : list) {
if (const LSP::DocumentSymbol *s = E) {
contents.push_back(s->render().value);
contents.push_back(s->render(allowed_tags).value);
}
}
ret["contents"] = contents;
@ -430,7 +343,7 @@ Variant GDScriptTextDocument::declaration(const Dictionary &p_params) {
case LSP::SymbolKind::Function:
id = "class_method:" + symbol->native_class + ":" + symbol->name;
break;
default:
default: // Deprecated.
id = "class_global:" + symbol->native_class + ":" + symbol->name;
break;
}

View file

@ -44,8 +44,6 @@ protected:
Ref<FileAccess> file_checker;
Array native_member_completions;
private:
Array find_symbols(const LSP::TextDocumentPositionParams &p_location, List<const LSP::DocumentSymbol *> &r_list);
void notify_client_show_symbol(const LSP::DocumentSymbol *symbol);
@ -62,21 +60,17 @@ public:
Variant nativeSymbol(const Dictionary &p_params);
Array documentSymbol(const Dictionary &p_params);
Array documentHighlight(const Dictionary &p_params);
Array completion(const Dictionary &p_params);
Dictionary resolve(const Dictionary &p_params);
Dictionary rename(const Dictionary &p_params);
Variant prepareRename(const Dictionary &p_params);
Array references(const Dictionary &p_params);
Array foldingRange(const Dictionary &p_params);
Array codeLens(const Dictionary &p_params);
Array documentLink(const Dictionary &p_params);
Array colorPresentation(const Dictionary &p_params);
Variant hover(const Dictionary &p_params);
Array definition(const Dictionary &p_params);
Variant declaration(const Dictionary &p_params);
Variant signatureHelp(const Dictionary &p_params);
void initialize();
GDScriptTextDocument();
};

View file

@ -30,30 +30,33 @@
#include "gdscript_workspace.h"
#include "../editor/gdscript_editor_language.h"
#include "../gdscript.h"
#include "../gdscript_parser.h"
#include "gdscript_language_protocol.h"
#include "core/config/project_settings.h"
#include "core/object/callable_mp.h"
#include "core/object/class_db.h"
#include "core/object/editor_language.h"
#include "core/object/script_language.h"
#include "editor/doc/doc_tools.h"
#include "editor/doc/editor_help.h"
#include "editor/editor_node.h"
#include "editor/file_system/editor_file_system.h"
#include "editor/settings/editor_settings.h"
#include "scene/resources/packed_scene.h"
void GDScriptWorkspace::_bind_methods() {
ClassDB::bind_method(D_METHOD("apply_new_signal"), &GDScriptWorkspace::apply_new_signal);
ClassDB::bind_method(D_METHOD("apply_new_signal", "obj", "function", "args"), &GDScriptWorkspace::apply_new_signal);
ClassDB::bind_method(D_METHOD("get_file_path", "uri"), &GDScriptWorkspace::get_file_path);
ClassDB::bind_method(D_METHOD("get_file_uri", "path"), &GDScriptWorkspace::get_file_uri);
ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
ClassDB::bind_method(D_METHOD("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api);
#ifndef DISABLE_DEPRECATED
ClassDB::bind_method(D_METHOD("didDeleteFiles"), &GDScriptWorkspace::didDeleteFiles);
ClassDB::bind_method(D_METHOD("didDeleteFiles", "params"), &GDScriptWorkspace::didDeleteFiles);
ClassDB::bind_method(D_METHOD("parse_script", "path", "content"), &GDScriptWorkspace::parse_script);
ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_script);
ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_local_script);
ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
#endif
}
@ -422,7 +425,7 @@ bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_
String path = get_file_path(p_doc_pos.textDocument.uri);
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
if (parser) {
_ALLOW_DISCARD_ parser->get_identifier_under_position(p_doc_pos.position, r_range);
_ALLOW_DISCARD_ parser->get_symbol_name_under_position(p_doc_pos.position, r_range);
r_symbol = *reference_symbol;
return true;
}
@ -433,7 +436,7 @@ bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_
Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path) {
Vector<LSP::Location> usages;
String identifier = p_symbol.name;
const String &identifier = p_symbol.name;
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_file_path);
if (parser) {
const PackedStringArray &content = parser->get_lines();
@ -451,18 +454,30 @@ Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::Document
params.position.line = i;
params.position.character = character;
const LSP::DocumentSymbol *other_symbol = resolve_symbol(params);
LSP::Range range;
String identifier_under_cursor = parser->get_symbol_name_under_position(params.position, range);
if (other_symbol == &p_symbol) {
LSP::Location loc;
loc.uri = text_doc.uri;
loc.range.start = params.position;
loc.range.end.line = params.position.line;
loc.range.end.character = params.position.character + identifier.length();
usages.append(loc);
if (identifier_under_cursor == identifier) {
const LSP::DocumentSymbol *other_symbol = resolve_symbol(params);
if (other_symbol == &p_symbol) {
LSP::Location loc;
loc.uri = text_doc.uri;
loc.range.start = params.position;
loc.range.end.line = params.position.line;
loc.range.end.character = params.position.character + identifier.length();
usages.append(loc);
}
}
character = line.find(identifier, character + 1);
if (identifier_under_cursor.length() < identifier.length()) {
// `get_symbol_name_under_position` is supposed to recognize all possible symbol names. Since a simple string search already confirmed
// the presence of `p_symbol.name` in the text, this case has to be a bug.
ERR_PRINT(vformat("LSP Bug, please report. \"get_symbol_name_under_position\" did not correctly resolve \"%s\"", identifier));
character = line.find(identifier, character + 1);
} else {
character = line.find(identifier, range.end.character);
}
}
}
}
@ -592,51 +607,6 @@ void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
}
void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
if (!efsd) {
return;
}
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_get_owners(efsd->get_subdir(i), p_path, owners);
}
for (int i = 0; i < efsd->get_file_count(); i++) {
Vector<String> deps = efsd->get_file_deps(i);
bool found = false;
for (int j = 0; j < deps.size(); j++) {
if (deps[j] == p_path) {
found = true;
break;
}
}
if (!found) {
continue;
}
owners.push_back(efsd->get_file_path(i));
}
}
Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
Node *owner_scene_node = nullptr;
List<String> owners;
_get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
for (const String &owner : owners) {
NodePath owner_path = owner;
Ref<Resource> owner_res = ResourceLoader::load(String(owner_path));
if (Object::cast_to<PackedScene>(owner_res.ptr())) {
Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
owner_scene_node = owner_packed_scene->instantiate();
break;
}
}
return owner_scene_node;
}
void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
String path = get_file_path(p_params.textDocument.uri);
String call_hint;
@ -644,7 +614,7 @@ void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<S
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
if (parser) {
Node *owner_scene_node = _get_owner_scene_node(path);
Node *owner_scene_node = GDScriptLanguageProtocol::get_singleton()->get_scene_cache()->get(path);
Array stack;
Node *current = nullptr;
@ -669,10 +639,7 @@ void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<S
}
String code = parser->get_text_for_completion(p_params.position);
GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
if (owner_scene_node) {
memdelete(owner_scene_node);
}
GDScriptEditorLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
}
}
@ -683,46 +650,45 @@ const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocu
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
if (parser) {
String symbol_identifier = p_symbol_name;
if (symbol_identifier.get_slice_count("(") > 0) {
symbol_identifier = symbol_identifier.get_slicec('(', 0);
String symbol_name = p_symbol_name;
if (symbol_name.get_slice_count("(") > 0) {
symbol_name = symbol_name.get_slicec('(', 0);
}
LSP::Position pos = p_doc_pos.position;
if (symbol_identifier.is_empty()) {
if (symbol_name.is_empty()) {
LSP::Range range;
symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
symbol_name = parser->get_symbol_name_under_position(p_doc_pos.position, range);
pos.character = range.end.character;
}
if (!symbol_identifier.is_empty()) {
if (ScriptServer::is_global_class(symbol_identifier)) {
String class_path = ScriptServer::get_global_class_path(symbol_identifier);
if (!symbol_name.is_empty()) {
if (ScriptServer::is_global_class(symbol_name)) {
String class_path = ScriptServer::get_global_class_path(symbol_name);
symbol = get_script_symbol(class_path);
} else {
ScriptLanguage::LookupResult ret;
if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
symbol_identifier = "_init";
EditorLanguage::LookupResult ret;
// TODO: `lookup_code` should already account for this. We might be able to simplify code here.
if (symbol_name == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
symbol_name = "_init";
}
if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
if (OK == GDScriptEditorLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_name, p_func_required), symbol_name, path, nullptr, ret)) {
if (ret.location >= 0) {
String target_script_path = path;
if (ret.script.is_valid()) {
target_script_path = ret.script->get_path();
} else if (!ret.script_path.is_empty()) {
if (!ret.script_path.is_empty()) {
target_script_path = ret.script_path;
}
const ExtendGDScriptParser *target_parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(target_script_path);
if (target_parser) {
symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_name);
if (symbol) {
switch (symbol->kind) {
case LSP::SymbolKind::Function: {
if (symbol->name != symbol_identifier) {
symbol = get_parameter_symbol(symbol, symbol_identifier);
if (symbol->name != symbol_name) {
symbol = get_parameter_symbol(symbol, symbol_name);
}
} break;
}
@ -730,15 +696,15 @@ const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocu
}
} else {
String member = ret.class_member;
if (member.is_empty() && symbol_identifier != ret.class_name) {
member = symbol_identifier;
if (member.is_empty() && symbol_name != ret.class_name) {
member = symbol_name;
}
symbol = get_native_symbol(ret.class_name, member);
}
} else {
symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
symbol = get_local_symbol_at(parser, symbol_name, p_doc_pos.position);
if (!symbol) {
symbol = parser->get_member_symbol(symbol_identifier);
symbol = parser->get_member_symbol(symbol_name);
}
}
}
@ -804,7 +770,8 @@ Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams
if (symbol->kind == LSP::SymbolKind::Method || symbol->kind == LSP::SymbolKind::Function) {
LSP::SignatureInformation signature_info;
signature_info.label = symbol->detail;
signature_info.documentation = symbol->render();
const HashSet<String> &allowed_tags = GDScriptLanguageProtocol::get_singleton()->get_client_markdown_allowed_html_tags();
signature_info.documentation = symbol->render(allowed_tags);
for (int i = 0; i < symbol->children.size(); i++) {
const LSP::DocumentSymbol &arg = symbol->children[i];

View file

@ -30,22 +30,18 @@
#pragma once
#include "core/error/error_macros.h"
#include "gdscript_extend_parser.h"
#include "godot_lsp.h"
#include "core/error/error_macros.h"
#include "core/variant/variant.h"
#include "editor/file_system/editor_file_system.h"
class GDScriptWorkspace : public RefCounted {
GDCLASS(GDScriptWorkspace, RefCounted);
private:
void _get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners);
Node *_get_owner_scene_node(String p_path);
#ifndef DISABLE_DEPRECATED
void didDeleteFiles() {}
void didDeleteFiles(const Dictionary &p_params) {}
Error parse_script(const String &p_path, const String &p_content) {
WARN_DEPRECATED;
return Error::FAILED;
@ -76,9 +72,6 @@ protected:
void apply_new_signal(Object *obj, String function, PackedStringArray args);
public:
String root;
String root_uri;
HashMap<StringName, ClassMembers> native_members;
public:

View file

@ -34,12 +34,21 @@
#include "core/object/class_db.h"
#include "core/templates/list.h"
// Enable additional LSP related logging.
//#define DEBUG_LSP
#ifdef DEBUG_LSP
#define LOG_LSP(...) print_line("[ LSP -", __FILE__, ":", __LINE__, "-", __func__, "] -", ##__VA_ARGS__)
#else
#define LOG_LSP(...)
#endif
namespace LSP {
typedef String DocumentUri;
/** Format BBCode documentation from DocData to markdown */
static String marked_documentation(const String &p_bbcode);
static String marked_documentation(const String &p_bbcode, const HashSet<String> &p_allowed_html_tags);
/**
* Text documents are identified using a URI. On the protocol level, URIs are passed as strings.
@ -101,6 +110,9 @@ struct Position {
dict["character"] = character;
return dict;
}
Position() = default;
Position(int p_line, int p_character) : line(p_line), character(p_character) {}
};
/**
@ -151,6 +163,10 @@ struct Range {
dict["end"] = end.to_json();
return dict;
}
Range() = default;
Range(Position p_start, Position p_end) : start(p_start), end(p_end) {}
Range(int p_start_line, int p_start_column, int p_end_line, int p_end_column) : start(p_start_line, p_start_column), end(p_end_line, p_end_column) {}
};
/**
@ -310,6 +326,13 @@ struct TextEdit {
* empty string.
*/
String newText;
_FORCE_INLINE_ Dictionary to_json() const {
Dictionary dict;
dict["newText"] = newText;
dict["range"] = range.to_json();
return dict;
}
};
/**
@ -490,22 +513,6 @@ struct SignatureHelpOptions {
}
};
/**
* Code Lens options.
*/
struct CodeLensOptions {
/**
* Code lens has a resolve provider as well.
*/
bool resolveProvider = false;
Dictionary to_json() {
Dictionary dict;
dict["resolveProvider"] = resolveProvider;
return dict;
}
};
/**
* Rename options
*/
@ -570,24 +577,6 @@ struct SaveOptions {
}
};
/**
* Color provider options.
*/
struct ColorProviderOptions {
Dictionary to_json() {
return Dictionary();
}
};
/**
* Folding range provider options.
*/
struct FoldingRangeProviderOptions {
Dictionary to_json() {
return Dictionary();
}
};
struct TextDocumentSyncOptions {
/**
* Open and close notifications are sent to the server. If omitted open close notification should not
@ -1067,9 +1056,19 @@ struct CompletionItem {
if (!insertText.is_empty()) {
dict["insertText"] = insertText;
}
if (insertTextFormat) {
dict["insertTextFormat"] = insertTextFormat;
}
if (!textEdit.newText.is_empty()) {
dict["textEdit"] = textEdit.to_json();
}
if (resolved) {
dict["detail"] = detail;
dict["documentation"] = documentation.to_json();
if (!detail.is_empty()) {
dict["detail"] = detail;
}
if (!documentation.value.is_empty()) {
dict["documentation"] = documentation.to_json();
}
dict["deprecated"] = deprecated;
dict["preselect"] = preselect;
if (!sortText.is_empty()) {
@ -1122,6 +1121,7 @@ struct CompletionItem {
if (p_dict.has("insertText")) {
insertText = p_dict["insertText"];
}
insertTextFormat = p_dict.get("insertTextFormat", 0);
if (p_dict.has("data")) {
data = p_dict["data"];
}
@ -1272,61 +1272,19 @@ struct DocumentSymbol {
return dict;
}
_FORCE_INLINE_ MarkupContent render() const {
_FORCE_INLINE_ MarkupContent render(const HashSet<String> &p_allowed_html_tags) const {
MarkupContent markdown;
if (detail.length()) {
markdown.value = "\t" + detail + "\n\n";
}
if (documentation.length()) {
markdown.value += marked_documentation(documentation) + "\n\n";
markdown.value += marked_documentation(documentation, p_allowed_html_tags) + "\n\n";
}
if (script_path.length()) {
markdown.value += "Defined in [" + script_path + "](" + uri + ")";
}
return markdown;
}
_FORCE_INLINE_ CompletionItem make_completion_item(bool resolved = false) const {
LSP::CompletionItem item;
item.label = name;
if (resolved) {
item.documentation = render();
}
switch (kind) {
case LSP::SymbolKind::Enum:
item.kind = LSP::CompletionItemKind::Enum;
break;
case LSP::SymbolKind::Class:
item.kind = LSP::CompletionItemKind::Class;
break;
case LSP::SymbolKind::Property:
item.kind = LSP::CompletionItemKind::Property;
break;
case LSP::SymbolKind::Method:
case LSP::SymbolKind::Function:
item.kind = LSP::CompletionItemKind::Method;
break;
case LSP::SymbolKind::Event:
item.kind = LSP::CompletionItemKind::Event;
break;
case LSP::SymbolKind::Constant:
item.kind = LSP::CompletionItemKind::Constant;
break;
case LSP::SymbolKind::Variable:
item.kind = LSP::CompletionItemKind::Variable;
break;
case LSP::SymbolKind::File:
item.kind = LSP::CompletionItemKind::File;
break;
default:
item.kind = LSP::CompletionItemKind::Text;
break;
}
return item;
}
};
struct ApplyWorkspaceEditParams {
@ -1766,7 +1724,7 @@ struct ServerCapabilities {
/**
* The server provides document highlight support.
*/
bool documentHighlightProvider = false;
bool documentHighlightProvider = true;
/**
* The server provides document symbol support.
@ -1790,11 +1748,6 @@ struct ServerCapabilities {
*/
bool codeActionProvider = false;
/**
* The server provides code lens.
*/
CodeLensOptions codeLensProvider;
/**
* The server provides document formatting.
*/
@ -1822,20 +1775,6 @@ struct ServerCapabilities {
*/
DocumentLinkOptions documentLinkProvider;
/**
* The server provides color provider support.
*
* Since 3.6.0
*/
ColorProviderOptions colorProvider;
/**
* The server provides folding provider support.
*
* Since 3.10.0
*/
FoldingRangeProviderOptions foldingRangeProvider;
/**
* The server provides go to declaration support.
*
@ -1855,12 +1794,9 @@ struct ServerCapabilities {
signatureHelpProvider.triggerCharacters.push_back(",");
signatureHelpProvider.triggerCharacters.push_back("(");
dict["signatureHelpProvider"] = signatureHelpProvider.to_json();
//dict["codeLensProvider"] = codeLensProvider.to_json();
dict["documentOnTypeFormattingProvider"] = documentOnTypeFormattingProvider.to_json();
dict["renameProvider"] = renameProvider.to_json();
dict["documentLinkProvider"] = documentLinkProvider.to_json();
dict["colorProvider"] = false; // colorProvider.to_json();
dict["foldingRangeProvider"] = false; //foldingRangeProvider.to_json();
dict["executeCommandProvider"] = executeCommandProvider.to_json();
dict["hoverProvider"] = hoverProvider;
dict["definitionProvider"] = definitionProvider;
@ -1924,7 +1860,8 @@ struct GodotCapabilities {
};
/** Format BBCode documentation from DocData to markdown */
static String marked_documentation(const String &p_bbcode) {
static String marked_documentation(const String &p_bbcode, const HashSet<String> &p_allowed_html_tags) {
bool span_allowed = p_allowed_html_tags.has("span");
String markdown = p_bbcode.strip_edges();
Vector<String> lines = markdown.split("\n");
@ -2004,7 +1941,6 @@ static String marked_documentation(const String &p_bbcode) {
line = line.replace("[center]", "");
line = line.replace("[/center]", "");
line = line.replace("[/font]", "");
line = line.replace("[/color]", "");
line = line.replace("[/img]", "");
// Convert remaining simple bracketed class names to backticks and literal brackets.
@ -2077,6 +2013,35 @@ static String marked_documentation(const String &p_bbcode) {
pos += replacement.length();
}
// Convert [color] BBCode to <span>, if the client is capable of rendering it, strip it otherwise.
pos = 0;
while ((pos = line.find("[color=", pos)) != -1) {
constexpr int COLOR_OPEN_TAG_LENGTH = 7; // Length of "[color=".
constexpr int COLOR_CLOSE_TAG_LENGTH = 8; // Length of "[/color]".
int color_end = line.find_char(']', pos);
int close_start = line.find("[/color]", color_end);
if (color_end == -1 || close_start == -1) {
break;
}
String text = line.substr(color_end + 1, close_start - color_end - 1);
String replacement;
if (span_allowed) {
const String color = line.substr(pos + COLOR_OPEN_TAG_LENGTH, color_end - pos - COLOR_OPEN_TAG_LENGTH).strip_edges();
if (Color::html_is_valid(color)) {
replacement = "<span style=\"color:" + color + "\">" + text + "</span>";
} else if (int named_color_index = Color::find_named_color(color); named_color_index != -1) {
replacement = "<span style=\"color:#" + Color::get_named_color(named_color_index).to_html(false) + "\">" + text + "</span>";
}
}
// If no span replacement was produced (client can't render spans, or invalid color), just keep the inner text.
if (replacement.is_empty()) {
replacement = text;
}
line = line.substr(0, pos) + replacement + line.substr(close_start + COLOR_CLOSE_TAG_LENGTH);
pos += replacement.length();
}
// Replace the various link types with inline code ([class MyNode] to `MyNode`).
// Uses a while loop because there can occasionally be multiple links of the same type in a single line.
const Vector<String> link_start_patterns = {
@ -2098,10 +2063,10 @@ static String marked_documentation(const String &p_bbcode) {
}
}
// Remove tags with attributes like [color=red], as they don't have a direct Markdown
// Remove tags with attributes like [font=Arial], as they don't have a direct Markdown
// equivalent supported by external tools.
const String attribute_tags[] = {
"color", "font", "img"
"font", "img"
};
for (const String &tag_name : attribute_tags) {
int tag_pos = 0;
@ -2123,4 +2088,26 @@ static String marked_documentation(const String &p_bbcode) {
}
return markdown;
}
/**
* A document highlight is a range inside a text document which deserves
* special attention. Usually a document highlight is visualized by changing
* the background color of its range.
*/
struct DocumentHighlight {
/**
* The range this highlight applies to.
*/
Range range;
_FORCE_INLINE_ Dictionary to_json() const {
Dictionary dict;
dict["range"] = range.to_json();
return dict;
}
_FORCE_INLINE_ void load(const Dictionary &p_params) {
range.load(p_params["range"]);
}
};
} // namespace LSP

View file

@ -0,0 +1,186 @@
/**************************************************************************/
/* scene_cache.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "scene_cache.h"
#include "godot_lsp.h"
#include "core/io/resource_loader.h"
#include "editor/file_system/editor_file_system.h"
#include "scene/resources/packed_scene.h"
void SceneCache::_get_owner_paths(EditorFileSystemDirectory *p_dir, const String &p_script_path, LocalVector<String> &r_owner_paths) {
if (!p_dir) {
return;
}
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
_get_owner_paths(p_dir->get_subdir(i), p_script_path, r_owner_paths);
}
for (int i = 0; i < p_dir->get_file_count(); i++) {
if (p_dir->get_file_deps(i).has(p_script_path)) {
r_owner_paths.push_back(p_dir->get_file_path(i));
}
}
}
void SceneCache::_finalize_scene_load() {
ERR_FAIL_COND(current_loaded_owner.is_empty() || script_path_queue.is_empty());
Ref<PackedScene> scene_res = ResourceLoader::load_threaded_get(current_loaded_owner);
if (scene_res.is_valid()) {
cache[script_path_queue[0]] = scene_res->instantiate();
} else {
cache[script_path_queue[0]] = nullptr;
}
LOG_LSP("Scene cached for script:", script_path_queue[0]);
LOG_LSP("pending_script_queue length:", script_path_queue.size() - 1);
script_path_queue.remove_at(0);
current_loaded_owner = String();
}
void SceneCache::poll() {
if (current_loaded_owner.is_empty()) {
// No load ongoing, start the next one.
if (EditorFileSystem::get_singleton()->is_scanning() || script_path_queue.is_empty()) {
return;
}
LocalVector<String> owners;
_get_owner_paths(EditorFileSystem::get_singleton()->get_filesystem(), script_path_queue[0], owners);
for (const String &owner : owners) {
if (ResourceLoader::load_threaded_request(owner) == Error::OK) {
current_loaded_owner = owner;
LOG_LSP("Scene load started for:", current_loaded_owner);
break;
}
}
if (current_loaded_owner.is_empty()) {
cache[script_path_queue[0]] = nullptr;
LOG_LSP("No scene found for script:", script_path_queue[0]);
script_path_queue.remove_at(0);
LOG_LSP("pending_script_queue length:", script_path_queue.size());
}
} else {
ERR_FAIL_COND(script_path_queue.is_empty());
// There is an ongoing load. Check the status.
ResourceLoader::ThreadLoadStatus status = ResourceLoader::load_threaded_get_status(current_loaded_owner);
if (status == ResourceLoader::THREAD_LOAD_IN_PROGRESS) {
return;
}
if (status == ResourceLoader::THREAD_LOAD_LOADED) {
_finalize_scene_load();
} else {
LOG_LSP("Scene load failure for:", current_loaded_owner);
cache[script_path_queue[0]] = nullptr;
script_path_queue.remove_at(0);
current_loaded_owner = String();
}
}
}
Node *SceneCache::get(const String &p_script_path) {
if (!script_path_queue.is_empty() && script_path_queue[0] == p_script_path && !current_loaded_owner.is_empty()) {
_finalize_scene_load();
} else {
script_path_queue.erase(p_script_path);
}
if (Node **entry = cache.getptr(p_script_path)) {
return *entry;
}
// Fallback to blocking load. This could happen if the open request was only recently sent.
// TODO: This could also happen when multiple clients are connected.
LocalVector<String> owners;
_get_owner_paths(EditorFileSystem::get_singleton()->get_filesystem(), p_script_path, owners);
for (const String &owner : owners) {
Ref<PackedScene> scene = ResourceLoader::load(owner);
if (scene.is_valid()) {
Node *instance = scene->instantiate();
cache[p_script_path] = instance;
return instance;
}
}
cache[p_script_path] = nullptr;
return nullptr;
}
void SceneCache::request_load(const String &p_script_path) {
if (!cache.has(p_script_path) && !script_path_queue.has(p_script_path)) {
script_path_queue.push_back(p_script_path);
LOG_LSP("Scene load requested for:", p_script_path);
LOG_LSP("pending_script_queue length:", script_path_queue.size());
}
}
void SceneCache::unload(const String &p_script_path) {
if (!script_path_queue.is_empty() && script_path_queue[0] == p_script_path && !current_loaded_owner.is_empty()) {
_ALLOW_DISCARD_ ResourceLoader::load_threaded_get(current_loaded_owner);
script_path_queue.remove_at(0);
current_loaded_owner = String();
} else {
script_path_queue.erase(p_script_path);
}
if (!cache.has(p_script_path)) {
return;
}
memdelete_notnull(cache[p_script_path]);
cache.erase(p_script_path);
LOG_LSP("Cache cleared for path:", p_script_path);
}
void SceneCache::clear() {
if (!current_loaded_owner.is_empty()) {
_ALLOW_DISCARD_ ResourceLoader::load_threaded_get(current_loaded_owner);
current_loaded_owner = String();
}
script_path_queue.clear();
for (const KeyValue<String, Node *> &E : cache) {
memdelete_notnull(E.value);
}
cache.clear();
LOG_LSP("Cache cleared.");
}

View file

@ -0,0 +1,65 @@
/**************************************************************************/
/* scene_cache.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/string/ustring.h"
#include "core/templates/hash_map.h"
#include "core/templates/local_vector.h"
class Node;
class EditorFileSystemDirectory;
class PackedScene;
/**
* Used to load and cache scene instances for LSP autocompletion.
*
* This implementation is not thread safe.
*/
class SceneCache {
// Always contains the path to the scene which is currently loaded via the `ResourceLoader`.
// If this is not empty, `script_path_queue` must have at least one element.
String current_loaded_owner;
LocalVector<String> script_path_queue;
HashMap<String, Node *> cache;
void _get_owner_paths(EditorFileSystemDirectory *p_dir, const String &p_script_path, LocalVector<String> &r_owner_paths);
void _finalize_scene_load();
public:
void poll();
void clear();
void request_load(const String &p_script_path);
void unload(const String &p_script_path);
Node *get(const String &p_script_path);
};