Debian Codegraph @

modules/gdscript/language_server/gdscript_extend_parser.cpp

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