Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/language_server/gdscript_extend_parser.cpp
10278 views
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
if (HashMap<String, ExtendGDScriptParser *>::Iterator S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
348
symbol.documentation = S->value->class_symbol.documentation;
349
}
350
}
351
} else {
352
value_text = default_value.to_json_string();
353
}
354
} else {
355
value_text = default_value.to_json_string();
356
}
357
if (!value_text.is_empty()) {
358
symbol.detail += " = " + value_text;
359
}
360
361
r_symbol.children.push_back(symbol);
362
} break;
363
case ClassNode::Member::SIGNAL: {
364
LSP::DocumentSymbol symbol;
365
symbol.name = m.signal->identifier->name;
366
symbol.kind = LSP::SymbolKind::Event;
367
symbol.deprecated = false;
368
symbol.range = range_of_node(m.signal);
369
symbol.selectionRange = range_of_node(m.signal->identifier);
370
symbol.documentation = m.signal->doc_data.description;
371
symbol.uri = uri;
372
symbol.script_path = path;
373
symbol.detail = "signal " + String(m.signal->identifier->name) + "(";
374
for (int j = 0; j < m.signal->parameters.size(); j++) {
375
if (j > 0) {
376
symbol.detail += ", ";
377
}
378
symbol.detail += m.signal->parameters[j]->identifier->name;
379
}
380
symbol.detail += ")";
381
382
for (GDScriptParser::ParameterNode *param : m.signal->parameters) {
383
LSP::DocumentSymbol param_symbol;
384
param_symbol.name = param->identifier->name;
385
param_symbol.kind = LSP::SymbolKind::Variable;
386
param_symbol.deprecated = false;
387
param_symbol.local = true;
388
param_symbol.range = range_of_node(param);
389
param_symbol.selectionRange = range_of_node(param->identifier);
390
param_symbol.uri = uri;
391
param_symbol.script_path = path;
392
param_symbol.detail = "var " + param_symbol.name;
393
if (param->get_datatype().is_hard_type()) {
394
param_symbol.detail += ": " + param->get_datatype().to_string();
395
}
396
symbol.children.push_back(param_symbol);
397
}
398
r_symbol.children.push_back(symbol);
399
} break;
400
case ClassNode::Member::ENUM_VALUE: {
401
LSP::DocumentSymbol symbol;
402
403
symbol.name = m.enum_value.identifier->name;
404
symbol.kind = LSP::SymbolKind::EnumMember;
405
symbol.deprecated = false;
406
symbol.range.start = GodotPosition(m.enum_value.line, m.enum_value.start_column).to_lsp(lines);
407
symbol.range.end = GodotPosition(m.enum_value.line, m.enum_value.end_column).to_lsp(lines);
408
symbol.selectionRange = range_of_node(m.enum_value.identifier);
409
symbol.documentation = m.enum_value.doc_data.description;
410
symbol.uri = uri;
411
symbol.script_path = path;
412
413
symbol.detail = symbol.name + " = " + itos(m.enum_value.value);
414
415
r_symbol.children.push_back(symbol);
416
} break;
417
case ClassNode::Member::ENUM: {
418
LSP::DocumentSymbol symbol;
419
symbol.name = m.m_enum->identifier->name;
420
symbol.kind = LSP::SymbolKind::Enum;
421
symbol.range = range_of_node(m.m_enum);
422
symbol.selectionRange = range_of_node(m.m_enum->identifier);
423
symbol.documentation = m.m_enum->doc_data.description;
424
symbol.uri = uri;
425
symbol.script_path = path;
426
427
symbol.detail = "enum " + String(m.m_enum->identifier->name) + "{";
428
for (int j = 0; j < m.m_enum->values.size(); j++) {
429
if (j > 0) {
430
symbol.detail += ", ";
431
}
432
symbol.detail += String(m.m_enum->values[j].identifier->name) + " = " + itos(m.m_enum->values[j].value);
433
}
434
symbol.detail += "}";
435
436
for (GDScriptParser::EnumNode::Value value : m.m_enum->values) {
437
LSP::DocumentSymbol child;
438
439
child.name = value.identifier->name;
440
child.kind = LSP::SymbolKind::EnumMember;
441
child.deprecated = false;
442
child.range.start = GodotPosition(value.line, value.start_column).to_lsp(lines);
443
child.range.end = GodotPosition(value.line, value.end_column).to_lsp(lines);
444
child.selectionRange = range_of_node(value.identifier);
445
child.documentation = value.doc_data.description;
446
child.uri = uri;
447
child.script_path = path;
448
449
child.detail = child.name + " = " + itos(value.value);
450
451
symbol.children.push_back(child);
452
}
453
454
r_symbol.children.push_back(symbol);
455
} break;
456
case ClassNode::Member::FUNCTION: {
457
LSP::DocumentSymbol symbol;
458
parse_function_symbol(m.function, symbol);
459
r_symbol.children.push_back(symbol);
460
} break;
461
case ClassNode::Member::CLASS: {
462
LSP::DocumentSymbol symbol;
463
parse_class_symbol(m.m_class, symbol);
464
r_symbol.children.push_back(symbol);
465
} break;
466
case ClassNode::Member::GROUP:
467
break; // No-op, but silences warnings.
468
case ClassNode::Member::UNDEFINED:
469
break; // Unreachable.
470
}
471
}
472
}
473
474
void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, LSP::DocumentSymbol &r_symbol) {
475
const String uri = get_uri();
476
477
bool is_named = p_func->identifier != nullptr;
478
479
r_symbol.name = is_named ? p_func->identifier->name : "";
480
r_symbol.kind = (p_func->is_static || p_func->source_lambda != nullptr) ? LSP::SymbolKind::Function : LSP::SymbolKind::Method;
481
r_symbol.detail = "func";
482
if (is_named) {
483
r_symbol.detail += " " + String(p_func->identifier->name);
484
}
485
r_symbol.detail += "(";
486
r_symbol.deprecated = false;
487
r_symbol.range = range_of_node(p_func);
488
if (is_named) {
489
r_symbol.selectionRange = range_of_node(p_func->identifier);
490
} else {
491
r_symbol.selectionRange.start = r_symbol.selectionRange.end = r_symbol.range.start;
492
}
493
r_symbol.documentation = p_func->doc_data.description;
494
r_symbol.uri = uri;
495
r_symbol.script_path = path;
496
497
String parameters;
498
for (int i = 0; i < p_func->parameters.size(); i++) {
499
const ParameterNode *parameter = p_func->parameters[i];
500
if (i > 0) {
501
parameters += ", ";
502
}
503
parameters += String(parameter->identifier->name);
504
if (parameter->get_datatype().is_hard_type()) {
505
parameters += ": " + parameter->get_datatype().to_string();
506
}
507
if (parameter->initializer != nullptr) {
508
parameters += " = " + parameter->initializer->reduced_value.to_json_string();
509
}
510
}
511
if (p_func->is_vararg()) {
512
if (!p_func->parameters.is_empty()) {
513
parameters += ", ";
514
}
515
const ParameterNode *rest_param = p_func->rest_parameter;
516
parameters += "..." + rest_param->identifier->name + ": " + rest_param->get_datatype().to_string();
517
}
518
r_symbol.detail += parameters + ")";
519
520
const DataType return_type = p_func->get_datatype();
521
if (return_type.is_hard_type()) {
522
if (return_type.kind == DataType::BUILTIN && return_type.builtin_type == Variant::NIL) {
523
r_symbol.detail += " -> void";
524
} else {
525
r_symbol.detail += " -> " + return_type.to_string();
526
}
527
}
528
529
List<GDScriptParser::SuiteNode *> function_nodes;
530
531
List<GDScriptParser::Node *> node_stack;
532
node_stack.push_back(p_func->body);
533
534
while (!node_stack.is_empty()) {
535
GDScriptParser::Node *node = node_stack.front()->get();
536
node_stack.pop_front();
537
538
switch (node->type) {
539
case GDScriptParser::TypeNode::IF: {
540
GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node;
541
node_stack.push_back(if_node->true_block);
542
if (if_node->false_block) {
543
node_stack.push_back(if_node->false_block);
544
}
545
} break;
546
547
case GDScriptParser::TypeNode::FOR: {
548
GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node;
549
node_stack.push_back(for_node->loop);
550
} break;
551
552
case GDScriptParser::TypeNode::WHILE: {
553
GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node;
554
node_stack.push_back(while_node->loop);
555
} break;
556
557
case GDScriptParser::TypeNode::MATCH: {
558
GDScriptParser::MatchNode *match_node = (GDScriptParser::MatchNode *)node;
559
for (GDScriptParser::MatchBranchNode *branch_node : match_node->branches) {
560
node_stack.push_back(branch_node);
561
}
562
} break;
563
564
case GDScriptParser::TypeNode::MATCH_BRANCH: {
565
GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node;
566
node_stack.push_back(match_node->block);
567
} break;
568
569
case GDScriptParser::TypeNode::SUITE: {
570
GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node;
571
function_nodes.push_back(suite_node);
572
for (int i = 0; i < suite_node->statements.size(); ++i) {
573
node_stack.push_back(suite_node->statements[i]);
574
}
575
} break;
576
577
default:
578
continue;
579
}
580
}
581
582
for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) {
583
const GDScriptParser::SuiteNode *suite_node = N->get();
584
for (int i = 0; i < suite_node->locals.size(); i++) {
585
const SuiteNode::Local &local = suite_node->locals[i];
586
LSP::DocumentSymbol symbol;
587
symbol.name = local.name;
588
symbol.kind = local.type == SuiteNode::Local::CONSTANT ? LSP::SymbolKind::Constant : LSP::SymbolKind::Variable;
589
switch (local.type) {
590
case SuiteNode::Local::CONSTANT:
591
symbol.range = range_of_node(local.constant);
592
symbol.selectionRange = range_of_node(local.constant->identifier);
593
break;
594
case SuiteNode::Local::VARIABLE:
595
symbol.range = range_of_node(local.variable);
596
symbol.selectionRange = range_of_node(local.variable->identifier);
597
if (local.variable->initializer && local.variable->initializer->type == GDScriptParser::Node::LAMBDA) {
598
GDScriptParser::LambdaNode *lambda_node = (GDScriptParser::LambdaNode *)local.variable->initializer;
599
LSP::DocumentSymbol lambda;
600
parse_function_symbol(lambda_node->function, lambda);
601
// Merge lambda into current variable.
602
// -> Only interested in new variables, not lambda itself.
603
symbol.children.append_array(lambda.children);
604
}
605
break;
606
case SuiteNode::Local::PARAMETER:
607
symbol.range = range_of_node(local.parameter);
608
symbol.selectionRange = range_of_node(local.parameter->identifier);
609
break;
610
case SuiteNode::Local::FOR_VARIABLE:
611
case SuiteNode::Local::PATTERN_BIND:
612
symbol.range = range_of_node(local.bind);
613
symbol.selectionRange = range_of_node(local.bind);
614
break;
615
default:
616
// Fallback.
617
symbol.range.start = GodotPosition(local.start_line, local.start_column).to_lsp(get_lines());
618
symbol.range.end = GodotPosition(local.end_line, local.end_column).to_lsp(get_lines());
619
symbol.selectionRange = symbol.range;
620
break;
621
}
622
symbol.local = true;
623
symbol.uri = uri;
624
symbol.script_path = path;
625
symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var ";
626
symbol.detail += symbol.name;
627
if (local.get_datatype().is_hard_type()) {
628
symbol.detail += ": " + local.get_datatype().to_string();
629
}
630
switch (local.type) {
631
case SuiteNode::Local::CONSTANT:
632
symbol.documentation = local.constant->doc_data.description;
633
break;
634
case SuiteNode::Local::VARIABLE:
635
symbol.documentation = local.variable->doc_data.description;
636
break;
637
default:
638
break;
639
}
640
r_symbol.children.push_back(symbol);
641
}
642
}
643
}
644
645
String ExtendGDScriptParser::get_text_for_completion(const LSP::Position &p_cursor) const {
646
String longthing;
647
int len = lines.size();
648
for (int i = 0; i < len; i++) {
649
if (i == p_cursor.line) {
650
longthing += lines[i].substr(0, p_cursor.character);
651
longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
652
longthing += lines[i].substr(p_cursor.character);
653
} else {
654
longthing += lines[i];
655
}
656
657
if (i != len - 1) {
658
longthing += "\n";
659
}
660
}
661
662
return longthing;
663
}
664
665
String ExtendGDScriptParser::get_text_for_lookup_symbol(const LSP::Position &p_cursor, const String &p_symbol, bool p_func_required) const {
666
String longthing;
667
int len = lines.size();
668
for (int i = 0; i < len; i++) {
669
if (i == p_cursor.line) {
670
String line = lines[i];
671
String first_part = line.substr(0, p_cursor.character);
672
String last_part = line.substr(p_cursor.character, lines[i].length());
673
if (!p_symbol.is_empty()) {
674
String left_cursor_text;
675
for (int c = p_cursor.character - 1; c >= 0; c--) {
676
left_cursor_text = line.substr(c, p_cursor.character - c);
677
if (p_symbol.begins_with(left_cursor_text)) {
678
first_part = line.substr(0, c);
679
first_part += p_symbol;
680
break;
681
}
682
}
683
}
684
685
longthing += first_part;
686
longthing += String::chr(0xFFFF); // Not unicode, represents the cursor.
687
if (p_func_required) {
688
longthing += "("; // Tell the parser this is a function call.
689
}
690
longthing += last_part;
691
} else {
692
longthing += lines[i];
693
}
694
695
if (i != len - 1) {
696
longthing += "\n";
697
}
698
}
699
700
return longthing;
701
}
702
703
String ExtendGDScriptParser::get_identifier_under_position(const LSP::Position &p_position, LSP::Range &r_range) const {
704
ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
705
String line = lines[p_position.line];
706
if (line.is_empty()) {
707
return "";
708
}
709
ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
710
711
// `p_position` cursor is BETWEEN chars, not ON chars.
712
// ->
713
// ```gdscript
714
// var member| := some_func|(some_variable|)
715
// ^ ^ ^
716
// | | | cursor on `some_variable, position on `)`
717
// | |
718
// | | cursor on `some_func`, pos on `(`
719
// |
720
// | cursor on `member`, pos on ` ` (space)
721
// ```
722
// -> Move position to previous character if:
723
// * Position not on valid identifier char.
724
// * Prev position is valid identifier char.
725
LSP::Position pos = p_position;
726
if (
727
pos.character >= line.length() // Cursor at end of line.
728
|| (!is_unicode_identifier_continue(line[pos.character]) // Not on valid identifier char.
729
&& (pos.character > 0 // Not line start -> there is a prev char.
730
&& is_unicode_identifier_continue(line[pos.character - 1]) // Prev is valid identifier char.
731
))) {
732
pos.character--;
733
}
734
735
int start_pos = pos.character;
736
for (int c = pos.character; c >= 0; c--) {
737
start_pos = c;
738
char32_t ch = line[c];
739
bool valid_char = is_unicode_identifier_continue(ch);
740
if (!valid_char) {
741
break;
742
}
743
}
744
745
int end_pos = pos.character;
746
for (int c = pos.character; c < line.length(); c++) {
747
char32_t ch = line[c];
748
bool valid_char = is_unicode_identifier_continue(ch);
749
if (!valid_char) {
750
break;
751
}
752
end_pos = c;
753
}
754
755
if (!is_unicode_identifier_start(line[start_pos + 1])) {
756
return "";
757
}
758
759
if (start_pos < end_pos) {
760
r_range.start.line = r_range.end.line = pos.line;
761
r_range.start.character = start_pos + 1;
762
r_range.end.character = end_pos + 1;
763
return line.substr(start_pos + 1, end_pos - start_pos);
764
}
765
766
return "";
767
}
768
769
String ExtendGDScriptParser::get_uri() const {
770
return GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
771
}
772
773
const LSP::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(int p_line, const LSP::DocumentSymbol &p_parent, const String &p_symbol_name) const {
774
const LSP::DocumentSymbol *ret = nullptr;
775
if (p_line < p_parent.range.start.line) {
776
return ret;
777
} else if (p_parent.range.start.line == p_line && (p_symbol_name.is_empty() || p_parent.name == p_symbol_name)) {
778
return &p_parent;
779
} else {
780
for (int i = 0; i < p_parent.children.size(); i++) {
781
ret = search_symbol_defined_at_line(p_line, p_parent.children[i], p_symbol_name);
782
if (ret) {
783
break;
784
}
785
}
786
}
787
return ret;
788
}
789
790
Error ExtendGDScriptParser::get_left_function_call(const LSP::Position &p_position, LSP::Position &r_func_pos, int &r_arg_index) const {
791
ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
792
793
int bracket_stack = 0;
794
int index = 0;
795
796
bool found = false;
797
for (int l = p_position.line; l >= 0; --l) {
798
String line = lines[l];
799
int c = line.length() - 1;
800
if (l == p_position.line) {
801
c = MIN(c, p_position.character - 1);
802
}
803
804
while (c >= 0) {
805
const char32_t &character = line[c];
806
if (character == ')') {
807
++bracket_stack;
808
} else if (character == '(') {
809
--bracket_stack;
810
if (bracket_stack < 0) {
811
found = true;
812
}
813
}
814
if (bracket_stack <= 0 && character == ',') {
815
++index;
816
}
817
--c;
818
if (found) {
819
r_func_pos.character = c;
820
break;
821
}
822
}
823
824
if (found) {
825
r_func_pos.line = l;
826
r_arg_index = index;
827
return OK;
828
}
829
}
830
831
return ERR_METHOD_NOT_FOUND;
832
}
833
834
const LSP::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int p_line, const String &p_symbol_name) const {
835
if (p_line <= 0) {
836
return &class_symbol;
837
}
838
return search_symbol_defined_at_line(p_line, class_symbol, p_symbol_name);
839
}
840
841
const LSP::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
842
if (p_subclass.is_empty()) {
843
const LSP::DocumentSymbol *const *ptr = members.getptr(p_name);
844
if (ptr) {
845
return *ptr;
846
}
847
} else {
848
if (const ClassMembers *_class = inner_classes.getptr(p_subclass)) {
849
const LSP::DocumentSymbol *const *ptr = _class->getptr(p_name);
850
if (ptr) {
851
return *ptr;
852
}
853
}
854
}
855
856
return nullptr;
857
}
858
859
const List<LSP::DocumentLink> &ExtendGDScriptParser::get_document_links() const {
860
return document_links;
861
}
862
863
const Array &ExtendGDScriptParser::get_member_completions() {
864
if (member_completions.is_empty()) {
865
for (const KeyValue<String, const LSP::DocumentSymbol *> &E : members) {
866
const LSP::DocumentSymbol *symbol = E.value;
867
LSP::CompletionItem item = symbol->make_completion_item();
868
item.data = JOIN_SYMBOLS(path, E.key);
869
member_completions.push_back(item.to_json());
870
}
871
872
for (const KeyValue<String, ClassMembers> &E : inner_classes) {
873
const ClassMembers *inner_class = &E.value;
874
875
for (const KeyValue<String, const LSP::DocumentSymbol *> &F : *inner_class) {
876
const LSP::DocumentSymbol *symbol = F.value;
877
LSP::CompletionItem item = symbol->make_completion_item();
878
item.data = JOIN_SYMBOLS(path, JOIN_SYMBOLS(E.key, F.key));
879
member_completions.push_back(item.to_json());
880
}
881
}
882
}
883
884
return member_completions;
885
}
886
887
Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
888
Dictionary func;
889
ERR_FAIL_NULL_V(p_func, func);
890
func["name"] = p_func->identifier->name;
891
func["return_type"] = p_func->get_datatype().to_string();
892
func["rpc_config"] = p_func->rpc_config;
893
Array parameters;
894
for (int i = 0; i < p_func->parameters.size(); i++) {
895
Dictionary arg;
896
arg["name"] = p_func->parameters[i]->identifier->name;
897
arg["type"] = p_func->parameters[i]->get_datatype().to_string();
898
if (p_func->parameters[i]->initializer != nullptr) {
899
arg["default_value"] = p_func->parameters[i]->initializer->reduced_value;
900
}
901
parameters.push_back(arg);
902
}
903
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
904
func["signature"] = symbol->detail;
905
func["description"] = symbol->documentation;
906
}
907
func["arguments"] = parameters;
908
return func;
909
}
910
911
Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode *p_class) const {
912
Dictionary class_api;
913
914
ERR_FAIL_NULL_V(p_class, class_api);
915
916
class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
917
class_api["path"] = path;
918
Array extends_class;
919
for (int i = 0; i < p_class->extends.size(); i++) {
920
extends_class.append(String(p_class->extends[i]->name));
921
}
922
class_api["extends_class"] = extends_class;
923
class_api["extends_file"] = String(p_class->extends_path);
924
class_api["icon"] = String(p_class->icon_path);
925
926
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
927
class_api["signature"] = symbol->detail;
928
class_api["description"] = symbol->documentation;
929
}
930
931
Array nested_classes;
932
Array constants;
933
Array class_members;
934
Array signals;
935
Array methods;
936
Array static_functions;
937
938
for (int i = 0; i < p_class->members.size(); i++) {
939
const ClassNode::Member &m = p_class->members[i];
940
switch (m.type) {
941
case ClassNode::Member::CLASS:
942
nested_classes.push_back(dump_class_api(m.m_class));
943
break;
944
case ClassNode::Member::CONSTANT: {
945
Dictionary api;
946
api["name"] = m.constant->identifier->name;
947
api["value"] = m.constant->initializer->reduced_value;
948
api["data_type"] = m.constant->get_datatype().to_string();
949
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
950
api["signature"] = symbol->detail;
951
api["description"] = symbol->documentation;
952
}
953
constants.push_back(api);
954
} break;
955
case ClassNode::Member::ENUM_VALUE: {
956
Dictionary api;
957
api["name"] = m.enum_value.identifier->name;
958
api["value"] = m.enum_value.value;
959
api["data_type"] = m.get_datatype().to_string();
960
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
961
api["signature"] = symbol->detail;
962
api["description"] = symbol->documentation;
963
}
964
constants.push_back(api);
965
} break;
966
case ClassNode::Member::ENUM: {
967
Dictionary enum_dict;
968
for (int j = 0; j < m.m_enum->values.size(); j++) {
969
enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
970
}
971
972
Dictionary api;
973
api["name"] = m.m_enum->identifier->name;
974
api["value"] = enum_dict;
975
api["data_type"] = m.get_datatype().to_string();
976
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
977
api["signature"] = symbol->detail;
978
api["description"] = symbol->documentation;
979
}
980
constants.push_back(api);
981
} break;
982
case ClassNode::Member::VARIABLE: {
983
Dictionary api;
984
api["name"] = m.variable->identifier->name;
985
api["data_type"] = m.variable->get_datatype().to_string();
986
api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
987
api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
988
api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());
989
api["export"] = m.variable->exported;
990
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
991
api["signature"] = symbol->detail;
992
api["description"] = symbol->documentation;
993
}
994
class_members.push_back(api);
995
} break;
996
case ClassNode::Member::SIGNAL: {
997
Dictionary api;
998
api["name"] = m.signal->identifier->name;
999
Array pars;
1000
for (int j = 0; j < m.signal->parameters.size(); j++) {
1001
pars.append(String(m.signal->parameters[j]->identifier->name));
1002
}
1003
api["arguments"] = pars;
1004
if (const LSP::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
1005
api["signature"] = symbol->detail;
1006
api["description"] = symbol->documentation;
1007
}
1008
signals.push_back(api);
1009
} break;
1010
case ClassNode::Member::FUNCTION: {
1011
if (m.function->is_static) {
1012
static_functions.append(dump_function_api(m.function));
1013
} else {
1014
methods.append(dump_function_api(m.function));
1015
}
1016
} break;
1017
case ClassNode::Member::GROUP:
1018
break; // No-op, but silences warnings.
1019
case ClassNode::Member::UNDEFINED:
1020
break; // Unreachable.
1021
}
1022
}
1023
1024
class_api["sub_classes"] = nested_classes;
1025
class_api["constants"] = constants;
1026
class_api["members"] = class_members;
1027
class_api["signals"] = signals;
1028
class_api["methods"] = methods;
1029
class_api["static_functions"] = static_functions;
1030
1031
return class_api;
1032
}
1033
1034
Dictionary ExtendGDScriptParser::generate_api() const {
1035
Dictionary api;
1036
if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(get_tree())) {
1037
api = dump_class_api(gdclass);
1038
}
1039
return api;
1040
}
1041
1042
Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
1043
path = p_path;
1044
lines = p_code.split("\n");
1045
1046
Error err = GDScriptParser::parse(p_code, p_path, false);
1047
GDScriptAnalyzer analyzer(this);
1048
1049
if (err == OK) {
1050
err = analyzer.analyze();
1051
}
1052
update_diagnostics();
1053
update_symbols();
1054
update_document_links(p_code);
1055
return err;
1056
}
1057
1058