1/**************************************************************************/
2/* gdscript_extend_parser.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "gdscript_extend_parser.h"
32
33#include "../gdscript.h"
34#include "../gdscript_analyzer.h"
35#include "editor/editor_settings.h"
36#include "gdscript_language_protocol.h"
37#include "gdscript_workspace.h"
38
39int get_indent_size() {
40 if (EditorSettings::get_singleton()) {
41 return EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
42 } else {
43 return 4;
44 }
45}
46
47lsp::Position GodotPosition::to_lsp(const Vector<String> &p_lines) const {
48 lsp::Position res;
49
50 // Special case: `line = 0` -> root class (range covers everything).
51 if (this->line <= 0) {
52 return res;
53 }
54 // Special case: `line = p_lines.size() + 1` -> root class (range covers everything).
55 if (this->line >= p_lines.size() + 1) {
56 res.line = p_lines.size();
57 return res;
58 }
59 res.line = this->line - 1;
60 // Note: character outside of `pos_line.length()-1` is valid.
61 res.character = this->column - 1;
62
63 String pos_line = p_lines[res.line];
64 if (pos_line.contains("\t")) {
65 int tab_size = get_indent_size();
66
67 int in_col = 1;
68 int res_char = 0;
69
70 while (res_char < pos_line.size() && in_col < this->column) {
71 if (pos_line[res_char] == '\t') {
72 in_col += tab_size;
73 res_char++;
74 } else {
75 in_col++;
76 res_char++;
77 }
78 }
79
80 res.character = res_char;
81 }
82
83 return res;
84}
85
86GodotPosition GodotPosition::from_lsp(const lsp::Position p_pos, const Vector<String> &p_lines) {
87 GodotPosition res(p_pos.line + 1, p_pos.character + 1);
88
89 // Line outside of actual text is valid (-> pos/cursor at end of text).
90 if (res.line > p_lines.size()) {
91 return res;
92 }
93
94 String line = p_lines[p_pos.line];
95 int tabs_before_char = 0;
96 for (int i = 0; i < p_pos.character && i < line.length(); i++) {
97 if (line[i] == '\t') {
98 tabs_before_char++;
99 }
100 }
101
102 if (tabs_before_char > 0) {
103 int tab_size = get_indent_size();
104 res.column += tabs_before_char * (tab_size - 1);
105 }
106
107 return res;
108}
109
110lsp::Range GodotRange::to_lsp(const Vector<String> &p_lines) const {
111 lsp::Range res;
112 res.start = start.to_lsp(p_lines);
113 res.end = end.to_lsp(p_lines);
114 return res;
115}
116
117GodotRange GodotRange::from_lsp(const lsp::Range &p_range, const Vector<String> &p_lines) {
118 GodotPosition start = GodotPosition::from_lsp(p_range.start, p_lines);
119 GodotPosition end = GodotPosition::from_lsp(p_range.end, p_lines);
120 return GodotRange(start, end);
121}
122
123void ExtendGDScriptParser::update_diagnostics() {
124 diagnostics.clear();
125
126 const List<ParserError> &parser_errors = get_errors();
127 for (const ParserError &error : parser_errors) {
128 lsp::Diagnostic diagnostic;
129 diagnostic.severity = lsp::DiagnosticSeverity::Error;
130 diagnostic.message = error.message;
131 diagnostic.source = "gdscript";
132 diagnostic.code = -1;
133 lsp::Range range;
134 lsp::Position pos;
135 const PackedStringArray line_array = get_lines();
136 int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, line_array.size() - 1);
137 const String &line_text = line_array[line];
138 pos.line = line;
139 pos.character = line_text.length() - line_text.strip_edges(true, false).length();
140 range.start = pos;
141 range.end = range.start;
142 range.end.character = line_text.strip_edges(false).length();
143 diagnostic.range = range;
144 diagnostics.push_back(diagnostic);
145 }
146
147 const List<GDScriptWarning> &parser_warnings = get_warnings();
148 for (const GDScriptWarning &warning : parser_warnings) {
149 lsp::Diagnostic diagnostic;
150 diagnostic.severity = lsp::DiagnosticSeverity::Warning;
151 diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message();
152 diagnostic.source = "gdscript";
153 diagnostic.code = warning.code;
154 lsp::Range range;
155 lsp::Position pos;
156 int line = LINE_NUMBER_TO_INDEX(warning.start_line);
157 const String &line_text = get_lines()[line];
158 pos.line = line;
159 pos.character = line_text.length() - line_text.strip_edges(true, false).length();
160 range.start = pos;
161 range.end = pos;
162 range.end.character = line_text.strip_edges(false).length();
163 diagnostic.range = range;
164 diagnostics.push_back(diagnostic);
165 }
166}
167
168void ExtendGDScriptParser::update_symbols() {
169 members.clear();
170
171 if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
172 parse_class_symbol(gdclass, class_symbol);
173
174 for (int i = 0; i < class_symbol.children.size(); i++) {
175 const lsp::DocumentSymbol &symbol = class_symbol.children[i];
176 members.insert(symbol.name, &symbol);
177
178 // Cache level one inner classes.
179 if (symbol.kind == lsp::SymbolKind::Class) {
180 ClassMembers inner_class;
181 for (int j = 0; j < symbol.children.size(); j++) {
182 const lsp::DocumentSymbol &s = symbol.children[j];
183 inner_class.insert(s.name, &s);
184 }
185 inner_classes.insert(symbol.name, inner_class);
186 }
187 }
188 }
189}
190
191void ExtendGDScriptParser::update_document_links(const String &p_code) {
192 document_links.clear();
193
194 GDScriptTokenizer scr_tokenizer;
195 Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES);
196 scr_tokenizer.set_source_code(p_code);
197 while (true) {
198 GDScriptTokenizer::Token token = scr_tokenizer.scan();
199 if (token.type == GDScriptTokenizer::Token::TK_EOF) {
200 break;
201 } else if (token.type == GDScriptTokenizer::Token::LITERAL) {
202 const Variant &const_val = token.literal;
203 if (const_val.get_type() == Variant::STRING) {
204 String scr_path = const_val;
205 bool exists = fs->file_exists(scr_path);
206 if (!exists) {
207 scr_path = get_path().get_base_dir() + "/" + scr_path;
208 exists = fs->file_exists(scr_path);
209 }
210 if (exists) {
211 String value = const_val;
212 lsp::DocumentLink link;
213 link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(scr_path);
214 link.range = GodotRange(GodotPosition(token.start_line, token.start_column), GodotPosition(token.end_line, token.end_column)).to_lsp(this->lines);
215 document_links.push_back(link);
216 }
217 }
218 }
219 }
220}
221
222lsp::Range ExtendGDScriptParser::range_of_node(const GDScriptParser::Node *p_node) const {
223 GodotPosition start(p_node->start_line, p_node->start_column);
224 GodotPosition end(p_node->end_line, p_node->end_column);
225 return GodotRange(start, end).to_lsp(this->lines);
226}
227
228void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol) {
229 const String uri = get_uri();
230
231 r_symbol.uri = uri;
232 r_symbol.script_path = path;
233 r_symbol.children.clear();
234 r_symbol.name = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
235 if (r_symbol.name.is_empty()) {
236 r_symbol.name = path.get_file();
237 }
238 r_symbol.kind = lsp::SymbolKind::Class;
239 r_symbol.deprecated = false;
240 r_symbol.range = range_of_node(p_class);
241 r_symbol.range.start.line = MAX(r_symbol.range.start.line, 0);
242 if (p_class->identifier) {
243 r_symbol.selectionRange = range_of_node(p_class->identifier);
244 }
245 r_symbol.detail = "class " + r_symbol.name;
246 {
247 String doc = p_class->doc_data.description;
248 if (!p_class->doc_data.description.is_empty()) {
249 doc += "\n\n" + p_class->doc_data.description;
250 }
251
252 if (!p_class->doc_data.tutorials.is_empty()) {
253 doc += "\n";
254 for (const Pair<String, String> &tutorial : p_class->doc_data.tutorials) {
255 if (tutorial.first.is_empty()) {
256 doc += vformat("\n@tutorial: %s", tutorial.second);
257 } else {
258 doc += vformat("\n@tutorial(%s): %s", tutorial.first, tutorial.second);
259 }
260 }
261 }
262 r_symbol.documentation = doc;
263 }
264
265 for (int i = 0; i < p_class->members.size(); i++) {
266 const ClassNode::Member &m = p_class->members[i];
267
268 switch (m.type) {
269 case ClassNode::Member::VARIABLE: {
270 lsp::DocumentSymbol symbol;
271 symbol.name = m.variable->identifier->name;
272 symbol.kind = m.variable->property == VariableNode::PROP_NONE ? lsp::SymbolKind::Variable : lsp::SymbolKind::Property;
273 symbol.deprecated = false;
274 symbol.range = range_of_node(m.variable);
275 symbol.selectionRange = range_of_node(m.variable->identifier);
276 if (m.variable->exported) {
277 symbol.detail += "@export ";
278 }
279 symbol.detail += "var " + m.variable->identifier->name;
280 if (m.get_datatype().is_hard_type()) {
281 symbol.detail += ": " + m.get_datatype().to_string();
282 }
283 if (m.variable->initializer != nullptr && m.variable->initializer->is_constant) {
284 symbol.detail += " = " + m.variable->initializer->reduced_value.to_json_string();
285 }
286
287 symbol.documentation = m.variable->doc_data.description;
288 symbol.uri = uri;
289 symbol.script_path = path;
290
291 if (m.variable->initializer && m.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
292 GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)m.variable->initializer;
293 lsp::DocumentSymbol lambda;
294 parse_function_symbol(lambda_node->function, lambda);
295 // Merge lambda into current variable.
296 symbol.children.append_array(lambda.children);
297 }
298
299 if (m.variable->getter && m.variable->getter->type == GDScriptParser::Node::FUNCTION) {
300 lsp::DocumentSymbol get_symbol;
301 parse_function_symbol(m.variable->getter, get_symbol);
302 get_symbol.local = true;
303 symbol.children.push_back(get_symbol);
304 }
305 if (m.variable->setter && m.variable->setter->type == GDScriptParser::Node::FUNCTION) {
306 lsp::DocumentSymbol set_symbol;
307 parse_function_symbol(m.variable->setter, set_symbol);
308 set_symbol.local = true;
309 symbol.children.push_back(set_symbol);
310 }
311
312 r_symbol.children.push_back(symbol);
313 } break;
314 case ClassNode::Member::CONSTANT: {
315 lsp::DocumentSymbol symbol;
316
317 symbol.name = m.constant->identifier->name;
318 symbol.kind = lsp::SymbolKind::Constant;
319 symbol.deprecated = false;
320 symbol.range = range_of_node(m.constant);
321 symbol.selectionRange = range_of_node(m.constant->identifier);
322 symbol.documentation = m.constant->doc_data.description;
323 symbol.uri = uri;
324 symbol.script_path = path;
325
326 symbol.detail = "const " + symbol.name;
327 if (m.constant->get_datatype().is_hard_type()) {
328 symbol.detail += ": " + m.constant->get_datatype().to_string();
329 }
330
331 const Variant &default_value = m.constant->initializer->reduced_value;
332 String value_text;
333 if (default_value.get_type() == Variant::OBJECT) {
334 Ref<Resource> res = default_value;
335 if (res.is_valid() && !res->get_path().is_empty()) {
336 value_text = "preload(\"" + res->get_path() + "\")";
337 if (symbol.documentation.is_empty()) {
338 if (HashMap<String, ExtendGDScriptParser *>::Iterator S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
339 symbol.documentation = S->value->class_symbol.documentation;
340 }
341 }
342 } else {
343 value_text = default_value.to_json_string();
344 }
345 } else {
346 value_text = default_value.to_json_string();
347 }
348 if (!value_text.is_empty()) {
349 symbol.detail += " = " + value_text;
350 }
351
352 r_symbol.children.push_back(symbol);
353 } break;
354 case ClassNode::Member::SIGNAL: {
355 lsp::DocumentSymbol symbol;
356 symbol.name = m.signal->identifier->name;
357 symbol.kind = lsp::SymbolKind::Event;
358 symbol.deprecated = false;
359 symbol.range = range_of_node(m.signal);
360 symbol.selectionRange = range_of_node(m.signal->identifier);
361 symbol.documentation = m.signal->doc_data.description;
362 symbol.uri = uri;
363 symbol.script_path = path;
364 symbol.detail = "signal " + String(m.signal->identifier->name) + "(";
365 for (int j = 0; j < m.signal->parameters.size(); j++) {
366 if (j > 0) {
367 symbol.detail += ", ";
368 }
369 symbol.detail += m.signal->parameters[j]->identifier->name;
370 }
371 symbol.detail += ")";
372
373 for (GDScriptParser::ParameterNode *param : m.signal->parameters) {
374 lsp::DocumentSymbol param_symbol;
375 param_symbol.name = param->identifier->name;
376 param_symbol.kind = lsp::SymbolKind::Variable;
377 param_symbol.deprecated = false;
378 param_symbol.local = true;
379 param_symbol.range = range_of_node(param);
380 param_symbol.selectionRange = range_of_node(param->identifier);
381 param_symbol.uri = uri;
382 param_symbol.script_path = path;
383 param_symbol.detail = "var " + param_symbol.name;
384 if (param->get_datatype().is_hard_type()) {
385 param_symbol.detail += ": " + param->get_datatype().to_string();
386 }
387 symbol.children.push_back(param_symbol);
388 }
389 r_symbol.children.push_back(symbol);
390 } break;
391 case ClassNode::Member::ENUM_VALUE: {
392 lsp::DocumentSymbol symbol;
393
394 symbol.name = m.enum_value.identifier->name;
395 symbol.kind = lsp::SymbolKind::EnumMember;
396 symbol.deprecated = false;
397 symbol.range.start = GodotPosition(m.enum_value.line, m.enum_value.leftmost_column).to_lsp(this->lines);
398 symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.rightmost_column).to_lsp(this->lines);
399 symbol.selectionRange = range_of_node(m.enum_value.identifier);
400 symbol.documentation = m.enum_value.doc_data.description;
401 symbol.uri = uri;
402 symbol.script_path = path;
403
404 symbol.detail = symbol.name + " = " + itos(m.enum_value.value);
405
406 r_symbol.children.push_back(symbol);
407 } break;
408 case ClassNode::Member::ENUM: {
409 lsp::DocumentSymbol symbol;
410 symbol.name = m.m_enum->identifier->name;
411 symbol.kind = lsp::SymbolKind::Enum;
412 symbol.range = range_of_node(m.m_enum);
413 symbol.selectionRange = range_of_node(m.m_enum->identifier);
414 symbol.documentation = m.m_enum->doc_data.description;
415 symbol.uri = uri;
416 symbol.script_path = path;
417
418 symbol.detail = "enum " + String(m.m_enum->identifier->name) + "{";
419 for (int j = 0; j < m.m_enum->values.size(); j++) {
420 if (j > 0) {
421 symbol.detail += ", ";
422 }
423 symbol.detail += String(m.m_enum->values[j].identifier->name) + " = " + itos(m.m_enum->values[j].value);
424 }
425 symbol.detail += "}";
426
427 for (GDScriptParser::EnumNode::Value value : m.m_enum->values) {
428 lsp::DocumentSymbol child;
429
430 child.name = value.identifier->name;
431 child.kind = lsp::SymbolKind::EnumMember;
432 child.deprecated = false;
433 child.range.start = GodotPosition(value.line, value.leftmost_column).to_lsp(this->lines);
434 child.range.end = GodotPosition(value.line, value.rightmost_column).to_lsp(this->lines);
435 child.selectionRange = range_of_node(value.identifier);
436 child.documentation = value.doc_data.description;
437 child.uri = uri;
438 child.script_path = path;
439
440 child.detail = child.name + " = " + itos(value.value);
441
442 symbol.children.push_back(child);
443 }
444
445 r_symbol.children.push_back(symbol);
446 } break;
447 case ClassNode::Member::FUNCTION: {
448 lsp::DocumentSymbol symbol;
449 parse_function_symbol(m.function, symbol);
450 r_symbol.children.push_back(symbol);
451 } break;
452 case ClassNode::Member::CLASS: {
453 lsp::DocumentSymbol symbol;
454 parse_class_symbol(m.m_class, symbol);
455 r_symbol.children.push_back(symbol);
456 } break;
457 case ClassNode::Member::GROUP:
458 break; // No-op, but silences warnings.
459 case ClassNode::Member::UNDEFINED:
460 break; // Unreachable.
461 }
462 }
463}
464
465void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol) {
466 const String uri = get_uri();
467
468 bool is_named = p_func->identifier != nullptr;
469
470 r_symbol.name = is_named ? p_func->identifier->name : "";
471 r_symbol.kind = (p_func->is_static || p_func->source_lambda != nullptr) ? lsp::SymbolKind::Function : lsp::SymbolKind::Method;
472 r_symbol.detail = "func";
473 if (is_named) {
474 r_symbol.detail += " " + String(p_func->identifier->name);
475 }
476 r_symbol.detail += "(";
477 r_symbol.deprecated = false;
478 r_symbol.range = range_of_node(p_func);
479 if (is_named) {
480 r_symbol.selectionRange = range_of_node(p_func->identifier);
481 } else {
482 r_symbol.selectionRange.start = r_symbol.selectionRange.end = r_symbol.range.start;
483 }
484 r_symbol.documentation = p_func->doc_data.description;
485 r_symbol.uri = uri;
486 r_symbol.script_path = path;
487
488 String parameters;
489 for (int i = 0; i < p_func->parameters.size(); i++) {
490 const ParameterNode *parameter = p_func->parameters[i];
491 if (i > 0) {
492 parameters += ", ";
493 }
494 parameters += String(parameter->identifier->name);
495 if (parameter->get_datatype().is_hard_type()) {
496 parameters += ": " + parameter->get_datatype().to_string();
497 }
498 if (parameter->initializer != nullptr) {
499 parameters += " = " + parameter->initializer->reduced_value.to_json_string();
500 }
501 }
502 r_symbol.detail += parameters + ")";
503 if (p_func->get_datatype().is_hard_type()) {
504 r_symbol.detail += " -> " + p_func->get_datatype().to_string();
505 }
506
507 List<GDScriptParser::SuiteNode *> function_nodes;
508
509 List<GDScriptParser::Node *> node_stack;
510 node_stack.push_back(p_func->body);
511
512 while (!node_stack.is_empty()) {
513 GDScriptParser::Node *node = node_stack[0];
514 node_stack.pop_front();
515
516 switch (node->type) {
517 case GDScriptParser::TypeNode::IF: {
518 GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node;
519 node_stack.push_back(if_node->true_block);
520 if (if_node->false_block) {
521 node_stack.push_back(if_node->false_block);
522 }
523 } break;
524
525 case GDScriptParser::TypeNode::FOR: {
526 GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node;
527 node_stack.push_back(for_node->loop);
528 } break;
529
530 case GDScriptParser::TypeNode::WHILE: {
531 GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node;
532 node_stack.push_back(while_node->loop);
533 } break;
534
535 case GDScriptParser::TypeNode::MATCH: {
536 GDScriptParser::MatchNode *match_node = (GDScriptParser::MatchNode *)node;
537 for (GDScriptParser::MatchBranchNode *branch_node : match_node->branches) {
538 node_stack.push_back(branch_node);
539 }
540 } break;
541
542 case GDScriptParser::TypeNode::MATCH_BRANCH: {
543 GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node;
544 node_stack.push_back(match_node->block);
545 } break;
546
547 case GDScriptParser::TypeNode::SUITE: {
548 GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node;
549 function_nodes.push_back(suite_node);
550 for (int i = 0; i < suite_node->statements.size(); ++i) {
551 node_stack.push_back(suite_node->statements[i]);
552 }
553 } break;
554
555 default:
556 continue;
557 }
558 }
559
560 for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) {
561 const GDScriptParser::SuiteNode *suite_node = N->get();
562 for (int i = 0; i < suite_node->locals.size(); i++) {
563 const SuiteNode::Local &local = suite_node->locals[i];
564 lsp::DocumentSymbol symbol;
565 symbol.name = local.name;
566 symbol.kind = local.type == SuiteNode::Local::CONSTANT ? lsp::SymbolKind::Constant : lsp::SymbolKind::Variable;
567 switch (local.type) {
568 case SuiteNode::Local::CONSTANT:
569 symbol.range = range_of_node(local.constant);
570 symbol.selectionRange = range_of_node(local.constant->identifier);
571 break;
572 case SuiteNode::Local::VARIABLE:
573 symbol.range = range_of_node(local.variable);
574 symbol.selectionRange = range_of_node(local.variable->identifier);
575 if (local.variable->initializer && local.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
576 GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)local.variable->initializer;
577 lsp::DocumentSymbol lambda;
578 parse_function_symbol(lambda_node->function, lambda);
579 // Merge lambda into current variable.
580 // -> Only interested in new variables, not lambda itself.
581 symbol.children.append_array(lambda.children);
582 }
583 break;
584 case SuiteNode::Local::PARAMETER:
585 symbol.range = range_of_node(local.parameter);
586 symbol.selectionRange = range_of_node(local.parameter->identifier);
587 break;
588 case SuiteNode::Local::FOR_VARIABLE:
589 case SuiteNode::Local::PATTERN_BIND:
590 symbol.range = range_of_node(local.bind);
591 symbol.selectionRange = range_of_node(local.bind);
592 break;
593 default:
594 // Fallback.
595 symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp(get_lines());
596 symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp(get_lines());
597 symbol.selectionRange = symbol.range;
598 break;
599 }
600 symbol.local = true;
601 symbol.uri = uri;
602 symbol.script_path = path;
603 symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var ";
604 symbol.detail += symbol.name;
605 if (local.get_datatype().is_hard_type()) {
606 symbol.detail += ": " + local.get_datatype().to_string();
607 }
608 switch (local.type) {
609 case SuiteNode::Local::CONSTANT:
610 symbol.documentation = local.constant->doc_data.description;
611 break;
612 case SuiteNode::Local::VARIABLE:
613 symbol.documentation = local.variable->doc_data.description;
614 break;
615 default:
616 break;
617 }
618 r_symbol.children.push_back(symbol);
619 }
620 }
621}
622
623String ExtendGDScriptParser::get_text_for_completion(const lsp::Position &p_cursor) const {
624 String longthing;
625 int len = lines.size();
626 for (int i = 0; i < len; i++) {
627 if (i == p_cursor.line) {
628 longthing += lines[i].substr(0, p_cursor.character);
629 longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
630 longthing += lines[i].substr(p_cursor.character, lines[i].size());
631 } else {
632 longthing += lines[i];
633 }
634
635 if (i != len - 1) {
636 longthing += "\n";
637 }
638 }
639
640 return longthing;
641}
642
643String ExtendGDScriptParser::get_text_for_lookup_symbol(const lsp::Position &p_cursor, const String &p_symbol, bool p_func_required) const {
644 String longthing;
645 int len = lines.size();
646 for (int i = 0; i < len; i++) {
647 if (i == p_cursor.line) {
648 String line = lines[i];
649 String first_part = line.substr(0, p_cursor.character);
650 String last_part = line.substr(p_cursor.character, lines[i].length());
651 if (!p_symbol.is_empty()) {
652 String left_cursor_text;
653 for (int c = p_cursor.character - 1; c >= 0; c--) {
654 left_cursor_text = line.substr(c, p_cursor.character - c);
655 if (p_symbol.begins_with(left_cursor_text)) {
656 first_part = line.substr(0, c);
657 first_part += p_symbol;
658 break;
659 }
660 }
661 }
662
663 longthing += first_part;
664 longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
665 if (p_func_required) {
666 longthing += "("; // Tell the parser this is a function call.
667 }
668 longthing += last_part;
669 } else {
670 longthing += lines[i];
671 }
672
673 if (i != len - 1) {
674 longthing += "\n";
675 }
676 }
677
678 return longthing;
679}
680
681String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &p_position, lsp::Range &r_range) const {
682 ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
683 String line = lines[p_position.line];
684 if (line.is_empty()) {
685 return "";
686 }
687 ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
688
689 // `p_position` cursor is BETWEEN chars, not ON chars.
690 // ->
691 // ```gdscript
692 // var member| := some_func|(some_variable|)
693 // ^ ^ ^
694 // | | | cursor on `some_variable, position on `)`
695 // | |
696 // | | cursor on `some_func`, pos on `(`
697 // |
698 // | cursor on `member`, pos on ` ` (space)
699 // ```
700 // -> Move position to previous character if:
701 // * Position not on valid identifier char.
702 // * Prev position is valid identifier char.
703 lsp::Position pos = p_position;
704 if (
705 pos.character >= line.length() // Cursor at end of line.
706 || (!is_ascii_identifier_char(line[pos.character]) // Not on valid identifier char.
707 && (pos.character > 0 // Not line start -> there is a prev char.
708 && is_ascii_identifier_char(line[pos.character - 1]) // Prev is valid identifier char.
709 ))) {
710 pos.character--;
711 }
712
713 int start_pos = pos.character;
714 for (int c = pos.character; c >= 0; c--) {
715 start_pos = c;
716 char32_t ch = line[c];
717 bool valid_char = is_ascii_identifier_char(ch);
718 if (!valid_char) {
719 break;
720 }
721 }
722
723 int end_pos = pos.character;
724 for (int c = pos.character; c < line.length(); c++) {
725 char32_t ch = line[c];
726 bool valid_char = is_ascii_identifier_char(ch);
727 if (!valid_char) {
728 break;
729 }
730 end_pos = c;
731 }
732
733 if (start_pos < end_pos) {
734 r_range.start.line = r_range.end.line = pos.line;
735 r_range.start.character = start_pos + 1;
736 r_range.end.character = end_pos + 1;
737 return line.substr(start_pos + 1, end_pos - start_pos);
738 }
739
740 return "";
741}
742
743String ExtendGDScriptParser::get_uri() const {
744 return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
745}
746
747const lsp::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const lsp::DocumentSymbol &p_parent, const String &p_symbol_name) const {
748 const lsp::DocumentSymbol *ret = nullptr;
749 if (p_line < p_parent.range.start.line) {
750 return ret;
751 } else if (p_parent.range.start.line == p_line && (p_symbol_name.is_empty() || p_parent.name == p_symbol_name)) {
752 return &p_parent;
753 } else {
754 for (int i = 0; i < p_parent.children.size(); i++) {
755 ret = search_symbol_defined_at_line(p_line, p_parent.children[i], p_symbol_name);
756 if (ret) {
757 break;
758 }
759 }
760 }
761 return ret;
762}
763
764Error ExtendGDScriptParser::get_left_function_call(const lsp::Position &p_position, lsp::Position &r_func_pos, int &r_arg_index) const {
765 ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
766
767 int bracket_stack = 0;
768 int index = 0;
769
770 bool found = false;
771 for (int l = p_position.line; l >= 0; --l) {
772 String line = lines[l];
773 int c = line.length() - 1;
774 if (l == p_position.line) {
775 c = MIN(c, p_position.character - 1);
776 }
777
778 while (c >= 0) {
779 const char32_t &character = line[c];
780 if (character == ')') {
781 ++bracket_stack;
782 } else if (character == '(') {
783 --bracket_stack;
784 if (bracket_stack < 0) {
785 found = true;
786 }
787 }
788 if (bracket_stack <= 0 && character == ',') {
789 ++index;
790 }
791 --c;
792 if (found) {
793 r_func_pos.character = c;
794 break;
795 }
796 }
797
798 if (found) {
799 r_func_pos.line = l;
800 r_arg_index = index;
801 return OK;
802 }
803 }
804
805 return ERR_METHOD_NOT_FOUND;
806}
807
808const lsp::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line, const String &p_symbol_name) const {
809 if (p_line <= 0) {
810 return &class_symbol;
811 }
812 return search_symbol_defined_at_line(p_line, class_symbol, p_symbol_name);
813}
814
815const lsp::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
816 if (p_subclass.is_empty()) {
817 const lsp::DocumentSymbol *const *ptr = members.getptr(p_name);
818 if (ptr) {
819 return *ptr;
820 }
821 } else {
822 if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
823 const lsp::DocumentSymbol *const *ptr = _class->getptr(p_name);
824 if (ptr) {
825 return *ptr;
826 }
827 }
828 }
829
830 return nullptr;
831}
832
833const List<lsp::DocumentLink> &ExtendGDScriptParser::get_document_links() const {
834 return document_links;
835}
836
837const Array &ExtendGDScriptParser::get_member_completions() {
838 if (member_completions.is_empty()) {
839 for (const KeyValue<String, const lsp::DocumentSymbol *> &E : members) {
840 const lsp::DocumentSymbol *symbol = E.value;
841 lsp::CompletionItem item = symbol->make_completion_item();
842 item.data = JOIN_SYMBOLS(path, E.key);
843 member_completions.push_back(item.to_json());
844 }
845
846 for (const KeyValue<String, ClassMembers> &E : inner_classes) {
847 const ClassMembers *inner_class = &E.value;
848
849 for (const KeyValue<String, const lsp::DocumentSymbol *> &F : *inner_class) {
850 const lsp::DocumentSymbol *symbol = F.value;
851 lsp::CompletionItem item = symbol->make_completion_item();
852 item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(E.key, F.key));
853 member_completions.push_back(item.to_json());
854 }
855 }
856 }
857
858 return member_completions;
859}
860
861Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
862 Dictionary func;
863 ERR_FAIL_NULL_V(p_func, func);
864 func["name"] = p_func->identifier->name;
865 func["return_type"] = p_func->get_datatype().to_string();
866 func["rpc_config"] = p_func->rpc_config;
867 Array parameters;
868 for (int i = 0; i < p_func->parameters.size(); i++) {
869 Dictionary arg;
870 arg["name"] = p_func->parameters[i]->identifier->name;
871 arg["type"] = p_func->parameters[i]->get_datatype().to_string();
872 if (p_func->parameters[i]->initializer != nullptr) {
873 arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
874 }
875 parameters.push_back(arg);
876 }
877 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
878 func["signature"] = symbol->detail;
879 func["description"] = symbol->documentation;
880 }
881 func["arguments"] = parameters;
882 return func;
883}
884
885Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
886 Dictionary class_api;
887
888 ERR_FAIL_NULL_V(p_class, class_api);
889
890 class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
891 class_api["path"] = path;
892 Array extends_class;
893 for (int i = 0; i < p_class->extends.size(); i++) {
894 extends_class.append(String(p_class->extends[i]->name));
895 }
896 class_api["extends_class"] = extends_class;
897 class_api["extends_file"] = String(p_class->extends_path);
898 class_api["icon"] = String(p_class->icon_path);
899
900 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
901 class_api["signature"] = symbol->detail;
902 class_api["description"] = symbol->documentation;
903 }
904
905 Array nested_classes;
906 Array constants;
907 Array class_members;
908 Array signals;
909 Array methods;
910 Array static_functions;
911
912 for (int i = 0; i < p_class->members.size(); i++) {
913 const ClassNode::Member &m = p_class->members[i];
914 switch (m.type) {
915 case ClassNode::Member::CLASS:
916 nested_classes.push_back(dump_class_api(m.m_class));
917 break;
918 case ClassNode::Member::CONSTANT: {
919 Dictionary api;
920 api["name"] = m.constant->identifier->name;
921 api["value"] = m.constant->initializer->reduced_value;
922 api["data_type"] = m.constant->get_datatype().to_string();
923 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
924 api["signature"] = symbol->detail;
925 api["description"] = symbol->documentation;
926 }
927 constants.push_back(api);
928 } break;
929 case ClassNode::Member::ENUM_VALUE: {
930 Dictionary api;
931 api["name"] = m.enum_value.identifier->name;
932 api["value"] = m.enum_value.value;
933 api["data_type"] = m.get_datatype().to_string();
934 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
935 api["signature"] = symbol->detail;
936 api["description"] = symbol->documentation;
937 }
938 constants.push_back(api);
939 } break;
940 case ClassNode::Member::ENUM: {
941 Dictionary enum_dict;
942 for (int j = 0; j < m.m_enum->values.size(); j++) {
943 enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
944 }
945
946 Dictionary api;
947 api["name"] = m.m_enum->identifier->name;
948 api["value"] = enum_dict;
949 api["data_type"] = m.get_datatype().to_string();
950 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
951 api["signature"] = symbol->detail;
952 api["description"] = symbol->documentation;
953 }
954 constants.push_back(api);
955 } break;
956 case ClassNode::Member::VARIABLE: {
957 Dictionary api;
958 api["name"] = m.variable->identifier->name;
959 api["data_type"] = m.variable->get_datatype().to_string();
960 api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
961 api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
962 api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());
963 api["export"] = m.variable->exported;
964 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
965 api["signature"] = symbol->detail;
966 api["description"] = symbol->documentation;
967 }
968 class_members.push_back(api);
969 } break;
970 case ClassNode::Member::SIGNAL: {
971 Dictionary api;
972 api["name"] = m.signal->identifier->name;
973 Array pars;
974 for (int j = 0; j < m.signal->parameters.size(); j++) {
975 pars.append(String(m.signal->parameters[j]->identifier->name));
976 }
977 api["arguments"] = pars;
978 if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
979 api["signature"] = symbol->detail;
980 api["description"] = symbol->documentation;
981 }
982 signals.push_back(api);
983 } break;
984 case ClassNode::Member::FUNCTION: {
985 if (m.function->is_static) {
986 static_functions.append(dump_function_api(m.function));
987 } else {
988 methods.append(dump_function_api(m.function));
989 }
990 } break;
991 case ClassNode::Member::GROUP:
992 break; // No-op, but silences warnings.
993 case ClassNode::Member::UNDEFINED:
994 break; // Unreachable.
995 }
996 }
997
998 class_api["sub_classes"] = nested_classes;
999 class_api["constants"] = constants;
1000 class_api["members"] = class_members;
1001 class_api["signals"] = signals;
1002 class_api["methods"] = methods;
1003 class_api["static_functions"] = static_functions;
1004
1005 return class_api;
1006}
1007
1008Dictionary ExtendGDScriptParser::generate_api() const {
1009 Dictionary api;
1010 if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
1011 api = dump_class_api(gdclass);
1012 }
1013 return api;
1014}
1015
1016Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
1017 path = p_path;
1018 lines = p_code.split("\n");
1019
1020 Error err = GDScriptParser::parse(p_code, p_path, false);
1021 GDScriptAnalyzer analyzer(this);
1022
1023 if (err == OK) {
1024 err = analyzer.analyze();
1025 }
1026 update_diagnostics();
1027 update_symbols();
1028 update_document_links(p_code);
1029 return err;
1030}
1031