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