Merge commit '88a2e4976b' as 'engine'
This commit is contained in:
commit
4587afe78c
13991 changed files with 7801538 additions and 0 deletions
|
|
@ -0,0 +1,980 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_extend_parser.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 "gdscript_extend_parser.h"
|
||||
|
||||
#include "../gdscript.h"
|
||||
#include "../gdscript_analyzer.h"
|
||||
#include "gdscript_language_protocol.h"
|
||||
#include "gdscript_workspace.h"
|
||||
|
||||
LSP::Position GodotPosition::to_lsp() const {
|
||||
LSP::Position res;
|
||||
res.line = line - 1;
|
||||
res.character = column - 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 {
|
||||
LSP::Range res;
|
||||
res.start = start.to_lsp();
|
||||
res.end = end.to_lsp();
|
||||
return res;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::update_diagnostics() {
|
||||
diagnostics.clear();
|
||||
|
||||
const List<ParserError> &parser_errors = get_errors();
|
||||
for (const ParserError &error : parser_errors) {
|
||||
LSP::Diagnostic diagnostic;
|
||||
diagnostic.severity = LSP::DiagnosticSeverity::Error;
|
||||
diagnostic.message = error.message;
|
||||
diagnostic.source = "gdscript";
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
const List<GDScriptWarning> &parser_warnings = get_warnings();
|
||||
for (const GDScriptWarning &warning : parser_warnings) {
|
||||
LSP::Diagnostic diagnostic;
|
||||
diagnostic.severity = LSP::DiagnosticSeverity::Warning;
|
||||
diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message();
|
||||
diagnostic.source = "gdscript";
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::update_symbols() {
|
||||
members.clear();
|
||||
|
||||
if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
|
||||
parse_class_symbol(gdclass, class_symbol);
|
||||
|
||||
for (int i = 0; i < class_symbol.children.size(); i++) {
|
||||
const LSP::DocumentSymbol &symbol = class_symbol.children[i];
|
||||
members.insert(symbol.name, &symbol);
|
||||
|
||||
// Cache level one inner classes.
|
||||
if (symbol.kind == LSP::SymbolKind::Class) {
|
||||
ClassMembers inner_class;
|
||||
for (int j = 0; j < symbol.children.size(); j++) {
|
||||
const LSP::DocumentSymbol &s = symbol.children[j];
|
||||
inner_class.insert(s.name, &s);
|
||||
}
|
||||
inner_classes.insert(symbol.name, inner_class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::update_document_links(const String &p_code) {
|
||||
document_links.clear();
|
||||
|
||||
GDScriptTokenizerText scr_tokenizer;
|
||||
Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES);
|
||||
scr_tokenizer.set_source_code(p_code);
|
||||
while (true) {
|
||||
GDScriptTokenizer::Token token = scr_tokenizer.scan();
|
||||
if (token.type == GDScriptTokenizer::Token::TK_EOF) {
|
||||
break;
|
||||
} else if (token.type == GDScriptTokenizer::Token::LITERAL) {
|
||||
const Variant &const_val = token.literal;
|
||||
if (const_val.get_type() == Variant::STRING) {
|
||||
String scr_path = const_val;
|
||||
if (scr_path.is_relative_path()) {
|
||||
scr_path = get_path().get_base_dir().path_join(scr_path).simplify_path();
|
||||
}
|
||||
bool exists = fs->file_exists(scr_path);
|
||||
|
||||
if (exists) {
|
||||
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();
|
||||
document_links.push_back(link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, LSP::DocumentSymbol &r_symbol) {
|
||||
const String uri = get_uri();
|
||||
|
||||
r_symbol.uri = uri;
|
||||
r_symbol.script_path = path;
|
||||
r_symbol.children.clear();
|
||||
r_symbol.name = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
|
||||
if (r_symbol.name.is_empty()) {
|
||||
r_symbol.name = path.get_file();
|
||||
}
|
||||
r_symbol.kind = LSP::SymbolKind::Class;
|
||||
r_symbol.deprecated = false;
|
||||
r_symbol.range = range_of_node(p_class);
|
||||
if (p_class->identifier) {
|
||||
r_symbol.selectionRange = range_of_node(p_class->identifier);
|
||||
} else {
|
||||
// No meaningful `selectionRange`, but we must ensure that it is inside of `range`.
|
||||
r_symbol.selectionRange.start = r_symbol.range.start;
|
||||
r_symbol.selectionRange.end = r_symbol.range.start;
|
||||
}
|
||||
r_symbol.detail = "class " + r_symbol.name;
|
||||
{
|
||||
String doc = p_class->doc_data.brief;
|
||||
if (!p_class->doc_data.description.is_empty()) {
|
||||
doc += "\n\n" + p_class->doc_data.description;
|
||||
}
|
||||
|
||||
if (!p_class->doc_data.tutorials.is_empty()) {
|
||||
doc += "\n";
|
||||
for (const Pair<String, String> &tutorial : p_class->doc_data.tutorials) {
|
||||
if (tutorial.first.is_empty()) {
|
||||
doc += vformat("\n@tutorial: %s", tutorial.second);
|
||||
} else {
|
||||
doc += vformat("\n@tutorial(%s): %s", tutorial.first, tutorial.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
r_symbol.documentation = doc;
|
||||
}
|
||||
|
||||
for (int i = 0; i < p_class->members.size(); i++) {
|
||||
const ClassNode::Member &m = p_class->members[i];
|
||||
|
||||
switch (m.type) {
|
||||
case ClassNode::Member::VARIABLE: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = m.variable->identifier->name;
|
||||
symbol.kind = m.variable->property == VariableNode::PROP_NONE ? LSP::SymbolKind::Variable : LSP::SymbolKind::Property;
|
||||
symbol.deprecated = false;
|
||||
symbol.range = range_of_node(m.variable);
|
||||
symbol.selectionRange = range_of_node(m.variable->identifier);
|
||||
if (m.variable->exported) {
|
||||
symbol.detail += "@export ";
|
||||
}
|
||||
symbol.detail += "var " + m.variable->identifier->name;
|
||||
if (m.get_datatype().is_hard_type()) {
|
||||
symbol.detail += ": " + m.get_datatype().to_string();
|
||||
}
|
||||
if (m.variable->initializer != nullptr && m.variable->initializer->is_constant) {
|
||||
symbol.detail += " = " + m.variable->initializer->reduced_value.to_json_string();
|
||||
}
|
||||
|
||||
symbol.documentation = m.variable->doc_data.description;
|
||||
symbol.uri = uri;
|
||||
symbol.script_path = path;
|
||||
|
||||
if (m.variable->initializer && m.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
|
||||
GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)m.variable->initializer;
|
||||
LSP::DocumentSymbol lambda;
|
||||
parse_function_symbol(lambda_node->function, lambda);
|
||||
// Merge lambda into current variable.
|
||||
symbol.children.append_array(lambda.children);
|
||||
}
|
||||
|
||||
if (m.variable->getter && m.variable->getter->type == GDScriptParser::Node::FUNCTION) {
|
||||
LSP::DocumentSymbol get_symbol;
|
||||
parse_function_symbol(m.variable->getter, get_symbol);
|
||||
get_symbol.local = true;
|
||||
symbol.children.push_back(get_symbol);
|
||||
}
|
||||
if (m.variable->setter && m.variable->setter->type == GDScriptParser::Node::FUNCTION) {
|
||||
LSP::DocumentSymbol set_symbol;
|
||||
parse_function_symbol(m.variable->setter, set_symbol);
|
||||
set_symbol.local = true;
|
||||
symbol.children.push_back(set_symbol);
|
||||
}
|
||||
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::CONSTANT: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
|
||||
symbol.name = m.constant->identifier->name;
|
||||
symbol.kind = LSP::SymbolKind::Constant;
|
||||
symbol.deprecated = false;
|
||||
symbol.range = range_of_node(m.constant);
|
||||
symbol.selectionRange = range_of_node(m.constant->identifier);
|
||||
symbol.documentation = m.constant->doc_data.description;
|
||||
symbol.uri = uri;
|
||||
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();
|
||||
}
|
||||
|
||||
const Variant &default_value = m.constant->initializer->reduced_value;
|
||||
String value_text;
|
||||
if (default_value.get_type() == Variant::OBJECT) {
|
||||
Ref<Resource> res = default_value;
|
||||
if (res.is_valid() && !res->get_path().is_empty()) {
|
||||
value_text = "preload(\"" + res->get_path() + "\")";
|
||||
if (symbol.documentation.is_empty()) {
|
||||
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(res->get_path());
|
||||
if (parser) {
|
||||
symbol.documentation = parser->class_symbol.documentation;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
value_text = default_value.to_json_string();
|
||||
}
|
||||
} else {
|
||||
value_text = default_value.to_json_string();
|
||||
}
|
||||
if (!value_text.is_empty()) {
|
||||
symbol.detail += " = " + value_text;
|
||||
}
|
||||
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::SIGNAL: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = m.signal->identifier->name;
|
||||
symbol.kind = LSP::SymbolKind::Event;
|
||||
symbol.deprecated = false;
|
||||
symbol.range = range_of_node(m.signal);
|
||||
symbol.selectionRange = range_of_node(m.signal->identifier);
|
||||
symbol.documentation = m.signal->doc_data.description;
|
||||
symbol.uri = uri;
|
||||
symbol.script_path = path;
|
||||
symbol.detail = "signal " + String(m.signal->identifier->name) + "(";
|
||||
for (int j = 0; j < m.signal->parameters.size(); j++) {
|
||||
if (j > 0) {
|
||||
symbol.detail += ", ";
|
||||
}
|
||||
symbol.detail += m.signal->parameters[j]->identifier->name;
|
||||
}
|
||||
symbol.detail += ")";
|
||||
|
||||
for (GDScriptParser::ParameterNode *param : m.signal->parameters) {
|
||||
LSP::DocumentSymbol param_symbol;
|
||||
param_symbol.name = param->identifier->name;
|
||||
param_symbol.kind = LSP::SymbolKind::Variable;
|
||||
param_symbol.deprecated = false;
|
||||
param_symbol.local = true;
|
||||
param_symbol.range = range_of_node(param);
|
||||
param_symbol.selectionRange = range_of_node(param->identifier);
|
||||
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();
|
||||
}
|
||||
symbol.children.push_back(param_symbol);
|
||||
}
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::ENUM_VALUE: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
|
||||
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();
|
||||
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;
|
||||
symbol.script_path = path;
|
||||
|
||||
symbol.detail = symbol.name + " = " + itos(m.enum_value.value);
|
||||
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::ENUM: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = m.m_enum->identifier->name;
|
||||
symbol.kind = LSP::SymbolKind::Enum;
|
||||
symbol.range = range_of_node(m.m_enum);
|
||||
symbol.selectionRange = range_of_node(m.m_enum->identifier);
|
||||
symbol.documentation = m.m_enum->doc_data.description;
|
||||
symbol.uri = uri;
|
||||
symbol.script_path = path;
|
||||
|
||||
symbol.detail = "enum " + String(m.m_enum->identifier->name) + "{";
|
||||
for (int j = 0; j < m.m_enum->values.size(); j++) {
|
||||
if (j > 0) {
|
||||
symbol.detail += ", ";
|
||||
}
|
||||
symbol.detail += String(m.m_enum->values[j].identifier->name) + " = " + itos(m.m_enum->values[j].value);
|
||||
}
|
||||
symbol.detail += "}";
|
||||
|
||||
for (GDScriptParser::EnumNode::Value value : m.m_enum->values) {
|
||||
LSP::DocumentSymbol child;
|
||||
|
||||
child.name = value.identifier->name;
|
||||
child.kind = LSP::SymbolKind::EnumMember;
|
||||
child.deprecated = false;
|
||||
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;
|
||||
child.script_path = path;
|
||||
|
||||
child.detail = child.name + " = " + itos(value.value);
|
||||
|
||||
symbol.children.push_back(child);
|
||||
}
|
||||
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::FUNCTION: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
parse_function_symbol(m.function, symbol);
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::CLASS: {
|
||||
LSP::DocumentSymbol symbol;
|
||||
parse_class_symbol(m.m_class, symbol);
|
||||
r_symbol.children.push_back(symbol);
|
||||
} break;
|
||||
case ClassNode::Member::GROUP:
|
||||
break; // No-op, but silences warnings.
|
||||
case ClassNode::Member::UNDEFINED:
|
||||
break; // Unreachable.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, LSP::DocumentSymbol &r_symbol) {
|
||||
const String uri = get_uri();
|
||||
|
||||
bool is_named = p_func->identifier != nullptr;
|
||||
|
||||
r_symbol.name = is_named ? p_func->identifier->name : "";
|
||||
r_symbol.kind = (p_func->is_static || p_func->source_lambda != nullptr) ? LSP::SymbolKind::Function : LSP::SymbolKind::Method;
|
||||
r_symbol.detail = "func";
|
||||
if (is_named) {
|
||||
r_symbol.detail += " " + String(p_func->identifier->name);
|
||||
}
|
||||
r_symbol.detail += "(";
|
||||
r_symbol.deprecated = false;
|
||||
r_symbol.range = range_of_node(p_func);
|
||||
if (is_named) {
|
||||
r_symbol.selectionRange = range_of_node(p_func->identifier);
|
||||
} else {
|
||||
r_symbol.selectionRange.start = r_symbol.selectionRange.end = r_symbol.range.start;
|
||||
}
|
||||
r_symbol.documentation = p_func->doc_data.description;
|
||||
r_symbol.uri = uri;
|
||||
r_symbol.script_path = path;
|
||||
|
||||
String parameters;
|
||||
for (int i = 0; i < p_func->parameters.size(); i++) {
|
||||
const ParameterNode *parameter = p_func->parameters[i];
|
||||
if (i > 0) {
|
||||
parameters += ", ";
|
||||
}
|
||||
parameters += String(parameter->identifier->name);
|
||||
if (parameter->get_datatype().is_hard_type()) {
|
||||
parameters += ": " + parameter->get_datatype().to_string();
|
||||
}
|
||||
if (parameter->initializer != nullptr) {
|
||||
parameters += " = " + parameter->initializer->reduced_value.to_json_string();
|
||||
}
|
||||
}
|
||||
if (p_func->is_vararg()) {
|
||||
if (!p_func->parameters.is_empty()) {
|
||||
parameters += ", ";
|
||||
}
|
||||
const ParameterNode *rest_param = p_func->rest_parameter;
|
||||
parameters += "..." + rest_param->identifier->name + ": " + rest_param->get_datatype().to_string();
|
||||
}
|
||||
r_symbol.detail += parameters + ")";
|
||||
|
||||
const DataType return_type = p_func->get_datatype();
|
||||
if (return_type.is_hard_type()) {
|
||||
if (return_type.kind == DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
|
||||
r_symbol.detail += " -> void";
|
||||
} else {
|
||||
r_symbol.detail += " -> " + return_type.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
List<GDScriptParser::SuiteNode *> function_nodes;
|
||||
|
||||
List<GDScriptParser::Node *> node_stack;
|
||||
node_stack.push_back(p_func->body);
|
||||
|
||||
while (!node_stack.is_empty()) {
|
||||
GDScriptParser::Node *node = node_stack.front()->get();
|
||||
node_stack.pop_front();
|
||||
|
||||
switch (node->type) {
|
||||
case GDScriptParser::TypeNode::IF: {
|
||||
GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node;
|
||||
node_stack.push_back(if_node->true_block);
|
||||
if (if_node->false_block) {
|
||||
node_stack.push_back(if_node->false_block);
|
||||
}
|
||||
} break;
|
||||
|
||||
case GDScriptParser::TypeNode::FOR: {
|
||||
GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node;
|
||||
node_stack.push_back(for_node->loop);
|
||||
} break;
|
||||
|
||||
case GDScriptParser::TypeNode::WHILE: {
|
||||
GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node;
|
||||
node_stack.push_back(while_node->loop);
|
||||
} break;
|
||||
|
||||
case GDScriptParser::TypeNode::MATCH: {
|
||||
GDScriptParser::MatchNode *match_node = (GDScriptParser::MatchNode *)node;
|
||||
for (GDScriptParser::MatchBranchNode *branch_node : match_node->branches) {
|
||||
node_stack.push_back(branch_node);
|
||||
}
|
||||
} break;
|
||||
|
||||
case GDScriptParser::TypeNode::MATCH_BRANCH: {
|
||||
GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node;
|
||||
node_stack.push_back(match_node->block);
|
||||
} break;
|
||||
|
||||
case GDScriptParser::TypeNode::SUITE: {
|
||||
GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node;
|
||||
function_nodes.push_back(suite_node);
|
||||
for (int i = 0; i < suite_node->statements.size(); ++i) {
|
||||
node_stack.push_back(suite_node->statements[i]);
|
||||
}
|
||||
} break;
|
||||
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) {
|
||||
const GDScriptParser::SuiteNode *suite_node = N->get();
|
||||
for (int i = 0; i < suite_node->locals.size(); i++) {
|
||||
const SuiteNode::Local &local = suite_node->locals[i];
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = local.name;
|
||||
symbol.kind = local.type == SuiteNode::Local::CONSTANT ? LSP::SymbolKind::Constant : LSP::SymbolKind::Variable;
|
||||
switch (local.type) {
|
||||
case SuiteNode::Local::CONSTANT:
|
||||
symbol.range = range_of_node(local.constant);
|
||||
symbol.selectionRange = range_of_node(local.constant->identifier);
|
||||
break;
|
||||
case SuiteNode::Local::VARIABLE:
|
||||
symbol.range = range_of_node(local.variable);
|
||||
symbol.selectionRange = range_of_node(local.variable->identifier);
|
||||
if (local.variable->initializer && local.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
|
||||
GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)local.variable->initializer;
|
||||
LSP::DocumentSymbol lambda;
|
||||
parse_function_symbol(lambda_node->function, lambda);
|
||||
// Merge lambda into current variable.
|
||||
// -> Only interested in new variables, not lambda itself.
|
||||
symbol.children.append_array(lambda.children);
|
||||
}
|
||||
break;
|
||||
case SuiteNode::Local::PARAMETER:
|
||||
symbol.range = range_of_node(local.parameter);
|
||||
symbol.selectionRange = range_of_node(local.parameter->identifier);
|
||||
break;
|
||||
case SuiteNode::Local::FOR_VARIABLE:
|
||||
case SuiteNode::Local::PATTERN_BIND:
|
||||
symbol.range = range_of_node(local.bind);
|
||||
symbol.selectionRange = range_of_node(local.bind);
|
||||
break;
|
||||
default:
|
||||
// Fallback.
|
||||
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;
|
||||
}
|
||||
symbol.local = true;
|
||||
symbol.uri = uri;
|
||||
symbol.script_path = path;
|
||||
symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var ";
|
||||
symbol.detail += symbol.name;
|
||||
if (local.get_datatype().is_hard_type()) {
|
||||
symbol.detail += ": " + local.get_datatype().to_string();
|
||||
}
|
||||
switch (local.type) {
|
||||
case SuiteNode::Local::CONSTANT:
|
||||
symbol.documentation = local.constant->doc_data.description;
|
||||
break;
|
||||
case SuiteNode::Local::VARIABLE:
|
||||
symbol.documentation = local.variable->doc_data.description;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
r_symbol.children.push_back(symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String ExtendGDScriptParser::get_text_for_completion(const LSP::Position &p_cursor) const {
|
||||
String longthing;
|
||||
int len = lines.size();
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (i == p_cursor.line) {
|
||||
longthing += lines[i].substr(0, p_cursor.character);
|
||||
longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
|
||||
longthing += lines[i].substr(p_cursor.character);
|
||||
} else {
|
||||
longthing += lines[i];
|
||||
}
|
||||
|
||||
if (i != len - 1) {
|
||||
longthing += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return longthing;
|
||||
}
|
||||
|
||||
String ExtendGDScriptParser::get_text_for_lookup_symbol(const LSP::Position &p_cursor, const String &p_symbol, bool p_func_required) const {
|
||||
String longthing;
|
||||
int len = lines.size();
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (i == p_cursor.line) {
|
||||
// This code tries to insert the symbol into the preexisting code. Due to using a simple
|
||||
// algorithm, the results might not always match the option semantically (e.g. different
|
||||
// identifier name). This is fine because symbol lookup will prioritize the provided
|
||||
// symbol name over the actual code. Establishing a syntactic target (e.g. identifier)
|
||||
// is usually sufficient.
|
||||
|
||||
String line = lines[i];
|
||||
String first_part = line.substr(0, p_cursor.character);
|
||||
String last_part = line.substr(p_cursor.character, lines[i].length());
|
||||
if (!p_symbol.is_empty()) {
|
||||
String left_cursor_text;
|
||||
for (int c = p_cursor.character - 1; c >= 0; c--) {
|
||||
left_cursor_text = line.substr(c, p_cursor.character - c);
|
||||
if (p_symbol.begins_with(left_cursor_text)) {
|
||||
first_part = line.substr(0, c);
|
||||
first_part += p_symbol;
|
||||
break;
|
||||
} else if (c == 0) {
|
||||
// No preexisting code that matches the option. Insert option in place.
|
||||
first_part += p_symbol;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
longthing += first_part;
|
||||
longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
|
||||
if (p_func_required) {
|
||||
longthing += "("; // Tell the parser this is a function call.
|
||||
}
|
||||
longthing += last_part;
|
||||
} else {
|
||||
longthing += lines[i];
|
||||
}
|
||||
|
||||
if (i != len - 1) {
|
||||
longthing += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return longthing;
|
||||
}
|
||||
|
||||
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
|
||||
// var member| := some_func|(some_variable|)
|
||||
// ^ ^ ^
|
||||
// | | | cursor on `some_variable, position on `)`
|
||||
// | |
|
||||
// | | cursor on `some_func`, pos on `(`
|
||||
// |
|
||||
// | cursor on `member`, pos on ` ` (space)
|
||||
// ```
|
||||
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--;
|
||||
}
|
||||
|
||||
// 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--) {
|
||||
char32_t ch = line[c];
|
||||
if (is_unicode_identifier_start(ch)) {
|
||||
last_valid_start_pos = c;
|
||||
}
|
||||
if (!is_unicode_identifier_continue(ch)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 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];
|
||||
if (!is_unicode_identifier_continue(ch)) {
|
||||
break;
|
||||
}
|
||||
end_pos = c + 1;
|
||||
}
|
||||
|
||||
if (last_valid_start_pos == -1) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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 {
|
||||
return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name) const {
|
||||
const LSP::DocumentSymbol *ret = nullptr;
|
||||
if (p_line < p_parent.range.start.line) {
|
||||
return ret;
|
||||
} else if (p_parent.range.start.line == p_line && (p_symbol_name.is_empty() || p_parent.name == p_symbol_name)) {
|
||||
return &p_parent;
|
||||
} else {
|
||||
for (int i = 0; i < p_parent.children.size(); i++) {
|
||||
ret = search_symbol_defined_at_line(p_line, p_parent.children[i], p_symbol_name);
|
||||
if (ret) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Error ExtendGDScriptParser::get_left_function_call(const LSP::Position &p_position, LSP::Position &r_func_pos, int &r_arg_index) const {
|
||||
ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
|
||||
|
||||
int bracket_stack = 0;
|
||||
int index = 0;
|
||||
|
||||
bool found = false;
|
||||
for (int l = p_position.line; l >= 0; --l) {
|
||||
String line = lines[l];
|
||||
int c = line.length() - 1;
|
||||
if (l == p_position.line) {
|
||||
c = MIN(c, p_position.character - 1);
|
||||
}
|
||||
|
||||
while (c >= 0) {
|
||||
const char32_t &character = line[c];
|
||||
if (character == ')') {
|
||||
++bracket_stack;
|
||||
} else if (character == '(') {
|
||||
--bracket_stack;
|
||||
if (bracket_stack < 0) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (bracket_stack <= 0 && character == ',') {
|
||||
++index;
|
||||
}
|
||||
--c;
|
||||
if (found) {
|
||||
r_func_pos.character = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
r_func_pos.line = l;
|
||||
r_arg_index = index;
|
||||
return OK;
|
||||
}
|
||||
}
|
||||
|
||||
return ERR_METHOD_NOT_FOUND;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line, const String &p_symbol_name) const {
|
||||
if (p_line <= 0) {
|
||||
return &class_symbol;
|
||||
}
|
||||
return search_symbol_defined_at_line(p_line, class_symbol, p_symbol_name);
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
|
||||
if (p_subclass.is_empty()) {
|
||||
const LSP::DocumentSymbol *const *ptr = members.getptr(p_name);
|
||||
if (ptr) {
|
||||
return *ptr;
|
||||
}
|
||||
} else {
|
||||
if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
|
||||
const LSP::DocumentSymbol *const *ptr = _class->getptr(p_name);
|
||||
if (ptr) {
|
||||
return *ptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const List<LSP::DocumentLink> &ExtendGDScriptParser::get_document_links() const {
|
||||
return document_links;
|
||||
}
|
||||
|
||||
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["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();
|
||||
if (p_func->parameters[i]->initializer != nullptr) {
|
||||
arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
|
||||
}
|
||||
parameters.push_back(arg);
|
||||
}
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
|
||||
func["signature"] = symbol->detail;
|
||||
func["description"] = symbol->documentation;
|
||||
}
|
||||
func["arguments"] = parameters;
|
||||
return func;
|
||||
}
|
||||
|
||||
Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
|
||||
ERR_FAIL_NULL_V(p_class, Dictionary());
|
||||
Dictionary class_api;
|
||||
|
||||
class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
|
||||
class_api["path"] = path;
|
||||
Array extends_class;
|
||||
for (int i = 0; i < p_class->extends.size(); i++) {
|
||||
extends_class.append(String(p_class->extends[i]->name));
|
||||
}
|
||||
class_api["extends_class"] = extends_class;
|
||||
class_api["extends_file"] = String(p_class->extends_path);
|
||||
class_api["icon"] = String(p_class->icon_path);
|
||||
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
|
||||
class_api["signature"] = symbol->detail;
|
||||
class_api["description"] = symbol->documentation;
|
||||
}
|
||||
|
||||
Array nested_classes;
|
||||
Array constants;
|
||||
Array class_members;
|
||||
Array signals;
|
||||
Array methods;
|
||||
Array static_functions;
|
||||
|
||||
for (int i = 0; i < p_class->members.size(); i++) {
|
||||
const ClassNode::Member &m = p_class->members[i];
|
||||
switch (m.type) {
|
||||
case ClassNode::Member::CLASS:
|
||||
nested_classes.push_back(dump_class_api(m.m_class));
|
||||
break;
|
||||
case ClassNode::Member::CONSTANT: {
|
||||
Dictionary api;
|
||||
api["name"] = m.constant->identifier->name;
|
||||
api["value"] = m.constant->initializer->reduced_value;
|
||||
api["data_type"] = m.constant->get_datatype().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;
|
||||
}
|
||||
constants.push_back(api);
|
||||
} break;
|
||||
case ClassNode::Member::ENUM_VALUE: {
|
||||
Dictionary api;
|
||||
api["name"] = m.enum_value.identifier->name;
|
||||
api["value"] = m.enum_value.value;
|
||||
api["data_type"] = m.get_datatype().to_string();
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
|
||||
api["signature"] = symbol->detail;
|
||||
api["description"] = symbol->documentation;
|
||||
}
|
||||
constants.push_back(api);
|
||||
} break;
|
||||
case ClassNode::Member::ENUM: {
|
||||
Dictionary enum_dict;
|
||||
for (int j = 0; j < m.m_enum->values.size(); j++) {
|
||||
enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
|
||||
}
|
||||
|
||||
Dictionary api;
|
||||
api["name"] = m.m_enum->identifier->name;
|
||||
api["value"] = enum_dict;
|
||||
api["data_type"] = m.get_datatype().to_string();
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
|
||||
api["signature"] = symbol->detail;
|
||||
api["description"] = symbol->documentation;
|
||||
}
|
||||
constants.push_back(api);
|
||||
} break;
|
||||
case ClassNode::Member::VARIABLE: {
|
||||
Dictionary api;
|
||||
api["name"] = m.variable->identifier->name;
|
||||
api["data_type"] = m.variable->get_datatype().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());
|
||||
api["export"] = m.variable->exported;
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
|
||||
api["signature"] = symbol->detail;
|
||||
api["description"] = symbol->documentation;
|
||||
}
|
||||
class_members.push_back(api);
|
||||
} break;
|
||||
case ClassNode::Member::SIGNAL: {
|
||||
Dictionary api;
|
||||
api["name"] = m.signal->identifier->name;
|
||||
Array pars;
|
||||
for (int j = 0; j < m.signal->parameters.size(); j++) {
|
||||
pars.append(String(m.signal->parameters[j]->identifier->name));
|
||||
}
|
||||
api["arguments"] = pars;
|
||||
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
|
||||
api["signature"] = symbol->detail;
|
||||
api["description"] = symbol->documentation;
|
||||
}
|
||||
signals.push_back(api);
|
||||
} break;
|
||||
case ClassNode::Member::FUNCTION: {
|
||||
if (m.function->is_static) {
|
||||
static_functions.append(dump_function_api(m.function));
|
||||
} else {
|
||||
methods.append(dump_function_api(m.function));
|
||||
}
|
||||
} break;
|
||||
case ClassNode::Member::GROUP:
|
||||
break; // No-op, but silences warnings.
|
||||
case ClassNode::Member::UNDEFINED:
|
||||
break; // Unreachable.
|
||||
}
|
||||
}
|
||||
|
||||
class_api["sub_classes"] = nested_classes;
|
||||
class_api["constants"] = constants;
|
||||
class_api["members"] = class_members;
|
||||
class_api["signals"] = signals;
|
||||
class_api["methods"] = methods;
|
||||
class_api["static_functions"] = static_functions;
|
||||
|
||||
return class_api;
|
||||
}
|
||||
|
||||
Dictionary ExtendGDScriptParser::generate_api() const {
|
||||
Dictionary api;
|
||||
if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
|
||||
api = dump_class_api(gdclass);
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
void ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
|
||||
path = p_path;
|
||||
lines = p_code.split("\n");
|
||||
|
||||
parse_result = GDScriptParser::parse(p_code, p_path, false);
|
||||
GDScriptAnalyzer analyzer(this);
|
||||
|
||||
if (parse_result == OK) {
|
||||
parse_result = analyzer.analyze();
|
||||
}
|
||||
update_diagnostics();
|
||||
update_symbols();
|
||||
update_document_links(p_code);
|
||||
}
|
||||
167
engine/modules/gdscript/language_server/gdscript_extend_parser.h
Normal file
167
engine/modules/gdscript/language_server/gdscript_extend_parser.h
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_extend_parser.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 "../gdscript_parser.h"
|
||||
#include "godot_lsp.h"
|
||||
|
||||
#include "core/variant/variant.h"
|
||||
|
||||
#ifndef LINE_NUMBER_TO_INDEX
|
||||
#define LINE_NUMBER_TO_INDEX(p_line) ((p_line) - 1)
|
||||
#endif
|
||||
#ifndef COLUMN_NUMBER_TO_INDEX
|
||||
#define COLUMN_NUMBER_TO_INDEX(p_column) ((p_column) - 1)
|
||||
#endif
|
||||
|
||||
typedef HashMap<String, const LSP::DocumentSymbol *> ClassMembers;
|
||||
|
||||
/**
|
||||
* Represents a Position as used by GDScript Parser. Used for conversion to and from `LSP::Position`.
|
||||
*
|
||||
* Difference to `LSP::Position`:
|
||||
* * Line & Char/column: 1-based
|
||||
* * LSP: both 0-based
|
||||
* * Tabs are expanded to columns using tab size (`text_editor/behavior/indent/size`).
|
||||
* * LSP: tab is single char
|
||||
*
|
||||
* Example:
|
||||
* ```gdscript
|
||||
* →→var my_value = 42
|
||||
* ```
|
||||
* `_` is at:
|
||||
* * Godot: `column=12`
|
||||
* * using `indent/size=4`
|
||||
* * Note: counting starts at `1`
|
||||
* * LSP: `character=8`
|
||||
* * Note: counting starts at `0`
|
||||
*/
|
||||
struct GodotPosition {
|
||||
int line;
|
||||
int column;
|
||||
|
||||
GodotPosition(int p_line, int p_column) :
|
||||
line(p_line), column(p_column) {}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
String to_string() const {
|
||||
return vformat("(%d,%d)", line, column);
|
||||
}
|
||||
};
|
||||
|
||||
struct GodotRange {
|
||||
GodotPosition start;
|
||||
GodotPosition end;
|
||||
|
||||
GodotRange(GodotPosition p_start, GodotPosition p_end) :
|
||||
start(p_start), end(p_end) {}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
String to_string() const {
|
||||
return vformat("[%s:%s]", start.to_string(), end.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
class ExtendGDScriptParser : public GDScriptParser {
|
||||
String path;
|
||||
Vector<String> lines;
|
||||
|
||||
LSP::DocumentSymbol class_symbol;
|
||||
Vector<LSP::Diagnostic> diagnostics;
|
||||
List<LSP::DocumentLink> document_links;
|
||||
ClassMembers members;
|
||||
HashMap<String, ClassMembers> inner_classes;
|
||||
|
||||
LSP::Range range_of_node(const GDScriptParser::Node *p_node) const;
|
||||
|
||||
void update_diagnostics();
|
||||
|
||||
void update_symbols();
|
||||
void update_document_links(const String &p_code);
|
||||
void parse_class_symbol(const GDScriptParser::ClassNode *p_class, LSP::DocumentSymbol &r_symbol);
|
||||
void parse_function_symbol(const GDScriptParser::FunctionNode *p_func, LSP::DocumentSymbol &r_symbol);
|
||||
|
||||
Dictionary dump_function_api(const GDScriptParser::FunctionNode *p_func) const;
|
||||
Dictionary dump_class_api(const GDScriptParser::ClassNode *p_class) const;
|
||||
|
||||
const LSP::DocumentSymbol *search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name = "") const;
|
||||
|
||||
public:
|
||||
_FORCE_INLINE_ const String &get_path() const { return path; }
|
||||
_FORCE_INLINE_ const Vector<String> &get_lines() const { return lines; }
|
||||
_FORCE_INLINE_ const LSP::DocumentSymbol &get_symbols() const { return class_symbol; }
|
||||
_FORCE_INLINE_ const Vector<LSP::Diagnostic> &get_diagnostics() const { return diagnostics; }
|
||||
_FORCE_INLINE_ const ClassMembers &get_members() const { return members; }
|
||||
_FORCE_INLINE_ const HashMap<String, ClassMembers> &get_inner_classes() const { return inner_classes; }
|
||||
Error parse_result;
|
||||
|
||||
Error get_left_function_call(const LSP::Position &p_position, LSP::Position &r_func_pos, int &r_arg_index) const;
|
||||
|
||||
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;
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* `p_symbol_name` gets ignored if empty. Otherwise symbol must match passed in named.
|
||||
*
|
||||
* Necessary when multiple symbols at same line for example with `func`:
|
||||
* `func handle_arg(arg: int):`
|
||||
* -> Without `p_symbol_name`: returns `handle_arg`. Even if parameter (`arg`) is wanted.
|
||||
* With `p_symbol_name`: symbol name MUST match `p_symbol_name`: returns `arg`.
|
||||
*/
|
||||
const LSP::DocumentSymbol *get_symbol_defined_at_line(int p_line, const String &p_symbol_name = "") const;
|
||||
const LSP::DocumentSymbol *get_member_symbol(const String &p_name, const String &p_subclass = "") const;
|
||||
const List<LSP::DocumentLink> &get_document_links() const;
|
||||
|
||||
const Array &get_member_completions();
|
||||
Dictionary generate_api() const;
|
||||
|
||||
void parse(const String &p_code, const String &p_path);
|
||||
};
|
||||
|
|
@ -0,0 +1,714 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_language_protocol.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 "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"
|
||||
|
||||
#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(!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)); \
|
||||
Ref<LSPeer> client = clients.get(latest_client_id); \
|
||||
ERR_FAIL_COND(!client.is_valid());
|
||||
|
||||
GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;
|
||||
|
||||
Error GDScriptLanguageProtocol::LSPeer::handle_data() {
|
||||
int read = 0;
|
||||
// Read headers
|
||||
if (!has_header) {
|
||||
while (true) {
|
||||
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
|
||||
req_pos = 0;
|
||||
ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");
|
||||
}
|
||||
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
|
||||
if (err != OK) {
|
||||
return FAILED;
|
||||
} else if (read != 1) { // Busy, wait until next poll
|
||||
return ERR_BUSY;
|
||||
}
|
||||
char *r = (char *)req_buf;
|
||||
int l = req_pos;
|
||||
|
||||
// End of headers
|
||||
if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
|
||||
r[l - 3] = '\0'; // Null terminate to read string
|
||||
String header = String::utf8(r);
|
||||
content_length = header.substr(16).to_int();
|
||||
has_header = true;
|
||||
req_pos = 0;
|
||||
break;
|
||||
}
|
||||
req_pos++;
|
||||
}
|
||||
}
|
||||
if (has_header) {
|
||||
while (req_pos < content_length) {
|
||||
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
|
||||
req_pos = 0;
|
||||
has_header = false;
|
||||
ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
|
||||
}
|
||||
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
|
||||
if (err != OK) {
|
||||
return FAILED;
|
||||
} else if (read != 1) {
|
||||
return ERR_BUSY;
|
||||
}
|
||||
req_pos++;
|
||||
}
|
||||
|
||||
// Parse data
|
||||
String msg = String::utf8((const char *)req_buf, req_pos);
|
||||
|
||||
// Reset to read again
|
||||
req_pos = 0;
|
||||
has_header = false;
|
||||
|
||||
// Response
|
||||
String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
|
||||
clear_stale_parsers();
|
||||
if (!output.is_empty()) {
|
||||
res_queue.push_back(output.utf8());
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error GDScriptLanguageProtocol::LSPeer::send_data() {
|
||||
int sent = 0;
|
||||
while (!res_queue.is_empty()) {
|
||||
CharString c_res = res_queue[0];
|
||||
if (res_sent < c_res.size()) {
|
||||
Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
|
||||
if (err != OK) {
|
||||
return err;
|
||||
}
|
||||
res_sent += sent;
|
||||
}
|
||||
// Response sent
|
||||
if (res_sent >= c_res.size() - 1) {
|
||||
res_sent = 0;
|
||||
res_queue.remove_at(0);
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error GDScriptLanguageProtocol::on_client_connected() {
|
||||
Ref<StreamPeerTCP> tcp_peer = server->take_connection();
|
||||
ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
|
||||
Ref<LSPeer> peer = memnew(LSPeer);
|
||||
peer->connection = tcp_peer;
|
||||
clients.insert(next_client_id, peer);
|
||||
next_client_id++;
|
||||
EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
|
||||
return OK;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
String GDScriptLanguageProtocol::process_message(const String &p_text) {
|
||||
String ret = process_string(p_text);
|
||||
if (ret.is_empty()) {
|
||||
return ret;
|
||||
} else {
|
||||
return format_output(ret);
|
||||
}
|
||||
}
|
||||
|
||||
String GDScriptLanguageProtocol::format_output(const String &p_text) {
|
||||
String header = "Content-Length: ";
|
||||
CharString charstr = p_text.utf8();
|
||||
size_t len = charstr.length();
|
||||
header += itos(len);
|
||||
header += "\r\n\r\n";
|
||||
|
||||
return header + 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", "client_id"), &GDScriptLanguageProtocol::on_client_disconnected);
|
||||
ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
|
||||
#endif // !DISABLE_DEPRECATED
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
{
|
||||
// Warn if the workspace root does not match with the project that is currently open in Godot,
|
||||
// since it might lead to unexpected behavior, like wrong warnings about duplicate class names.
|
||||
|
||||
String root;
|
||||
Variant root_uri_var = p_params["rootUri"];
|
||||
Variant root_var = p_params.get("rootPath", Variant());
|
||||
if (root_uri_var.is_string()) {
|
||||
root = get_workspace()->get_file_path(root_uri_var);
|
||||
} else if (root_var.is_string()) {
|
||||
root = root_var;
|
||||
}
|
||||
|
||||
if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
if (!_initialized) {
|
||||
workspace->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");
|
||||
|
||||
return ret.to_json();
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
|
||||
LSP::GodotCapabilities capabilities;
|
||||
|
||||
DocTools *doc = EditorHelp::get_doc_data();
|
||||
for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
|
||||
LSP::GodotNativeClassInfo gdclass;
|
||||
gdclass.name = E.value.name;
|
||||
gdclass.class_doc = &(E.value);
|
||||
if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
|
||||
gdclass.class_info = ptr;
|
||||
}
|
||||
capabilities.native_classes.push_back(gdclass);
|
||||
}
|
||||
|
||||
notify_client("gdscript/capabilities", capabilities.to_json());
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::poll(int p_limit_usec) {
|
||||
uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
|
||||
|
||||
if (server->is_connection_available()) {
|
||||
on_client_connected();
|
||||
}
|
||||
|
||||
scene_cache.poll();
|
||||
|
||||
HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
|
||||
while (E != clients.end()) {
|
||||
Ref<LSPeer> peer = E->value;
|
||||
peer->connection->poll();
|
||||
StreamPeerTCP::Status status = peer->connection->get_status();
|
||||
if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
|
||||
on_client_disconnected(E->key);
|
||||
E = clients.begin();
|
||||
continue;
|
||||
} else {
|
||||
Error err = OK;
|
||||
while (peer->connection->get_available_bytes() > 0) {
|
||||
latest_client_id = E->key;
|
||||
err = peer->handle_data();
|
||||
if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (err != OK && err != ERR_BUSY) {
|
||||
on_client_disconnected(E->key);
|
||||
E = clients.begin();
|
||||
continue;
|
||||
}
|
||||
|
||||
err = peer->send_data();
|
||||
if (err != OK && err != ERR_BUSY) {
|
||||
on_client_disconnected(E->key);
|
||||
E = clients.begin();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
++E;
|
||||
}
|
||||
}
|
||||
|
||||
Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
|
||||
return server->listen(p_port, p_bind_ip);
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::stop() {
|
||||
for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
|
||||
Ref<LSPeer> peer = clients.get(E.key);
|
||||
peer->connection->disconnect_from_host();
|
||||
}
|
||||
|
||||
scene_cache.clear();
|
||||
server->stop();
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
|
||||
#ifdef TESTS_ENABLED
|
||||
if (clients.is_empty()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (p_client_id == -1) {
|
||||
ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
|
||||
p_client_id = latest_client_id;
|
||||
}
|
||||
ERR_FAIL_COND(!clients.has(p_client_id));
|
||||
Ref<LSPeer> peer = clients.get(p_client_id);
|
||||
ERR_FAIL_COND(peer.is_null());
|
||||
|
||||
Dictionary message = make_notification(p_method, p_params);
|
||||
String msg = Variant(message).to_json_string();
|
||||
msg = format_output(msg);
|
||||
peer->res_queue.push_back(msg.utf8());
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
|
||||
#ifdef TESTS_ENABLED
|
||||
if (clients.is_empty()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (p_client_id == -1) {
|
||||
ERR_FAIL_COND_MSG(latest_client_id == LSP_NO_CLIENT, "GDScript LSP: Can't notify client as none was connected.");
|
||||
p_client_id = latest_client_id;
|
||||
}
|
||||
ERR_FAIL_COND(!clients.has(p_client_id));
|
||||
Ref<LSPeer> peer = clients.get(p_client_id);
|
||||
ERR_FAIL_COND(peer.is_null());
|
||||
|
||||
Dictionary message = make_request(p_method, p_params, next_server_id);
|
||||
next_server_id++;
|
||||
String msg = Variant(message).to_json_string();
|
||||
msg = format_output(msg);
|
||||
peer->res_queue.push_back(msg.utf8());
|
||||
}
|
||||
|
||||
bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
|
||||
return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
|
||||
}
|
||||
|
||||
bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
|
||||
return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
|
||||
}
|
||||
|
||||
ExtendGDScriptParser *GDScriptLanguageProtocol::LSPeer::parse_script(const String &p_path) {
|
||||
remove_cached_parser(p_path);
|
||||
|
||||
String content;
|
||||
const LSP::TextDocumentItem *document = managed_files.getptr(p_path);
|
||||
if (document == nullptr) {
|
||||
if (!p_path.has_extension("gd")) {
|
||||
return nullptr;
|
||||
}
|
||||
Error err;
|
||||
content = FileAccess::get_file_as_string(p_path, &err);
|
||||
if (err != OK) {
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
if (document->languageId != LSP::LanguageId::GDSCRIPT) {
|
||||
return nullptr;
|
||||
}
|
||||
content = document->text;
|
||||
}
|
||||
|
||||
ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
|
||||
parse_results[p_path] = parser;
|
||||
|
||||
parser->parse(content, p_path);
|
||||
|
||||
if (document != nullptr) {
|
||||
GDScriptLanguageProtocol::get_singleton()->get_workspace()->publish_diagnostics(p_path);
|
||||
} else {
|
||||
// Don't keep cached for further requests since we can't invalidate the cache properly.
|
||||
stale_parsers.insert(p_path);
|
||||
}
|
||||
|
||||
return parser;
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::LSPeer::clear_stale_parsers() {
|
||||
while (!stale_parsers.is_empty()) {
|
||||
remove_cached_parser(*stale_parsers.begin());
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::LSPeer::remove_cached_parser(const String &p_path) {
|
||||
HashMap<String, ExtendGDScriptParser *>::Iterator cached = parse_results.find(p_path);
|
||||
if (cached) {
|
||||
memdelete(cached->value);
|
||||
parse_results.remove(cached);
|
||||
}
|
||||
|
||||
stale_parsers.erase(p_path);
|
||||
}
|
||||
|
||||
ExtendGDScriptParser *GDScriptLanguageProtocol::get_parse_result(const String &p_path) {
|
||||
LSP_CLIENT_V(nullptr);
|
||||
|
||||
ExtendGDScriptParser **cached_parser = client->parse_results.getptr(p_path);
|
||||
if (cached_parser == nullptr) {
|
||||
return client->parse_script(p_path);
|
||||
}
|
||||
return *cached_parser;
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::lsp_did_open(const Dictionary &p_params) {
|
||||
LSP_CLIENT;
|
||||
|
||||
LSP::TextDocumentItem document;
|
||||
document.load(p_params["textDocument"]);
|
||||
|
||||
// We keep track of non GDScript files that the client owns, but we are not interested in the content.
|
||||
if (document.languageId != LSP::LanguageId::GDSCRIPT) {
|
||||
document.text = "";
|
||||
}
|
||||
|
||||
String path = get_workspace()->get_file_path(document.uri);
|
||||
|
||||
/// An open notification must not be sent more than once without a corresponding close notification send before.
|
||||
ERR_FAIL_COND_MSG(client->managed_files.has(path), "LSP: Client is opening already opened file.");
|
||||
|
||||
client->managed_files[path] = document;
|
||||
client->parse_script(path);
|
||||
|
||||
scene_cache.request_load(path);
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::lsp_did_change(const Dictionary &p_params) {
|
||||
LSP_CLIENT;
|
||||
|
||||
LSP::TextDocumentIdentifier identifier;
|
||||
identifier.load(p_params["textDocument"]);
|
||||
|
||||
String path = get_workspace()->get_file_path(identifier.uri);
|
||||
LSP::TextDocumentItem *document = client->managed_files.getptr(path);
|
||||
|
||||
/// Before a client can change a text document it must claim ownership of its content using the textDocument/didOpen notification.
|
||||
ERR_FAIL_COND_MSG(document == nullptr, "LSP: Client is changing file without opening it.");
|
||||
|
||||
if (document->languageId != LSP::LanguageId::GDSCRIPT) {
|
||||
return;
|
||||
}
|
||||
|
||||
Array contentChanges = p_params["contentChanges"];
|
||||
|
||||
if (contentChanges.is_empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// We only support TextDocumentSyncKind::Full. So only the last full text is relevant.
|
||||
LSP::TextDocumentContentChangeEvent event;
|
||||
event.load(contentChanges.back());
|
||||
document->text = event.text;
|
||||
|
||||
client->parse_script(path);
|
||||
}
|
||||
|
||||
void GDScriptLanguageProtocol::lsp_did_close(const Dictionary &p_params) {
|
||||
LSP_CLIENT;
|
||||
|
||||
LSP::TextDocumentIdentifier identifier;
|
||||
identifier.load(p_params["textDocument"]);
|
||||
|
||||
String path = get_workspace()->get_file_path(identifier.uri);
|
||||
bool was_opened = client->managed_files.erase(path);
|
||||
|
||||
client->remove_cached_parser(path);
|
||||
|
||||
/// 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) {
|
||||
LSP_CLIENT;
|
||||
|
||||
String path = workspace->get_file_path(p_doc_pos.textDocument.uri);
|
||||
|
||||
const ExtendGDScriptParser *parser = get_parse_result(path);
|
||||
if (!parser) {
|
||||
return;
|
||||
}
|
||||
|
||||
String symbol_name;
|
||||
LSP::Range 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_name)) {
|
||||
r_list.push_back(*symbol);
|
||||
}
|
||||
}
|
||||
|
||||
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_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_name)) {
|
||||
r_list.push_back(*symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GDScriptLanguageProtocol::LSPeer::~LSPeer() {
|
||||
while (!parse_results.is_empty()) {
|
||||
String path = parse_results.begin()->key;
|
||||
remove_cached_parser(path);
|
||||
}
|
||||
stale_parsers.clear();
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
#define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
|
||||
#define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
|
||||
#define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))
|
||||
// clang-format on
|
||||
|
||||
GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
|
||||
server.instantiate();
|
||||
singleton = this;
|
||||
workspace.instantiate();
|
||||
text_document.instantiate();
|
||||
|
||||
SET_DOCUMENT_METHOD(didOpen);
|
||||
SET_DOCUMENT_METHOD(didClose);
|
||||
SET_DOCUMENT_METHOD(didChange);
|
||||
SET_DOCUMENT_METHOD(willSaveWaitUntil);
|
||||
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);
|
||||
SET_DOCUMENT_METHOD(signatureHelp);
|
||||
|
||||
SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.
|
||||
|
||||
SET_COMPLETION_METHOD(resolve);
|
||||
|
||||
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
|
||||
#undef SET_COMPLETION_METHOD
|
||||
#undef SET_WORKSPACE_METHOD
|
||||
|
||||
#undef LSP_CLIENT
|
||||
#undef LSP_CLIENT_V
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_language_protocol.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 "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"
|
||||
|
||||
#include "modules/jsonrpc/jsonrpc.h"
|
||||
|
||||
#define LSP_MAX_BUFFER_SIZE 4194304
|
||||
#define LSP_MAX_CLIENTS 8
|
||||
|
||||
#define LSP_NO_CLIENT -1
|
||||
|
||||
class GDScriptLanguageProtocol : public JSONRPC {
|
||||
GDCLASS(GDScriptLanguageProtocol, JSONRPC)
|
||||
|
||||
friend class TestGDScriptLanguageProtocolInitializer;
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
private:
|
||||
struct LSPeer : RefCounted {
|
||||
Ref<StreamPeerTCP> connection;
|
||||
|
||||
uint8_t req_buf[LSP_MAX_BUFFER_SIZE];
|
||||
int req_pos = 0;
|
||||
bool has_header = false;
|
||||
bool has_content = false;
|
||||
int content_length = 0;
|
||||
Vector<CharString> res_queue;
|
||||
int res_sent = 0;
|
||||
|
||||
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.
|
||||
*/
|
||||
HashMap<String, LSP::TextDocumentItem> managed_files;
|
||||
HashMap<String, ExtendGDScriptParser *> parse_results;
|
||||
|
||||
void remove_cached_parser(const String &p_path);
|
||||
ExtendGDScriptParser *parse_script(const String &p_path);
|
||||
|
||||
~LSPeer();
|
||||
|
||||
private:
|
||||
void clear_stale_parsers();
|
||||
// Paths of parsers which we can't cache longterm.
|
||||
// Can be cleared up using `clear_stale_parsers()`.
|
||||
HashSet<String> stale_parsers;
|
||||
};
|
||||
|
||||
enum LSPErrorCode {
|
||||
RequestCancelled = -32800,
|
||||
ContentModified = -32801,
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
int next_server_id = 0;
|
||||
|
||||
Ref<GDScriptTextDocument> text_document;
|
||||
Ref<GDScriptWorkspace> workspace;
|
||||
|
||||
Error on_client_connected();
|
||||
void on_client_disconnected(const int &p_client_id);
|
||||
|
||||
String process_message(const String &p_text);
|
||||
String format_output(const String &p_text);
|
||||
|
||||
bool _initialized = false;
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
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);
|
||||
Error start(int p_port, const IPAddress &p_bind_ip);
|
||||
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);
|
||||
|
||||
bool is_smart_resolve_enabled() const;
|
||||
bool is_goto_native_symbols_enabled() const;
|
||||
|
||||
// Text Document Synchronization
|
||||
void lsp_did_open(const Dictionary &p_params);
|
||||
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.
|
||||
*
|
||||
* The result fulfills no semantic guarantees, nor is it guaranteed to be complete.
|
||||
* Should only be used for "smart resolve".
|
||||
*/
|
||||
void resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list);
|
||||
|
||||
/**
|
||||
* Returns parse results for the given path, using the cache if available.
|
||||
* If no such file exists, or the file is not a GDScript file a `nullptr` is returned.
|
||||
*/
|
||||
ExtendGDScriptParser *get_parse_result(const String &p_path);
|
||||
|
||||
GDScriptLanguageProtocol();
|
||||
~GDScriptLanguageProtocol() {
|
||||
clients.clear();
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_language_server.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 "gdscript_language_server.h"
|
||||
|
||||
#include "gdscript_language_protocol.h"
|
||||
|
||||
#include "core/os/os.h"
|
||||
#include "editor/editor_log.h"
|
||||
#include "editor/editor_node.h"
|
||||
#include "editor/settings/editor_settings.h"
|
||||
|
||||
int GDScriptLanguageServer::port_override = -1;
|
||||
|
||||
GDScriptLanguageServer::GDScriptLanguageServer() {
|
||||
set_process_internal(true);
|
||||
}
|
||||
|
||||
void GDScriptLanguageServer::_notification(int p_what) {
|
||||
switch (p_what) {
|
||||
case NOTIFICATION_EXIT_TREE: {
|
||||
stop();
|
||||
} break;
|
||||
|
||||
case NOTIFICATION_INTERNAL_PROCESS: {
|
||||
if (!start_attempted && EditorNode::get_singleton()->is_editor_ready()) {
|
||||
start_attempted = true;
|
||||
start();
|
||||
}
|
||||
|
||||
if (started && !use_thread) {
|
||||
GDScriptLanguageProtocol::get_singleton()->poll(poll_limit_usec);
|
||||
}
|
||||
} break;
|
||||
|
||||
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
|
||||
if (!EditorSettings::get_singleton()->check_changed_settings_in_group("network/language_server")) {
|
||||
break;
|
||||
}
|
||||
|
||||
String remote_host = String(_EDITOR_GET("network/language_server/remote_host"));
|
||||
int remote_port = (GDScriptLanguageServer::port_override > -1) ? GDScriptLanguageServer::port_override : (int)_EDITOR_GET("network/language_server/remote_port");
|
||||
bool remote_use_thread = (bool)_EDITOR_GET("network/language_server/use_thread");
|
||||
int remote_poll_limit = (int)_EDITOR_GET("network/language_server/poll_limit_usec");
|
||||
if (remote_host != host || remote_port != port || remote_use_thread != use_thread || remote_poll_limit != poll_limit_usec) {
|
||||
stop();
|
||||
start();
|
||||
}
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptLanguageServer::thread_main(void *p_userdata) {
|
||||
set_current_thread_safe_for_nodes(true);
|
||||
GDScriptLanguageServer *self = static_cast<GDScriptLanguageServer *>(p_userdata);
|
||||
while (self->thread_running) {
|
||||
// Poll 20 times per second
|
||||
GDScriptLanguageProtocol::get_singleton()->poll(self->poll_limit_usec);
|
||||
OS::get_singleton()->delay_usec(50000);
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptLanguageServer::start() {
|
||||
host = String(_EDITOR_GET("network/language_server/remote_host"));
|
||||
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");
|
||||
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() {
|
||||
if (use_thread) {
|
||||
ERR_FAIL_COND(!thread.is_started());
|
||||
thread_running = false;
|
||||
thread.wait_to_finish();
|
||||
}
|
||||
GDScriptLanguageProtocol::get_singleton()->stop();
|
||||
started = false;
|
||||
EditorNode::get_log()->add_message("--- GDScript language server stopped ---", EditorLog::MSG_TYPE_EDITOR);
|
||||
}
|
||||
|
||||
void register_lsp_types() {
|
||||
GDREGISTER_CLASS(GDScriptLanguageProtocol);
|
||||
GDREGISTER_CLASS(GDScriptTextDocument);
|
||||
GDREGISTER_CLASS(GDScriptWorkspace);
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_language_server.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 "editor/plugins/editor_plugin.h"
|
||||
|
||||
class GDScriptLanguageServer : public EditorPlugin {
|
||||
GDCLASS(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;
|
||||
int port = 0;
|
||||
int poll_limit_usec = 0;
|
||||
|
||||
static void thread_main(void *p_userdata);
|
||||
|
||||
private:
|
||||
void _notification(int p_what);
|
||||
|
||||
public:
|
||||
static int port_override;
|
||||
GDScriptLanguageServer();
|
||||
void start();
|
||||
void stop();
|
||||
};
|
||||
|
||||
void register_lsp_types();
|
||||
|
|
@ -0,0 +1,424 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_text_document.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 "gdscript_text_document.h"
|
||||
|
||||
#include "../gdscript.h"
|
||||
#include "gdscript_extend_parser.h"
|
||||
#include "gdscript_language_protocol.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("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("foldingRange", "params"), &GDScriptTextDocument::foldingRange);
|
||||
ClassDB::bind_method(D_METHOD("codeLens", "params"), &GDScriptTextDocument::codeLens);
|
||||
ClassDB::bind_method(D_METHOD("documentLink", "params"), &GDScriptTextDocument::documentLink);
|
||||
ClassDB::bind_method(D_METHOD("colorPresentation", "params"), &GDScriptTextDocument::colorPresentation);
|
||||
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) {
|
||||
GDScriptLanguageProtocol::get_singleton()->lsp_did_open(p_param);
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::didChange(const Variant &p_param) {
|
||||
GDScriptLanguageProtocol::get_singleton()->lsp_did_change(p_param);
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::didClose(const Variant &p_param) {
|
||||
GDScriptLanguageProtocol::get_singleton()->lsp_did_close(p_param);
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::willSaveWaitUntil(const Variant &p_param) {
|
||||
Dictionary dict = p_param;
|
||||
LSP::TextDocumentIdentifier doc;
|
||||
doc.load(dict["textDocument"]);
|
||||
|
||||
String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri);
|
||||
Ref<Script> scr = ResourceLoader::load(path);
|
||||
if (scr.is_valid()) {
|
||||
ScriptEditor::get_singleton()->clear_docs_from_script(scr);
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::didSave(const Variant &p_param) {
|
||||
Dictionary dict = p_param;
|
||||
LSP::TextDocumentIdentifier doc;
|
||||
doc.load(dict["textDocument"]);
|
||||
String text = dict["text"];
|
||||
|
||||
String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(doc.uri);
|
||||
Ref<GDScript> scr = ResourceLoader::load(path);
|
||||
if (scr.is_valid() && (scr->load_source_code(path) == OK)) {
|
||||
if (scr->is_tool()) {
|
||||
scr->get_language()->reload_tool_script(scr, true);
|
||||
} else {
|
||||
scr->reload(true);
|
||||
}
|
||||
|
||||
scr->update_exports();
|
||||
|
||||
if (!Thread::is_main_thread()) {
|
||||
callable_mp(this, &GDScriptTextDocument::reload_script).call_deferred(scr);
|
||||
} else {
|
||||
reload_script(scr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::reload_script(Ref<GDScript> p_to_reload_script) {
|
||||
ScriptEditor::get_singleton()->reload_scripts(true);
|
||||
ScriptEditor::get_singleton()->update_docs_from_script(p_to_reload_script);
|
||||
ScriptEditor::get_singleton()->trigger_live_script_reload(p_to_reload_script->get_path());
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::notify_client_show_symbol(const LSP::DocumentSymbol *symbol) {
|
||||
ERR_FAIL_NULL(symbol);
|
||||
GDScriptLanguageProtocol::get_singleton()->notify_client("gdscript/show_native_symbol", symbol->to_json(true));
|
||||
}
|
||||
|
||||
Variant GDScriptTextDocument::nativeSymbol(const Dictionary &p_params) {
|
||||
Variant ret;
|
||||
|
||||
LSP::NativeSymbolInspectParams params;
|
||||
params.load(p_params);
|
||||
|
||||
if (const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_native_symbol(params)) {
|
||||
ret = symbol->to_json(true);
|
||||
notify_client_show_symbol(symbol);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
Array GDScriptTextDocument::documentSymbol(const Dictionary &p_params) {
|
||||
Dictionary params = p_params["textDocument"];
|
||||
String uri = params["uri"];
|
||||
String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(uri);
|
||||
Array arr;
|
||||
|
||||
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
|
||||
if (parser) {
|
||||
LSP::DocumentSymbol symbol = parser->get_symbols();
|
||||
arr.push_back(symbol.to_json(true));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
Array GDScriptTextDocument::documentHighlight(const Dictionary &p_params) {
|
||||
Array arr;
|
||||
LSP::TextDocumentPositionParams params;
|
||||
params.load(p_params);
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
String new_name = p_params["newName"];
|
||||
|
||||
return GDScriptLanguageProtocol::get_singleton()->get_workspace()->rename(params, new_name);
|
||||
}
|
||||
|
||||
Variant GDScriptTextDocument::prepareRename(const Dictionary &p_params) {
|
||||
LSP::TextDocumentPositionParams params;
|
||||
params.load(p_params);
|
||||
|
||||
LSP::DocumentSymbol symbol;
|
||||
LSP::Range range;
|
||||
if (GDScriptLanguageProtocol::get_singleton()->get_workspace()->can_rename(params, symbol, range)) {
|
||||
return Variant(range.to_json());
|
||||
}
|
||||
|
||||
// `null` -> rename not valid at current location.
|
||||
return Variant();
|
||||
}
|
||||
|
||||
Array GDScriptTextDocument::references(const Dictionary &p_params) {
|
||||
Array res;
|
||||
|
||||
LSP::ReferenceParams params;
|
||||
params.load(p_params);
|
||||
|
||||
const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
|
||||
if (symbol) {
|
||||
Vector<LSP::Location> usages = GDScriptLanguageProtocol::get_singleton()->get_workspace()->find_all_usages(*symbol);
|
||||
res.resize(usages.size());
|
||||
int declaration_adjustment = 0;
|
||||
for (int i = 0; i < usages.size(); i++) {
|
||||
LSP::Location usage = usages[i];
|
||||
if (!params.context.includeDeclaration && usage.range == symbol->range) {
|
||||
declaration_adjustment++;
|
||||
continue;
|
||||
}
|
||||
res[i - declaration_adjustment] = usages[i].to_json();
|
||||
}
|
||||
|
||||
if (declaration_adjustment > 0) {
|
||||
res.resize(res.size() - declaration_adjustment);
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
|
||||
LSP::CompletionItem item;
|
||||
item.load(p_params);
|
||||
|
||||
LSP::CompletionParams params;
|
||||
Variant data = p_params["data"];
|
||||
|
||||
const LSP::DocumentSymbol *symbol = nullptr;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
if (symbol) {
|
||||
item.documentation = symbol->render();
|
||||
}
|
||||
|
||||
if (item.kind == LSP::CompletionItemKind::Event) {
|
||||
if (params.context.triggerKind == LSP::CompletionTriggerKind::TriggerCharacter && (params.context.triggerCharacter == "(")) {
|
||||
const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
|
||||
item.insertText = item.label.quote(quote_style);
|
||||
}
|
||||
}
|
||||
|
||||
if (item.kind == LSP::CompletionItemKind::Method) {
|
||||
bool is_trigger_character = params.context.triggerKind == LSP::CompletionTriggerKind::TriggerCharacter;
|
||||
bool is_quote_character = params.context.triggerCharacter == "\"" || params.context.triggerCharacter == "'";
|
||||
|
||||
if (is_trigger_character && is_quote_character && item.insertText.is_quoted()) {
|
||||
item.insertText = item.insertText.unquote();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
LSP::DocumentLinkParams params;
|
||||
params.load(p_params);
|
||||
|
||||
List<LSP::DocumentLink> links;
|
||||
GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_document_links(params.textDocument.uri, links);
|
||||
for (const LSP::DocumentLink &E : links) {
|
||||
ret.push_back(E.to_json());
|
||||
}
|
||||
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);
|
||||
|
||||
const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
|
||||
if (symbol) {
|
||||
LSP::Hover hover;
|
||||
hover.contents = symbol->render();
|
||||
hover.range.start = params.position;
|
||||
hover.range.end = params.position;
|
||||
return hover.to_json();
|
||||
|
||||
} else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
|
||||
Dictionary ret;
|
||||
Array contents;
|
||||
List<const LSP::DocumentSymbol *> list;
|
||||
GDScriptLanguageProtocol::get_singleton()->resolve_related_symbols(params, list);
|
||||
for (const LSP::DocumentSymbol *&E : list) {
|
||||
if (const LSP::DocumentSymbol *s = E) {
|
||||
contents.push_back(s->render().value);
|
||||
}
|
||||
}
|
||||
ret["contents"] = contents;
|
||||
return ret;
|
||||
}
|
||||
|
||||
return Variant();
|
||||
}
|
||||
|
||||
Array GDScriptTextDocument::definition(const Dictionary &p_params) {
|
||||
LSP::TextDocumentPositionParams params;
|
||||
params.load(p_params);
|
||||
List<const LSP::DocumentSymbol *> symbols;
|
||||
return find_symbols(params, symbols);
|
||||
}
|
||||
|
||||
Variant GDScriptTextDocument::declaration(const Dictionary &p_params) {
|
||||
LSP::TextDocumentPositionParams params;
|
||||
params.load(p_params);
|
||||
List<const LSP::DocumentSymbol *> symbols;
|
||||
Array arr = find_symbols(params, symbols);
|
||||
if (arr.is_empty() && !symbols.is_empty() && !symbols.front()->get()->native_class.is_empty()) { // Find a native symbol
|
||||
const LSP::DocumentSymbol *symbol = symbols.front()->get();
|
||||
if (GDScriptLanguageProtocol::get_singleton()->is_goto_native_symbols_enabled()) {
|
||||
String id;
|
||||
switch (symbol->kind) {
|
||||
case LSP::SymbolKind::Class:
|
||||
id = "class_name:" + symbol->name;
|
||||
break;
|
||||
case LSP::SymbolKind::Constant:
|
||||
id = "class_constant:" + symbol->native_class + ":" + symbol->name;
|
||||
break;
|
||||
case LSP::SymbolKind::Property:
|
||||
case LSP::SymbolKind::Variable:
|
||||
id = "class_property:" + symbol->native_class + ":" + symbol->name;
|
||||
break;
|
||||
case LSP::SymbolKind::Enum:
|
||||
id = "class_enum:" + symbol->native_class + ":" + symbol->name;
|
||||
break;
|
||||
case LSP::SymbolKind::Method:
|
||||
case LSP::SymbolKind::Function:
|
||||
id = "class_method:" + symbol->native_class + ":" + symbol->name;
|
||||
break;
|
||||
default:
|
||||
id = "class_global:" + symbol->native_class + ":" + symbol->name;
|
||||
break;
|
||||
}
|
||||
callable_mp(this, &GDScriptTextDocument::show_native_symbol_in_editor).call_deferred(id);
|
||||
} else {
|
||||
notify_client_show_symbol(symbol);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
Variant GDScriptTextDocument::signatureHelp(const Dictionary &p_params) {
|
||||
Variant ret;
|
||||
|
||||
LSP::TextDocumentPositionParams params;
|
||||
params.load(p_params);
|
||||
|
||||
LSP::SignatureHelp s;
|
||||
if (OK == GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_signature(params, s)) {
|
||||
ret = s.to_json();
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
GDScriptTextDocument::GDScriptTextDocument() {
|
||||
file_checker = FileAccess::create(FileAccess::ACCESS_RESOURCES);
|
||||
}
|
||||
|
||||
void GDScriptTextDocument::show_native_symbol_in_editor(const String &p_symbol_id) {
|
||||
callable_mp(ScriptEditor::get_singleton(), &ScriptEditor::goto_help).call_deferred(p_symbol_id);
|
||||
|
||||
DisplayServer::get_singleton()->window_move_to_foreground();
|
||||
}
|
||||
|
||||
Array GDScriptTextDocument::find_symbols(const LSP::TextDocumentPositionParams &p_location, List<const LSP::DocumentSymbol *> &r_list) {
|
||||
Array arr;
|
||||
const LSP::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(p_location);
|
||||
if (symbol) {
|
||||
LSP::Location location;
|
||||
location.uri = symbol->uri;
|
||||
if (!location.uri.is_empty()) {
|
||||
location.range = symbol->selectionRange;
|
||||
const String &path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(symbol->uri);
|
||||
if (file_checker->file_exists(path)) {
|
||||
arr.push_back(location.to_json());
|
||||
}
|
||||
}
|
||||
r_list.push_back(symbol);
|
||||
} else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
|
||||
List<const LSP::DocumentSymbol *> list;
|
||||
GDScriptLanguageProtocol::get_singleton()->resolve_related_symbols(p_location, list);
|
||||
for (const LSP::DocumentSymbol *&E : list) {
|
||||
if (const LSP::DocumentSymbol *s = E) {
|
||||
if (!s->uri.is_empty()) {
|
||||
LSP::Location location;
|
||||
location.uri = s->uri;
|
||||
location.range = s->selectionRange;
|
||||
arr.push_back(location.to_json());
|
||||
r_list.push_back(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_text_document.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 "godot_lsp.h"
|
||||
|
||||
#include "core/io/file_access.h"
|
||||
#include "core/object/ref_counted.h"
|
||||
|
||||
class GDScript;
|
||||
|
||||
class GDScriptTextDocument : public RefCounted {
|
||||
GDCLASS(GDScriptTextDocument, RefCounted)
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
Ref<FileAccess> file_checker;
|
||||
|
||||
private:
|
||||
Array find_symbols(const LSP::TextDocumentPositionParams &p_location, List<const LSP::DocumentSymbol *> &r_list);
|
||||
void notify_client_show_symbol(const LSP::DocumentSymbol *symbol);
|
||||
|
||||
public:
|
||||
void didOpen(const Variant &p_param);
|
||||
void didClose(const Variant &p_param);
|
||||
void didChange(const Variant &p_param);
|
||||
void willSaveWaitUntil(const Variant &p_param);
|
||||
void didSave(const Variant &p_param);
|
||||
|
||||
void reload_script(Ref<GDScript> p_to_reload_script);
|
||||
void show_native_symbol_in_editor(const String &p_symbol_id);
|
||||
|
||||
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);
|
||||
|
||||
GDScriptTextDocument();
|
||||
};
|
||||
796
engine/modules/gdscript/language_server/gdscript_workspace.cpp
Normal file
796
engine/modules/gdscript/language_server/gdscript_workspace.cpp
Normal file
|
|
@ -0,0 +1,796 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_workspace.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 "gdscript_workspace.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/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"
|
||||
|
||||
void GDScriptWorkspace::_bind_methods() {
|
||||
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("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api);
|
||||
|
||||
#ifndef DISABLE_DEPRECATED
|
||||
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_local_script);
|
||||
ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
|
||||
#endif
|
||||
}
|
||||
|
||||
void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStringArray args) {
|
||||
Ref<Script> scr = obj->get_script();
|
||||
|
||||
if (scr->get_language()->get_name() != "GDScript") {
|
||||
return;
|
||||
}
|
||||
|
||||
String function_signature = "func " + function;
|
||||
String source = scr->get_source_code();
|
||||
|
||||
if (source.contains(function_signature)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int first_class = source.find("\nclass ");
|
||||
int start_line = 0;
|
||||
if (first_class != -1) {
|
||||
start_line = source.substr(0, first_class).split("\n").size();
|
||||
} else {
|
||||
start_line = source.split("\n").size();
|
||||
}
|
||||
|
||||
String function_body = "\n\n" + function_signature + "(";
|
||||
for (int i = 0; i < args.size(); ++i) {
|
||||
function_body += args[i];
|
||||
if (i < args.size() - 1) {
|
||||
function_body += ", ";
|
||||
}
|
||||
}
|
||||
function_body += ")";
|
||||
if (EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints")) {
|
||||
function_body += " -> void";
|
||||
}
|
||||
function_body += ":\n\tpass # Replace with function body.\n";
|
||||
|
||||
LSP::TextEdit text_edit;
|
||||
|
||||
if (first_class != -1) {
|
||||
function_body += "\n\n";
|
||||
}
|
||||
text_edit.range.end.line = text_edit.range.start.line = start_line;
|
||||
|
||||
text_edit.newText = function_body;
|
||||
|
||||
String uri = get_file_uri(scr->get_path());
|
||||
|
||||
LSP::ApplyWorkspaceEditParams params;
|
||||
params.edit.add_edit(uri, text_edit);
|
||||
|
||||
GDScriptLanguageProtocol::get_singleton()->request_client("workspace/applyEdit", params.to_json());
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
|
||||
StringName class_name = p_class;
|
||||
StringName empty;
|
||||
|
||||
while (class_name != empty) {
|
||||
if (HashMap<StringName, LSP::DocumentSymbol>::ConstIterator E = native_symbols.find(class_name)) {
|
||||
const LSP::DocumentSymbol &class_symbol = E->value;
|
||||
|
||||
if (p_member.is_empty()) {
|
||||
return &class_symbol;
|
||||
} else {
|
||||
for (int i = 0; i < class_symbol.children.size(); i++) {
|
||||
const LSP::DocumentSymbol &symbol = class_symbol.children[i];
|
||||
if (symbol.name == p_member) {
|
||||
return &symbol;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Might contain pseudo classes like @GDScript that only exist in documentation.
|
||||
if (ClassDB::class_exists(class_name)) {
|
||||
class_name = ClassDB::get_parent_class(class_name);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
|
||||
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
|
||||
if (parser) {
|
||||
return &(parser->get_symbols());
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::get_parameter_symbol(const LSP::DocumentSymbol *p_parent, const String &symbol_identifier) {
|
||||
for (int i = 0; i < p_parent->children.size(); ++i) {
|
||||
const LSP::DocumentSymbol *parameter_symbol = &p_parent->children[i];
|
||||
if (!parameter_symbol->detail.is_empty() && parameter_symbol->name == symbol_identifier) {
|
||||
return parameter_symbol;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::get_local_symbol_at(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier, const LSP::Position p_position) {
|
||||
// Go down and pick closest `DocumentSymbol` with `p_symbol_identifier`.
|
||||
|
||||
const LSP::DocumentSymbol *current = &p_parser->get_symbols();
|
||||
const LSP::DocumentSymbol *best_match = nullptr;
|
||||
|
||||
while (current) {
|
||||
if (current->name == p_symbol_identifier) {
|
||||
if (current->selectionRange.contains(p_position)) {
|
||||
// Exact match: pos is ON symbol decl identifier.
|
||||
return current;
|
||||
}
|
||||
|
||||
best_match = current;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *parent = current;
|
||||
current = nullptr;
|
||||
for (const LSP::DocumentSymbol &child : parent->children) {
|
||||
if (child.range.contains(p_position)) {
|
||||
current = &child;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return best_match;
|
||||
}
|
||||
|
||||
void GDScriptWorkspace::reload_all_workspace_scripts() {
|
||||
List<String> paths;
|
||||
list_script_files("res://", paths);
|
||||
for (const String &path : paths) {
|
||||
ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
|
||||
if (parser == nullptr || parser->parse_result != OK) {
|
||||
String err_msg = "LSP: Failed to parse script: " + path;
|
||||
if (parser) {
|
||||
err_msg += "\n" + parser->get_errors().front()->get().message;
|
||||
}
|
||||
ERR_PRINT(err_msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
|
||||
Error err;
|
||||
Ref<DirAccess> dir = DirAccess::open(p_root_dir, &err);
|
||||
if (OK != err) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore scripts in directories with a .gdignore file.
|
||||
if (dir->file_exists(".gdignore")) {
|
||||
return;
|
||||
}
|
||||
|
||||
dir->list_dir_begin();
|
||||
String file_name = dir->get_next();
|
||||
while (file_name.length()) {
|
||||
if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
|
||||
list_script_files(p_root_dir.path_join(file_name), r_files);
|
||||
} else if (file_name.ends_with(".gd")) {
|
||||
String script_file = p_root_dir.path_join(file_name);
|
||||
r_files.push_back(script_file);
|
||||
}
|
||||
file_name = dir->get_next();
|
||||
}
|
||||
}
|
||||
|
||||
#define HANDLE_DOC(m_string) ((is_native ? DTR(m_string) : (m_string)).strip_edges())
|
||||
|
||||
Error GDScriptWorkspace::initialize() {
|
||||
if (initialized) {
|
||||
return OK;
|
||||
}
|
||||
|
||||
DocTools *doc = EditorHelp::get_doc_data();
|
||||
for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
|
||||
const DocData::ClassDoc &class_data = E.value;
|
||||
const bool is_native = !class_data.is_script_doc;
|
||||
LSP::DocumentSymbol class_symbol;
|
||||
String class_name = E.key;
|
||||
class_symbol.name = class_name;
|
||||
class_symbol.native_class = class_name;
|
||||
class_symbol.kind = LSP::SymbolKind::Class;
|
||||
class_symbol.detail = String("<Native> class ") + class_name;
|
||||
if (!class_data.inherits.is_empty()) {
|
||||
class_symbol.detail += " extends " + class_data.inherits;
|
||||
}
|
||||
class_symbol.documentation = HANDLE_DOC(class_data.brief_description) + "\n" + HANDLE_DOC(class_data.description);
|
||||
|
||||
for (int i = 0; i < class_data.constants.size(); i++) {
|
||||
const DocData::ConstantDoc &const_data = class_data.constants[i];
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = const_data.name;
|
||||
symbol.native_class = class_name;
|
||||
symbol.kind = LSP::SymbolKind::Constant;
|
||||
symbol.detail = "const " + class_name + "." + const_data.name;
|
||||
if (const_data.enumeration.length()) {
|
||||
symbol.detail += ": " + const_data.enumeration;
|
||||
}
|
||||
symbol.detail += " = " + const_data.value;
|
||||
symbol.documentation = HANDLE_DOC(const_data.description);
|
||||
class_symbol.children.push_back(symbol);
|
||||
}
|
||||
|
||||
for (int i = 0; i < class_data.properties.size(); i++) {
|
||||
const DocData::PropertyDoc &data = class_data.properties[i];
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = data.name;
|
||||
symbol.native_class = class_name;
|
||||
symbol.kind = LSP::SymbolKind::Property;
|
||||
symbol.detail = "var " + class_name + "." + data.name;
|
||||
if (data.enumeration.length()) {
|
||||
symbol.detail += ": " + data.enumeration;
|
||||
} else {
|
||||
symbol.detail += ": " + data.type;
|
||||
}
|
||||
symbol.documentation = HANDLE_DOC(data.description);
|
||||
class_symbol.children.push_back(symbol);
|
||||
}
|
||||
|
||||
for (int i = 0; i < class_data.theme_properties.size(); i++) {
|
||||
const DocData::ThemeItemDoc &data = class_data.theme_properties[i];
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = data.name;
|
||||
symbol.native_class = class_name;
|
||||
symbol.kind = LSP::SymbolKind::Property;
|
||||
symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type;
|
||||
symbol.documentation = HANDLE_DOC(data.description);
|
||||
class_symbol.children.push_back(symbol);
|
||||
}
|
||||
|
||||
Vector<DocData::MethodDoc> method_likes;
|
||||
method_likes.append_array(class_data.methods);
|
||||
method_likes.append_array(class_data.annotations);
|
||||
const int constructors_start_idx = method_likes.size();
|
||||
method_likes.append_array(class_data.constructors);
|
||||
const int operator_start_idx = method_likes.size();
|
||||
method_likes.append_array(class_data.operators);
|
||||
const int signal_start_idx = method_likes.size();
|
||||
method_likes.append_array(class_data.signals);
|
||||
|
||||
for (int i = 0; i < method_likes.size(); i++) {
|
||||
const DocData::MethodDoc &data = method_likes[i];
|
||||
|
||||
LSP::DocumentSymbol symbol;
|
||||
symbol.name = data.name;
|
||||
symbol.native_class = class_name;
|
||||
|
||||
if (i >= signal_start_idx) {
|
||||
symbol.kind = LSP::SymbolKind::Event;
|
||||
} else if (i >= operator_start_idx) {
|
||||
symbol.kind = LSP::SymbolKind::Operator;
|
||||
} else if (i >= constructors_start_idx) {
|
||||
symbol.kind = LSP::SymbolKind::Constructor;
|
||||
} else {
|
||||
symbol.kind = LSP::SymbolKind::Method;
|
||||
}
|
||||
|
||||
String params = "";
|
||||
bool arg_default_value_started = false;
|
||||
for (int j = 0; j < data.arguments.size(); j++) {
|
||||
const DocData::ArgumentDoc &arg = data.arguments[j];
|
||||
|
||||
LSP::DocumentSymbol symbol_arg;
|
||||
symbol_arg.name = arg.name;
|
||||
symbol_arg.kind = LSP::SymbolKind::Variable;
|
||||
symbol_arg.detail = arg.type;
|
||||
|
||||
if (!arg_default_value_started && !arg.default_value.is_empty()) {
|
||||
arg_default_value_started = true;
|
||||
}
|
||||
String arg_str = arg.name + ": " + arg.type;
|
||||
if (arg_default_value_started) {
|
||||
arg_str += " = " + arg.default_value;
|
||||
}
|
||||
if (j < data.arguments.size() - 1) {
|
||||
arg_str += ", ";
|
||||
}
|
||||
params += arg_str;
|
||||
|
||||
symbol.children.push_back(symbol_arg);
|
||||
}
|
||||
if (data.qualifiers.contains("vararg")) {
|
||||
params += params.is_empty() ? "..." : ", ...";
|
||||
}
|
||||
|
||||
String return_type = data.return_type;
|
||||
if (return_type.is_empty()) {
|
||||
return_type = "void";
|
||||
}
|
||||
symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
|
||||
symbol.documentation = HANDLE_DOC(data.description);
|
||||
class_symbol.children.push_back(symbol);
|
||||
}
|
||||
|
||||
native_symbols.insert(class_name, class_symbol);
|
||||
}
|
||||
|
||||
reload_all_workspace_scripts();
|
||||
|
||||
if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
|
||||
for (const KeyValue<StringName, LSP::DocumentSymbol> &E : native_symbols) {
|
||||
ClassMembers members;
|
||||
const LSP::DocumentSymbol &class_symbol = E.value;
|
||||
for (int i = 0; i < class_symbol.children.size(); i++) {
|
||||
const LSP::DocumentSymbol &symbol = class_symbol.children[i];
|
||||
members.insert(symbol.name, &symbol);
|
||||
}
|
||||
native_members.insert(E.key, members);
|
||||
}
|
||||
}
|
||||
|
||||
EditorNode *editor_node = EditorNode::get_singleton();
|
||||
editor_node->connect("script_add_function_request", callable_mp(this, &GDScriptWorkspace::apply_new_signal));
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
static bool is_valid_rename_target(const LSP::DocumentSymbol *p_symbol) {
|
||||
// Must be valid symbol.
|
||||
if (!p_symbol) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cannot rename builtin.
|
||||
if (!p_symbol->native_class.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Source must be available.
|
||||
if (p_symbol->script_path.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Dictionary GDScriptWorkspace::rename(const LSP::TextDocumentPositionParams &p_doc_pos, const String &new_name) {
|
||||
LSP::WorkspaceEdit edit;
|
||||
|
||||
const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
|
||||
if (is_valid_rename_target(reference_symbol)) {
|
||||
Vector<LSP::Location> usages = find_all_usages(*reference_symbol);
|
||||
for (int i = 0; i < usages.size(); ++i) {
|
||||
LSP::Location loc = usages[i];
|
||||
|
||||
edit.add_change(loc.uri, loc.range.start.line, loc.range.start.character, loc.range.end.character, new_name);
|
||||
}
|
||||
}
|
||||
|
||||
return edit.to_json();
|
||||
}
|
||||
|
||||
bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::DocumentSymbol &r_symbol, LSP::Range &r_range) {
|
||||
const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
|
||||
if (!is_valid_rename_target(reference_symbol)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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_symbol_name_under_position(p_doc_pos.position, r_range);
|
||||
r_symbol = *reference_symbol;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path) {
|
||||
Vector<LSP::Location> usages;
|
||||
|
||||
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();
|
||||
for (int i = 0; i < content.size(); ++i) {
|
||||
String line = content[i];
|
||||
|
||||
int character = line.find(identifier);
|
||||
while (character > -1) {
|
||||
LSP::TextDocumentPositionParams params;
|
||||
|
||||
LSP::TextDocumentIdentifier text_doc;
|
||||
text_doc.uri = get_file_uri(p_file_path);
|
||||
|
||||
params.textDocument = text_doc;
|
||||
params.position.line = i;
|
||||
params.position.character = character;
|
||||
|
||||
LSP::Range range;
|
||||
String identifier_under_cursor = parser->get_symbol_name_under_position(params.position, range);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return usages;
|
||||
}
|
||||
|
||||
Vector<LSP::Location> GDScriptWorkspace::find_all_usages(const LSP::DocumentSymbol &p_symbol) {
|
||||
if (p_symbol.local) {
|
||||
// Only search in current document.
|
||||
return find_usages_in_file(p_symbol, p_symbol.script_path);
|
||||
}
|
||||
// Search in all documents.
|
||||
List<String> paths;
|
||||
list_script_files("res://", paths);
|
||||
|
||||
Vector<LSP::Location> usages;
|
||||
for (const String &path : paths) {
|
||||
usages.append_array(find_usages_in_file(p_symbol, path));
|
||||
}
|
||||
return usages;
|
||||
}
|
||||
|
||||
String GDScriptWorkspace::get_file_path(const String &p_uri) {
|
||||
int port;
|
||||
String scheme;
|
||||
String host;
|
||||
String encoded_path;
|
||||
String fragment;
|
||||
|
||||
// Don't use the returned error, the result isn't OK for URIs that are not valid web URLs.
|
||||
p_uri.parse_url(scheme, host, port, encoded_path, fragment);
|
||||
|
||||
// TODO: Make the parsing RFC-3986 compliant.
|
||||
ERR_FAIL_COND_V_MSG(scheme != "file" && scheme != "file:" && scheme != "file://", String(), "LSP: The language server only supports the file protocol: " + p_uri);
|
||||
|
||||
// Treat host like authority for now and ignore the port. It's an edge case for invalid file URI's anyway.
|
||||
ERR_FAIL_COND_V_MSG(host != "" && host != "localhost", String(), "LSP: The language server does not support nonlocal files: " + p_uri);
|
||||
|
||||
// If query or fragment are present, the URI is not a valid file URI as per RFC-8089.
|
||||
// We currently don't handle the query and it will be part of the path. However,
|
||||
// this should not be a problem for a correct file URI.
|
||||
ERR_FAIL_COND_V_MSG(fragment != "", String(), "LSP: Received malformed file URI: " + p_uri);
|
||||
|
||||
String canonical_res = ProjectSettings::get_singleton()->get_resource_path();
|
||||
String simple_path = encoded_path.uri_file_decode().simplify_path();
|
||||
|
||||
// First try known paths that point to res://, to reduce file system interaction.
|
||||
bool res_adjusted = false;
|
||||
for (const String &res_path : absolute_res_paths) {
|
||||
if (simple_path.begins_with(res_path)) {
|
||||
res_adjusted = true;
|
||||
simple_path = "res://" + simple_path.substr(res_path.size());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Traverse the path and compare each directory with res://
|
||||
if (!res_adjusted) {
|
||||
Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
|
||||
|
||||
int offset = 0;
|
||||
while (offset <= simple_path.length()) {
|
||||
offset = simple_path.find_char('/', offset);
|
||||
if (offset == -1) {
|
||||
offset = simple_path.length();
|
||||
}
|
||||
|
||||
String part = simple_path.substr(0, offset);
|
||||
|
||||
if (!part.is_empty()) {
|
||||
bool is_equal = dir->is_equivalent(canonical_res, part);
|
||||
|
||||
if (is_equal) {
|
||||
absolute_res_paths.insert(part);
|
||||
res_adjusted = true;
|
||||
simple_path = "res://" + simple_path.substr(offset + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
offset += 1;
|
||||
}
|
||||
|
||||
// Could not resolve the path to the project.
|
||||
if (!res_adjusted) {
|
||||
return simple_path;
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the file inside of the project using EditorFileSystem.
|
||||
EditorFileSystemDirectory *editor_dir;
|
||||
int file_idx;
|
||||
editor_dir = EditorFileSystem::get_singleton()->find_file(simple_path, &file_idx);
|
||||
if (editor_dir) {
|
||||
return editor_dir->get_file_path(file_idx);
|
||||
}
|
||||
|
||||
return simple_path;
|
||||
}
|
||||
|
||||
String GDScriptWorkspace::get_file_uri(const String &p_path) const {
|
||||
String path = ProjectSettings::get_singleton()->globalize_path(p_path).lstrip("/");
|
||||
LocalVector<String> encoded_parts;
|
||||
for (const String &part : path.split("/")) {
|
||||
encoded_parts.push_back(part.uri_encode());
|
||||
}
|
||||
|
||||
// Always return file URI's with authority part (encoding drive letters with leading slash), to maintain compat with RFC-1738 which required it.
|
||||
return "file:///" + String("/").join(Vector<String>(encoded_parts));
|
||||
}
|
||||
|
||||
void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
|
||||
Dictionary params;
|
||||
Array errors;
|
||||
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
|
||||
if (parser) {
|
||||
const Vector<LSP::Diagnostic> &list = parser->get_diagnostics();
|
||||
errors.resize(list.size());
|
||||
for (int i = 0; i < list.size(); ++i) {
|
||||
errors[i] = list[i].to_json();
|
||||
}
|
||||
}
|
||||
params["diagnostics"] = errors;
|
||||
params["uri"] = get_file_uri(p_path);
|
||||
GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
|
||||
}
|
||||
|
||||
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;
|
||||
bool forced = false;
|
||||
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
|
||||
if (parser) {
|
||||
Node *owner_scene_node = GDScriptLanguageProtocol::get_singleton()->get_scene_cache()->get(path);
|
||||
|
||||
Array stack;
|
||||
Node *current = nullptr;
|
||||
if (owner_scene_node != nullptr) {
|
||||
stack.push_back(owner_scene_node);
|
||||
|
||||
while (!stack.is_empty()) {
|
||||
current = Object::cast_to<Node>(stack.pop_back());
|
||||
Ref<GDScript> scr = current->get_script();
|
||||
if (scr.is_valid() && GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < current->get_child_count(); ++i) {
|
||||
stack.push_back(current->get_child(i));
|
||||
}
|
||||
}
|
||||
|
||||
Ref<GDScript> scr = current->get_script();
|
||||
if (scr.is_null() || !GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
|
||||
current = owner_scene_node;
|
||||
}
|
||||
}
|
||||
|
||||
String code = parser->get_text_for_completion(p_params.position);
|
||||
GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
|
||||
}
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
|
||||
const LSP::DocumentSymbol *symbol = nullptr;
|
||||
|
||||
String path = get_file_path(p_doc_pos.textDocument.uri);
|
||||
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(path);
|
||||
if (parser) {
|
||||
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_name.is_empty()) {
|
||||
LSP::Range range;
|
||||
symbol_name = parser->get_symbol_name_under_position(p_doc_pos.position, range);
|
||||
pos.character = range.end.character;
|
||||
}
|
||||
|
||||
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;
|
||||
// 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_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()) {
|
||||
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_name);
|
||||
|
||||
if (symbol) {
|
||||
switch (symbol->kind) {
|
||||
case LSP::SymbolKind::Function: {
|
||||
if (symbol->name != symbol_name) {
|
||||
symbol = get_parameter_symbol(symbol, symbol_name);
|
||||
}
|
||||
} break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String member = ret.class_member;
|
||||
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_name, p_doc_pos.position);
|
||||
if (!symbol) {
|
||||
symbol = parser->get_member_symbol(symbol_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return symbol;
|
||||
}
|
||||
|
||||
const LSP::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params) {
|
||||
if (HashMap<StringName, LSP::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
|
||||
const LSP::DocumentSymbol &symbol = E->value;
|
||||
if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
|
||||
return &symbol;
|
||||
}
|
||||
|
||||
for (int i = 0; i < symbol.children.size(); ++i) {
|
||||
if (symbol.children[i].name == p_params.symbol_name) {
|
||||
return &(symbol.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list) {
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(get_file_path(p_uri));
|
||||
if (parser && parser->parse_result == Error::OK) {
|
||||
const List<LSP::DocumentLink> &links = parser->get_document_links();
|
||||
for (const LSP::DocumentLink &E : links) {
|
||||
r_list.push_back(E);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
|
||||
Dictionary api;
|
||||
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(p_path);
|
||||
if (parser) {
|
||||
api = parser->generate_api();
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature) {
|
||||
const ExtendGDScriptParser *parser = GDScriptLanguageProtocol::get_singleton()->get_parse_result(get_file_path(p_doc_pos.textDocument.uri));
|
||||
if (parser) {
|
||||
LSP::TextDocumentPositionParams text_pos;
|
||||
text_pos.textDocument = p_doc_pos.textDocument;
|
||||
|
||||
if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
|
||||
List<const LSP::DocumentSymbol *> symbols;
|
||||
|
||||
if (const LSP::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
|
||||
symbols.push_back(symbol);
|
||||
} else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
|
||||
GDScriptLanguageProtocol::get_singleton()->resolve_related_symbols(text_pos, symbols);
|
||||
}
|
||||
|
||||
for (const LSP::DocumentSymbol *const &symbol : symbols) {
|
||||
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();
|
||||
|
||||
for (int i = 0; i < symbol->children.size(); i++) {
|
||||
const LSP::DocumentSymbol &arg = symbol->children[i];
|
||||
LSP::ParameterInformation arg_info;
|
||||
arg_info.label = arg.name;
|
||||
signature_info.parameters.push_back(arg_info);
|
||||
}
|
||||
r_signature.signatures.push_back(signature_info);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (r_signature.signatures.size()) {
|
||||
return OK;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ERR_METHOD_NOT_FOUND;
|
||||
}
|
||||
|
||||
GDScriptWorkspace::GDScriptWorkspace() {}
|
||||
|
||||
GDScriptWorkspace::~GDScriptWorkspace() {}
|
||||
102
engine/modules/gdscript/language_server/gdscript_workspace.h
Normal file
102
engine/modules/gdscript/language_server/gdscript_workspace.h
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
/**************************************************************************/
|
||||
/* gdscript_workspace.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 "gdscript_extend_parser.h"
|
||||
#include "godot_lsp.h"
|
||||
|
||||
#include "core/error/error_macros.h"
|
||||
#include "core/variant/variant.h"
|
||||
|
||||
class GDScriptWorkspace : public RefCounted {
|
||||
GDCLASS(GDScriptWorkspace, RefCounted);
|
||||
|
||||
private:
|
||||
#ifndef DISABLE_DEPRECATED
|
||||
void didDeleteFiles(const Dictionary &p_params) {}
|
||||
Error parse_script(const String &p_path, const String &p_content) {
|
||||
WARN_DEPRECATED;
|
||||
return Error::FAILED;
|
||||
}
|
||||
Error parse_local_script(const String &p_path) {
|
||||
WARN_DEPRECATED;
|
||||
return Error::FAILED;
|
||||
}
|
||||
#endif // DISABLE_DEPRECATED
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
bool initialized = false;
|
||||
HashMap<StringName, LSP::DocumentSymbol> native_symbols;
|
||||
|
||||
// Absolute paths that are known to point to res://
|
||||
HashSet<String> absolute_res_paths;
|
||||
|
||||
const LSP::DocumentSymbol *get_native_symbol(const String &p_class, const String &p_member = "") const;
|
||||
const LSP::DocumentSymbol *get_script_symbol(const String &p_path) const;
|
||||
const LSP::DocumentSymbol *get_parameter_symbol(const LSP::DocumentSymbol *p_parent, const String &symbol_identifier);
|
||||
const LSP::DocumentSymbol *get_local_symbol_at(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier, const LSP::Position p_position);
|
||||
|
||||
void reload_all_workspace_scripts();
|
||||
|
||||
void list_script_files(const String &p_root_dir, List<String> &r_files);
|
||||
|
||||
void apply_new_signal(Object *obj, String function, PackedStringArray args);
|
||||
|
||||
public:
|
||||
String root;
|
||||
String root_uri;
|
||||
|
||||
HashMap<StringName, ClassMembers> native_members;
|
||||
|
||||
public:
|
||||
Error initialize();
|
||||
|
||||
String get_file_path(const String &p_uri);
|
||||
String get_file_uri(const String &p_path) const;
|
||||
|
||||
void publish_diagnostics(const String &p_path);
|
||||
void completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options);
|
||||
|
||||
const LSP::DocumentSymbol *resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name = "", bool p_func_required = false);
|
||||
|
||||
const LSP::DocumentSymbol *resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params);
|
||||
void resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list);
|
||||
Dictionary generate_script_api(const String &p_path);
|
||||
Error resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature);
|
||||
Dictionary rename(const LSP::TextDocumentPositionParams &p_doc_pos, const String &new_name);
|
||||
bool can_rename(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::DocumentSymbol &r_symbol, LSP::Range &r_range);
|
||||
Vector<LSP::Location> find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path);
|
||||
Vector<LSP::Location> find_all_usages(const LSP::DocumentSymbol &p_symbol);
|
||||
|
||||
GDScriptWorkspace();
|
||||
~GDScriptWorkspace();
|
||||
};
|
||||
2140
engine/modules/gdscript/language_server/godot_lsp.h
Normal file
2140
engine/modules/gdscript/language_server/godot_lsp.h
Normal file
File diff suppressed because it is too large
Load diff
186
engine/modules/gdscript/language_server/scene_cache.cpp
Normal file
186
engine/modules/gdscript/language_server/scene_cache.cpp
Normal 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.");
|
||||
}
|
||||
65
engine/modules/gdscript/language_server/scene_cache.h
Normal file
65
engine/modules/gdscript/language_server/scene_cache.h
Normal 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);
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue