Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/gdscript_parser.cpp
10277 views
1
/**************************************************************************/
2
/* gdscript_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_parser.h"
32
33
#include "gdscript.h"
34
#include "gdscript_tokenizer_buffer.h"
35
36
#include "core/config/project_settings.h"
37
#include "core/io/resource_loader.h"
38
#include "core/math/math_defs.h"
39
#include "scene/main/multiplayer_api.h"
40
41
#ifdef DEBUG_ENABLED
42
#include "core/string/string_builder.h"
43
#include "servers/text_server.h"
44
#endif
45
46
#ifdef TOOLS_ENABLED
47
#include "editor/settings/editor_settings.h"
48
#endif
49
50
// This function is used to determine that a type is "built-in" as opposed to native
51
// and custom classes. So `Variant::NIL` and `Variant::OBJECT` are excluded:
52
// `Variant::NIL` - `null` is literal, not a type.
53
// `Variant::OBJECT` - `Object` should be treated as a class, not as a built-in type.
54
static HashMap<StringName, Variant::Type> builtin_types;
55
Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
56
if (unlikely(builtin_types.is_empty())) {
57
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
58
Variant::Type type = (Variant::Type)i;
59
if (type != Variant::NIL && type != Variant::OBJECT) {
60
builtin_types[Variant::get_type_name(type)] = type;
61
}
62
}
63
}
64
65
if (builtin_types.has(p_type)) {
66
return builtin_types[p_type];
67
}
68
return Variant::VARIANT_MAX;
69
}
70
71
#ifdef TOOLS_ENABLED
72
HashMap<String, String> GDScriptParser::theme_color_names;
73
#endif
74
75
HashMap<StringName, GDScriptParser::AnnotationInfo> GDScriptParser::valid_annotations;
76
77
void GDScriptParser::cleanup() {
78
builtin_types.clear();
79
valid_annotations.clear();
80
}
81
82
void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
83
for (const KeyValue<StringName, AnnotationInfo> &E : valid_annotations) {
84
r_annotations->push_back(E.value.info);
85
}
86
}
87
88
bool GDScriptParser::annotation_exists(const String &p_annotation_name) const {
89
return valid_annotations.has(p_annotation_name);
90
}
91
92
GDScriptParser::GDScriptParser() {
93
// Register valid annotations.
94
if (unlikely(valid_annotations.is_empty())) {
95
// Script annotations.
96
register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
97
register_annotation(MethodInfo("@icon", PropertyInfo(Variant::STRING, "icon_path")), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
98
register_annotation(MethodInfo("@static_unload"), AnnotationInfo::SCRIPT, &GDScriptParser::static_unload_annotation);
99
register_annotation(MethodInfo("@abstract"), AnnotationInfo::SCRIPT | AnnotationInfo::CLASS | AnnotationInfo::FUNCTION, &GDScriptParser::abstract_annotation);
100
// Onready annotation.
101
register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
102
// Export annotations.
103
register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NONE, Variant::NIL>);
104
register_annotation(MethodInfo("@export_enum", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::NIL>, varray(), true);
105
register_annotation(MethodInfo("@export_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, varray(""), true);
106
register_annotation(MethodInfo("@export_file_path", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE_PATH, Variant::STRING>, varray(""), true);
107
register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
108
register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
109
register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
110
register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
111
register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
112
register_annotation(MethodInfo("@export_range", PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"), PropertyInfo(Variant::FLOAT, "step"), PropertyInfo(Variant::STRING, "extra_hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, varray(1.0, ""), true);
113
register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
114
register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
115
register_annotation(MethodInfo("@export_node_path", PropertyInfo(Variant::STRING, "type")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, varray(""), true);
116
register_annotation(MethodInfo("@export_flags", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, varray(), true);
117
register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
118
register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
119
register_annotation(MethodInfo("@export_flags_2d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_NAVIGATION, Variant::INT>);
120
register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
121
register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
122
register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>);
123
register_annotation(MethodInfo("@export_flags_avoidance"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_AVOIDANCE, Variant::INT>);
124
register_annotation(MethodInfo("@export_storage"), AnnotationInfo::VARIABLE, &GDScriptParser::export_storage_annotation);
125
register_annotation(MethodInfo("@export_custom", PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_ENUM, "PropertyHint"), PropertyInfo(Variant::STRING, "hint_string"), PropertyInfo(Variant::INT, "usage", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CLASS_IS_BITFIELD, "PropertyUsageFlags")), AnnotationInfo::VARIABLE, &GDScriptParser::export_custom_annotation, varray(PROPERTY_USAGE_DEFAULT));
126
register_annotation(MethodInfo("@export_tool_button", PropertyInfo(Variant::STRING, "text"), PropertyInfo(Variant::STRING, "icon")), AnnotationInfo::VARIABLE, &GDScriptParser::export_tool_button_annotation, varray(""));
127
// Export grouping annotations.
128
register_annotation(MethodInfo("@export_category", PropertyInfo(Variant::STRING, "name")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_CATEGORY>);
129
register_annotation(MethodInfo("@export_group", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_GROUP>, varray(""));
130
register_annotation(MethodInfo("@export_subgroup", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_SUBGROUP>, varray(""));
131
// Warning annotations.
132
register_annotation(MethodInfo("@warning_ignore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STATEMENT, &GDScriptParser::warning_ignore_annotation, varray(), true);
133
register_annotation(MethodInfo("@warning_ignore_start", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
134
register_annotation(MethodInfo("@warning_ignore_restore", PropertyInfo(Variant::STRING, "warning")), AnnotationInfo::STANDALONE, &GDScriptParser::warning_ignore_region_annotations, varray(), true);
135
// Networking.
136
register_annotation(MethodInfo("@rpc", PropertyInfo(Variant::STRING, "mode"), PropertyInfo(Variant::STRING, "sync"), PropertyInfo(Variant::STRING, "transfer_mode"), PropertyInfo(Variant::INT, "transfer_channel")), AnnotationInfo::FUNCTION, &GDScriptParser::rpc_annotation, varray("authority", "call_remote", "unreliable", 0));
137
}
138
139
#ifdef DEBUG_ENABLED
140
is_ignoring_warnings = !(bool)GLOBAL_GET("debug/gdscript/warnings/enable");
141
for (int i = 0; i < GDScriptWarning::WARNING_MAX; i++) {
142
warning_ignore_start_lines[i] = INT_MAX;
143
}
144
#endif
145
146
#ifdef TOOLS_ENABLED
147
if (unlikely(theme_color_names.is_empty())) {
148
// Vectors.
149
theme_color_names.insert("x", "axis_x_color");
150
theme_color_names.insert("y", "axis_y_color");
151
theme_color_names.insert("z", "axis_z_color");
152
theme_color_names.insert("w", "axis_w_color");
153
154
// Color.
155
theme_color_names.insert("r", "axis_x_color");
156
theme_color_names.insert("r8", "axis_x_color");
157
theme_color_names.insert("g", "axis_y_color");
158
theme_color_names.insert("g8", "axis_y_color");
159
theme_color_names.insert("b", "axis_z_color");
160
theme_color_names.insert("b8", "axis_z_color");
161
theme_color_names.insert("a", "axis_w_color");
162
theme_color_names.insert("a8", "axis_w_color");
163
}
164
#endif
165
}
166
167
GDScriptParser::~GDScriptParser() {
168
while (list != nullptr) {
169
Node *element = list;
170
list = list->next;
171
memdelete(element);
172
}
173
}
174
175
void GDScriptParser::clear() {
176
GDScriptParser tmp;
177
tmp = *this;
178
*this = GDScriptParser();
179
}
180
181
void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
182
// TODO: Improve error reporting by pointing at source code.
183
// TODO: Errors might point at more than one place at once (e.g. show previous declaration).
184
panic_mode = true;
185
// TODO: Improve positional information.
186
if (p_origin == nullptr) {
187
errors.push_back({ p_message, previous.start_line, previous.start_column });
188
} else {
189
errors.push_back({ p_message, p_origin->start_line, p_origin->start_column });
190
}
191
}
192
193
#ifdef DEBUG_ENABLED
194
void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
195
ERR_FAIL_NULL(p_source);
196
ERR_FAIL_INDEX(p_code, GDScriptWarning::WARNING_MAX);
197
198
if (is_ignoring_warnings) {
199
return;
200
}
201
if (GLOBAL_GET_CACHED(bool, "debug/gdscript/warnings/exclude_addons") && script_path.begins_with("res://addons/")) {
202
return;
203
}
204
GDScriptWarning::WarnLevel warn_level = (GDScriptWarning::WarnLevel)(int)GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(p_code));
205
if (warn_level == GDScriptWarning::IGNORE) {
206
return;
207
}
208
209
PendingWarning pw;
210
pw.source = p_source;
211
pw.code = p_code;
212
pw.treated_as_error = warn_level == GDScriptWarning::ERROR;
213
pw.symbols = p_symbols;
214
215
pending_warnings.push_back(pw);
216
}
217
218
void GDScriptParser::apply_pending_warnings() {
219
for (const PendingWarning &pw : pending_warnings) {
220
if (warning_ignored_lines[pw.code].has(pw.source->start_line)) {
221
continue;
222
}
223
if (warning_ignore_start_lines[pw.code] <= pw.source->start_line) {
224
continue;
225
}
226
227
GDScriptWarning warning;
228
warning.code = pw.code;
229
warning.symbols = pw.symbols;
230
warning.start_line = pw.source->start_line;
231
warning.end_line = pw.source->end_line;
232
233
if (pw.treated_as_error) {
234
push_error(warning.get_message() + String(" (Warning treated as error.)"), pw.source);
235
continue;
236
}
237
238
List<GDScriptWarning>::Element *before = nullptr;
239
for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
240
if (E->get().start_line > warning.start_line) {
241
break;
242
}
243
before = E;
244
}
245
if (before) {
246
warnings.insert_after(before, warning);
247
} else {
248
warnings.push_front(warning);
249
}
250
}
251
252
pending_warnings.clear();
253
}
254
#endif // DEBUG_ENABLED
255
256
void GDScriptParser::override_completion_context(const Node *p_for_node, CompletionType p_type, Node *p_node, int p_argument) {
257
if (!for_completion) {
258
return;
259
}
260
if (p_for_node == nullptr || completion_context.node != p_for_node) {
261
return;
262
}
263
CompletionContext context;
264
context.type = p_type;
265
context.current_class = current_class;
266
context.current_function = current_function;
267
context.current_suite = current_suite;
268
context.current_line = tokenizer->get_cursor_line();
269
context.current_argument = p_argument;
270
context.node = p_node;
271
context.parser = this;
272
if (!completion_call_stack.is_empty()) {
273
context.call = completion_call_stack.back()->get();
274
}
275
completion_context = context;
276
}
277
278
void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument, bool p_force) {
279
if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
280
return;
281
}
282
if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
283
return;
284
}
285
CompletionContext context;
286
context.type = p_type;
287
context.current_class = current_class;
288
context.current_function = current_function;
289
context.current_suite = current_suite;
290
context.current_line = tokenizer->get_cursor_line();
291
context.current_argument = p_argument;
292
context.node = p_node;
293
context.parser = this;
294
if (!completion_call_stack.is_empty()) {
295
context.call = completion_call_stack.back()->get();
296
}
297
completion_context = context;
298
}
299
300
void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force) {
301
if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
302
return;
303
}
304
if (previous.cursor_place != GDScriptTokenizerText::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizerText::CURSOR_END && current.cursor_place == GDScriptTokenizerText::CURSOR_NONE) {
305
return;
306
}
307
CompletionContext context;
308
context.type = p_type;
309
context.current_class = current_class;
310
context.current_function = current_function;
311
context.current_suite = current_suite;
312
context.current_line = tokenizer->get_cursor_line();
313
context.builtin_type = p_builtin_type;
314
context.parser = this;
315
if (!completion_call_stack.is_empty()) {
316
context.call = completion_call_stack.back()->get();
317
}
318
completion_context = context;
319
}
320
321
void GDScriptParser::push_completion_call(Node *p_call) {
322
if (!for_completion) {
323
return;
324
}
325
CompletionCall call;
326
call.call = p_call;
327
call.argument = 0;
328
completion_call_stack.push_back(call);
329
}
330
331
void GDScriptParser::pop_completion_call() {
332
if (!for_completion) {
333
return;
334
}
335
ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
336
completion_call_stack.pop_back();
337
}
338
339
void GDScriptParser::set_last_completion_call_arg(int p_argument) {
340
if (!for_completion) {
341
return;
342
}
343
ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
344
completion_call_stack.back()->get().argument = p_argument;
345
}
346
347
Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion, bool p_parse_body) {
348
clear();
349
350
String source = p_source_code;
351
int cursor_line = -1;
352
int cursor_column = -1;
353
for_completion = p_for_completion;
354
parse_body = p_parse_body;
355
356
int tab_size = 4;
357
#ifdef TOOLS_ENABLED
358
if (EditorSettings::get_singleton()) {
359
tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
360
}
361
#endif // TOOLS_ENABLED
362
363
if (p_for_completion) {
364
// Remove cursor sentinel char.
365
const Vector<String> lines = p_source_code.split("\n");
366
cursor_line = 1;
367
cursor_column = 1;
368
for (int i = 0; i < lines.size(); i++) {
369
bool found = false;
370
const String &line = lines[i];
371
for (int j = 0; j < line.size(); j++) {
372
if (line[j] == char32_t(0xFFFF)) {
373
found = true;
374
break;
375
} else if (line[j] == '\t') {
376
cursor_column += tab_size - 1;
377
}
378
cursor_column++;
379
}
380
if (found) {
381
break;
382
}
383
cursor_line++;
384
cursor_column = 1;
385
}
386
387
source = source.replace_first(String::chr(0xFFFF), String());
388
}
389
390
GDScriptTokenizerText *text_tokenizer = memnew(GDScriptTokenizerText);
391
text_tokenizer->set_source_code(source);
392
393
tokenizer = text_tokenizer;
394
395
tokenizer->set_cursor_position(cursor_line, cursor_column);
396
script_path = p_script_path.simplify_path();
397
current = tokenizer->scan();
398
// Avoid error or newline as the first token.
399
// The latter can mess with the parser when opening files filled exclusively with comments and newlines.
400
while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
401
if (current.type == GDScriptTokenizer::Token::ERROR) {
402
push_error(current.literal);
403
}
404
current = tokenizer->scan();
405
}
406
407
#ifdef DEBUG_ENABLED
408
// Warn about parsing an empty script file:
409
if (current.type == GDScriptTokenizer::Token::TK_EOF) {
410
// Create a dummy Node for the warning, pointing to the very beginning of the file
411
Node *nd = alloc_node<PassNode>();
412
nd->start_line = 1;
413
nd->start_column = 0;
414
nd->end_line = 1;
415
push_warning(nd, GDScriptWarning::EMPTY_FILE);
416
}
417
#endif
418
419
push_multiline(false); // Keep one for the whole parsing.
420
parse_program();
421
pop_multiline();
422
423
#ifdef TOOLS_ENABLED
424
comment_data = tokenizer->get_comments();
425
#endif
426
427
memdelete(text_tokenizer);
428
tokenizer = nullptr;
429
430
#ifdef DEBUG_ENABLED
431
if (multiline_stack.size() > 0) {
432
ERR_PRINT("Parser bug: Imbalanced multiline stack.");
433
}
434
#endif
435
436
if (errors.is_empty()) {
437
return OK;
438
} else {
439
return ERR_PARSE_ERROR;
440
}
441
}
442
443
Error GDScriptParser::parse_binary(const Vector<uint8_t> &p_binary, const String &p_script_path) {
444
GDScriptTokenizerBuffer *buffer_tokenizer = memnew(GDScriptTokenizerBuffer);
445
Error err = buffer_tokenizer->set_code_buffer(p_binary);
446
447
if (err) {
448
memdelete(buffer_tokenizer);
449
return err;
450
}
451
452
tokenizer = buffer_tokenizer;
453
script_path = p_script_path.simplify_path();
454
current = tokenizer->scan();
455
// Avoid error or newline as the first token.
456
// The latter can mess with the parser when opening files filled exclusively with comments and newlines.
457
while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
458
if (current.type == GDScriptTokenizer::Token::ERROR) {
459
push_error(current.literal);
460
}
461
current = tokenizer->scan();
462
}
463
464
push_multiline(false); // Keep one for the whole parsing.
465
parse_program();
466
pop_multiline();
467
468
memdelete(buffer_tokenizer);
469
tokenizer = nullptr;
470
471
if (errors.is_empty()) {
472
return OK;
473
} else {
474
return ERR_PARSE_ERROR;
475
}
476
}
477
478
GDScriptTokenizer::Token GDScriptParser::advance() {
479
lambda_ended = false; // Empty marker since we're past the end in any case.
480
481
if (current.type == GDScriptTokenizer::Token::TK_EOF) {
482
ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
483
}
484
previous = current;
485
current = tokenizer->scan();
486
while (current.type == GDScriptTokenizer::Token::ERROR) {
487
push_error(current.literal);
488
current = tokenizer->scan();
489
}
490
if (previous.type != GDScriptTokenizer::Token::DEDENT) { // `DEDENT` belongs to the next non-empty line.
491
for (Node *n : nodes_in_progress) {
492
update_extents(n);
493
}
494
}
495
return previous;
496
}
497
498
bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
499
if (!check(p_token_type)) {
500
return false;
501
}
502
advance();
503
return true;
504
}
505
506
bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const {
507
if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
508
return current.is_identifier();
509
}
510
return current.type == p_token_type;
511
}
512
513
bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
514
if (match(p_token_type)) {
515
return true;
516
}
517
push_error(p_error_message);
518
return false;
519
}
520
521
bool GDScriptParser::is_at_end() const {
522
return check(GDScriptTokenizer::Token::TK_EOF);
523
}
524
525
void GDScriptParser::synchronize() {
526
panic_mode = false;
527
while (!is_at_end()) {
528
if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
529
return;
530
}
531
532
switch (current.type) {
533
case GDScriptTokenizer::Token::CLASS:
534
case GDScriptTokenizer::Token::FUNC:
535
case GDScriptTokenizer::Token::STATIC:
536
case GDScriptTokenizer::Token::VAR:
537
case GDScriptTokenizer::Token::TK_CONST:
538
case GDScriptTokenizer::Token::SIGNAL:
539
//case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
540
case GDScriptTokenizer::Token::FOR:
541
case GDScriptTokenizer::Token::WHILE:
542
case GDScriptTokenizer::Token::MATCH:
543
case GDScriptTokenizer::Token::RETURN:
544
case GDScriptTokenizer::Token::ANNOTATION:
545
return;
546
default:
547
// Do nothing.
548
break;
549
}
550
551
advance();
552
}
553
}
554
555
void GDScriptParser::push_multiline(bool p_state) {
556
multiline_stack.push_back(p_state);
557
tokenizer->set_multiline_mode(p_state);
558
if (p_state) {
559
// Consume potential whitespace tokens already waiting in line.
560
while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
561
current = tokenizer->scan(); // Don't call advance() here, as we don't want to change the previous token.
562
}
563
}
564
}
565
566
void GDScriptParser::pop_multiline() {
567
ERR_FAIL_COND_MSG(multiline_stack.is_empty(), "Parser bug: trying to pop from multiline stack without available value.");
568
multiline_stack.pop_back();
569
tokenizer->set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
570
}
571
572
bool GDScriptParser::is_statement_end_token() const {
573
return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
574
}
575
576
bool GDScriptParser::is_statement_end() const {
577
return lambda_ended || in_lambda || is_statement_end_token();
578
}
579
580
void GDScriptParser::end_statement(const String &p_context) {
581
bool found = false;
582
while (is_statement_end() && !is_at_end()) {
583
// Remove sequential newlines/semicolons.
584
if (is_statement_end_token()) {
585
// Only consume if this is an actual token.
586
advance();
587
} else if (lambda_ended) {
588
lambda_ended = false; // Consume this "token".
589
found = true;
590
break;
591
} else {
592
if (!found) {
593
lambda_ended = true; // Mark the lambda as done since we found something else to end the statement.
594
found = true;
595
}
596
break;
597
}
598
599
found = true;
600
}
601
if (!found && !is_at_end()) {
602
push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
603
}
604
}
605
606
void GDScriptParser::parse_program() {
607
head = alloc_node<ClassNode>();
608
head->start_line = 1;
609
head->end_line = 1;
610
head->fqcn = GDScript::canonicalize_path(script_path);
611
current_class = head;
612
bool can_have_class_or_extends = true;
613
614
#define PUSH_PENDING_ANNOTATIONS_TO_HEAD \
615
if (!annotation_stack.is_empty()) { \
616
for (AnnotationNode *annot : annotation_stack) { \
617
head->annotations.push_back(annot); \
618
} \
619
annotation_stack.clear(); \
620
}
621
622
while (!check(GDScriptTokenizer::Token::TK_EOF)) {
623
if (match(GDScriptTokenizer::Token::ANNOTATION)) {
624
AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
625
if (annotation != nullptr) {
626
if (annotation->applies_to(AnnotationInfo::CLASS)) {
627
// We do not know in advance what the annotation will be applied to: the `head` class or the subsequent inner class.
628
// If we encounter `class_name`, `extends` or pure `SCRIPT` annotation, then it's `head`, otherwise it's an inner class.
629
annotation_stack.push_back(annotation);
630
} else if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
631
PUSH_PENDING_ANNOTATIONS_TO_HEAD;
632
if (annotation->name == SNAME("@tool") || annotation->name == SNAME("@icon") || annotation->name == SNAME("@static_unload")) {
633
// Some annotations need to be resolved and applied in the parser.
634
// The root class is not in any class, so `head->outer == nullptr`.
635
annotation->apply(this, head, nullptr);
636
} else {
637
head->annotations.push_back(annotation);
638
}
639
} else if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
640
if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
641
push_error(R"(Expected newline after a standalone annotation.)");
642
}
643
if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
644
head->add_member_group(annotation);
645
// This annotation must appear after script-level annotations and `class_name`/`extends`,
646
// so we stop looking for script-level stuff.
647
can_have_class_or_extends = false;
648
break;
649
} else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
650
// Some annotations need to be resolved and applied in the parser.
651
annotation->apply(this, nullptr, nullptr);
652
} else {
653
push_error(R"(Unexpected standalone annotation.)");
654
}
655
} else {
656
annotation_stack.push_back(annotation);
657
// This annotation must appear after script-level annotations and `class_name`/`extends`,
658
// so we stop looking for script-level stuff.
659
can_have_class_or_extends = false;
660
break;
661
}
662
}
663
} else if (check(GDScriptTokenizer::Token::LITERAL) && current.literal.get_type() == Variant::STRING) {
664
// Allow strings in class body as multiline comments.
665
advance();
666
if (!match(GDScriptTokenizer::Token::NEWLINE)) {
667
push_error("Expected newline after comment string.");
668
}
669
} else {
670
break;
671
}
672
}
673
674
if (current.type == GDScriptTokenizer::Token::CLASS_NAME || current.type == GDScriptTokenizer::Token::EXTENDS) {
675
// Set range of the class to only start at extends or class_name if present.
676
reset_extents(head, current);
677
}
678
679
while (can_have_class_or_extends) {
680
// Order here doesn't matter, but there should be only one of each at most.
681
switch (current.type) {
682
case GDScriptTokenizer::Token::CLASS_NAME:
683
PUSH_PENDING_ANNOTATIONS_TO_HEAD;
684
advance();
685
if (head->identifier != nullptr) {
686
push_error(R"("class_name" can only be used once.)");
687
} else {
688
parse_class_name();
689
}
690
break;
691
case GDScriptTokenizer::Token::EXTENDS:
692
PUSH_PENDING_ANNOTATIONS_TO_HEAD;
693
advance();
694
if (head->extends_used) {
695
push_error(R"("extends" can only be used once.)");
696
} else {
697
parse_extends();
698
end_statement("superclass");
699
}
700
break;
701
case GDScriptTokenizer::Token::TK_EOF:
702
PUSH_PENDING_ANNOTATIONS_TO_HEAD;
703
can_have_class_or_extends = false;
704
break;
705
case GDScriptTokenizer::Token::LITERAL:
706
if (current.literal.get_type() == Variant::STRING) {
707
// Allow strings in class body as multiline comments.
708
advance();
709
if (!match(GDScriptTokenizer::Token::NEWLINE)) {
710
push_error("Expected newline after comment string.");
711
}
712
break;
713
}
714
[[fallthrough]];
715
default:
716
// No tokens are allowed between script annotations and class/extends.
717
can_have_class_or_extends = false;
718
break;
719
}
720
721
if (panic_mode) {
722
synchronize();
723
}
724
}
725
726
#undef PUSH_PENDING_ANNOTATIONS_TO_HEAD
727
728
for (AnnotationNode *&annotation : head->annotations) {
729
if (annotation->name == SNAME("@abstract")) {
730
// Some annotations need to be resolved and applied in the parser.
731
// The root class is not in any class, so `head->outer == nullptr`.
732
annotation->apply(this, head, nullptr);
733
}
734
}
735
736
// When the only thing needed is the class name, icon, and abstractness; we don't need to parse the whole file.
737
// It really speed up the call to `GDScriptLanguage::get_global_class_name()` especially for large script.
738
if (!parse_body) {
739
return;
740
}
741
742
parse_class_body(true);
743
744
head->end_line = current.end_line;
745
head->end_column = current.end_column;
746
747
complete_extents(head);
748
749
#ifdef TOOLS_ENABLED
750
const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
751
752
int max_line = head->end_line;
753
if (!head->members.is_empty()) {
754
max_line = MIN(max_script_doc_line, head->members[0].get_line() - 1);
755
}
756
757
int line = 0;
758
while (line <= max_line) {
759
// Find the start.
760
if (comments.has(line) && comments[line].new_line && comments[line].comment.begins_with("##")) {
761
// Find the end.
762
while (line + 1 <= max_line && comments.has(line + 1) && comments[line + 1].new_line && comments[line + 1].comment.begins_with("##")) {
763
line++;
764
}
765
head->doc_data = parse_class_doc_comment(line);
766
break;
767
}
768
line++;
769
}
770
#endif // TOOLS_ENABLED
771
772
if (!check(GDScriptTokenizer::Token::TK_EOF)) {
773
push_error("Expected end of file.");
774
}
775
776
clear_unused_annotations();
777
}
778
779
Ref<GDScriptParserRef> GDScriptParser::get_depended_parser_for(const String &p_path) {
780
Ref<GDScriptParserRef> ref;
781
if (depended_parsers.has(p_path)) {
782
ref = depended_parsers[p_path];
783
} else {
784
Error err = OK;
785
ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, script_path);
786
if (ref.is_valid()) {
787
depended_parsers[p_path] = ref;
788
}
789
}
790
791
return ref;
792
}
793
794
const HashMap<String, Ref<GDScriptParserRef>> &GDScriptParser::get_depended_parsers() {
795
return depended_parsers;
796
}
797
798
GDScriptParser::ClassNode *GDScriptParser::find_class(const String &p_qualified_name) const {
799
String first = p_qualified_name.get_slice("::", 0);
800
801
Vector<String> class_names;
802
GDScriptParser::ClassNode *result = nullptr;
803
// Empty initial name means start at the head.
804
if (first.is_empty() || (head->identifier && first == head->identifier->name)) {
805
class_names = p_qualified_name.split("::");
806
result = head;
807
} else if (p_qualified_name.begins_with(script_path)) {
808
// Script path could have a class path separator("::") in it.
809
class_names = p_qualified_name.trim_prefix(script_path).split("::");
810
result = head;
811
} else if (head->has_member(first)) {
812
class_names = p_qualified_name.split("::");
813
GDScriptParser::ClassNode::Member member = head->get_member(first);
814
if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
815
result = member.m_class;
816
}
817
}
818
819
// Starts at index 1 because index 0 was handled above.
820
for (int i = 1; result != nullptr && i < class_names.size(); i++) {
821
const String &current_name = class_names[i];
822
GDScriptParser::ClassNode *next = nullptr;
823
if (result->has_member(current_name)) {
824
GDScriptParser::ClassNode::Member member = result->get_member(current_name);
825
if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
826
next = member.m_class;
827
}
828
}
829
result = next;
830
}
831
832
return result;
833
}
834
835
bool GDScriptParser::has_class(const GDScriptParser::ClassNode *p_class) const {
836
if (head->fqcn.is_empty() && p_class->fqcn.get_slice("::", 0).is_empty()) {
837
return p_class == head;
838
} else if (p_class->fqcn.begins_with(head->fqcn)) {
839
return find_class(p_class->fqcn.trim_prefix(head->fqcn)) == p_class;
840
}
841
842
return false;
843
}
844
845
GDScriptParser::ClassNode *GDScriptParser::parse_class(bool p_is_static) {
846
ClassNode *n_class = alloc_node<ClassNode>();
847
848
ClassNode *previous_class = current_class;
849
current_class = n_class;
850
n_class->outer = previous_class;
851
852
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
853
n_class->identifier = parse_identifier();
854
if (n_class->outer) {
855
String fqcn = n_class->outer->fqcn;
856
if (fqcn.is_empty()) {
857
fqcn = GDScript::canonicalize_path(script_path);
858
}
859
n_class->fqcn = fqcn + "::" + n_class->identifier->name;
860
} else {
861
n_class->fqcn = n_class->identifier->name;
862
}
863
}
864
865
if (match(GDScriptTokenizer::Token::EXTENDS)) {
866
parse_extends();
867
}
868
869
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
870
871
bool multiline = match(GDScriptTokenizer::Token::NEWLINE);
872
873
if (multiline && !consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
874
current_class = previous_class;
875
complete_extents(n_class);
876
return n_class;
877
}
878
879
if (match(GDScriptTokenizer::Token::EXTENDS)) {
880
if (n_class->extends_used) {
881
push_error(R"(Cannot use "extends" more than once in the same class.)");
882
}
883
parse_extends();
884
end_statement("superclass");
885
}
886
887
parse_class_body(multiline);
888
complete_extents(n_class);
889
890
if (multiline) {
891
consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
892
}
893
894
current_class = previous_class;
895
return n_class;
896
}
897
898
void GDScriptParser::parse_class_name() {
899
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
900
current_class->identifier = parse_identifier();
901
current_class->fqcn = String(current_class->identifier->name);
902
}
903
904
if (match(GDScriptTokenizer::Token::EXTENDS)) {
905
// Allow extends on the same line.
906
parse_extends();
907
end_statement("superclass");
908
} else {
909
end_statement("class_name statement");
910
}
911
}
912
913
void GDScriptParser::parse_extends() {
914
current_class->extends_used = true;
915
916
int chain_index = 0;
917
918
if (match(GDScriptTokenizer::Token::LITERAL)) {
919
if (previous.literal.get_type() != Variant::STRING) {
920
push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
921
}
922
current_class->extends_path = previous.literal;
923
924
if (!match(GDScriptTokenizer::Token::PERIOD)) {
925
return;
926
}
927
}
928
929
make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
930
931
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
932
return;
933
}
934
current_class->extends.push_back(parse_identifier());
935
936
while (match(GDScriptTokenizer::Token::PERIOD)) {
937
make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
938
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
939
return;
940
}
941
current_class->extends.push_back(parse_identifier());
942
}
943
}
944
945
template <typename T>
946
void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(bool), AnnotationInfo::TargetKind p_target, const String &p_member_kind, bool p_is_static) {
947
advance();
948
949
// Consume annotations.
950
List<AnnotationNode *> annotations;
951
while (!annotation_stack.is_empty()) {
952
AnnotationNode *last_annotation = annotation_stack.back()->get();
953
if (last_annotation->applies_to(p_target)) {
954
annotations.push_front(last_annotation);
955
annotation_stack.pop_back();
956
} else {
957
push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
958
clear_unused_annotations();
959
}
960
}
961
962
T *member = (this->*p_parse_function)(p_is_static);
963
if (member == nullptr) {
964
return;
965
}
966
967
#ifdef TOOLS_ENABLED
968
int doc_comment_line = member->start_line - 1;
969
#endif // TOOLS_ENABLED
970
971
for (AnnotationNode *&annotation : annotations) {
972
member->annotations.push_back(annotation);
973
#ifdef TOOLS_ENABLED
974
if (annotation->start_line <= doc_comment_line) {
975
doc_comment_line = annotation->start_line - 1;
976
}
977
#endif // TOOLS_ENABLED
978
}
979
980
#ifdef TOOLS_ENABLED
981
if constexpr (std::is_same_v<T, ClassNode>) {
982
if (has_comment(member->start_line, true)) {
983
// Inline doc comment.
984
member->doc_data = parse_class_doc_comment(member->start_line, true);
985
} else if (has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
986
// Normal doc comment. Don't check `min_member_doc_line` because a class ends parsing after its members.
987
// This may not work correctly for cases like `var a; class B`, but it doesn't matter in practice.
988
member->doc_data = parse_class_doc_comment(doc_comment_line);
989
}
990
} else {
991
if (has_comment(member->start_line, true)) {
992
// Inline doc comment.
993
member->doc_data = parse_doc_comment(member->start_line, true);
994
} else if (doc_comment_line >= min_member_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
995
// Normal doc comment.
996
member->doc_data = parse_doc_comment(doc_comment_line);
997
}
998
}
999
1000
min_member_doc_line = member->end_line + 1; // Prevent multiple members from using the same doc comment.
1001
#endif // TOOLS_ENABLED
1002
1003
if (member->identifier != nullptr) {
1004
if (!((String)member->identifier->name).is_empty()) { // Enums may be unnamed.
1005
if (current_class->members_indices.has(member->identifier->name)) {
1006
push_error(vformat(R"(%s "%s" has the same name as a previously declared %s.)", p_member_kind.capitalize(), member->identifier->name, current_class->get_member(member->identifier->name).get_type_name()), member->identifier);
1007
} else {
1008
current_class->add_member(member);
1009
}
1010
} else {
1011
current_class->add_member(member);
1012
}
1013
}
1014
}
1015
1016
void GDScriptParser::parse_class_body(bool p_is_multiline) {
1017
bool class_end = false;
1018
bool next_is_static = false;
1019
while (!class_end && !is_at_end()) {
1020
GDScriptTokenizer::Token token = current;
1021
switch (token.type) {
1022
case GDScriptTokenizer::Token::VAR:
1023
parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable", next_is_static);
1024
if (next_is_static) {
1025
current_class->has_static_data = true;
1026
}
1027
break;
1028
case GDScriptTokenizer::Token::TK_CONST:
1029
parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
1030
break;
1031
case GDScriptTokenizer::Token::SIGNAL:
1032
parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
1033
break;
1034
case GDScriptTokenizer::Token::FUNC:
1035
parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function", next_is_static);
1036
break;
1037
case GDScriptTokenizer::Token::CLASS:
1038
parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class");
1039
break;
1040
case GDScriptTokenizer::Token::ENUM:
1041
parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
1042
break;
1043
case GDScriptTokenizer::Token::STATIC: {
1044
advance();
1045
next_is_static = true;
1046
if (!check(GDScriptTokenizer::Token::FUNC) && !check(GDScriptTokenizer::Token::VAR)) {
1047
push_error(R"(Expected "func" or "var" after "static".)");
1048
}
1049
} break;
1050
case GDScriptTokenizer::Token::ANNOTATION: {
1051
advance();
1052
1053
// Check for class-level and standalone annotations.
1054
AnnotationNode *annotation = parse_annotation(AnnotationInfo::CLASS_LEVEL | AnnotationInfo::STANDALONE);
1055
if (annotation != nullptr) {
1056
if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
1057
if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
1058
push_error(R"(Expected newline after a standalone annotation.)");
1059
}
1060
if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
1061
current_class->add_member_group(annotation);
1062
} else if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
1063
// Some annotations need to be resolved and applied in the parser.
1064
annotation->apply(this, nullptr, nullptr);
1065
} else {
1066
push_error(R"(Unexpected standalone annotation.)");
1067
}
1068
} else { // `AnnotationInfo::CLASS_LEVEL`.
1069
annotation_stack.push_back(annotation);
1070
}
1071
}
1072
break;
1073
}
1074
case GDScriptTokenizer::Token::PASS:
1075
advance();
1076
end_statement(R"("pass")");
1077
break;
1078
case GDScriptTokenizer::Token::DEDENT:
1079
class_end = true;
1080
break;
1081
case GDScriptTokenizer::Token::LITERAL:
1082
if (current.literal.get_type() == Variant::STRING) {
1083
// Allow strings in class body as multiline comments.
1084
advance();
1085
if (!match(GDScriptTokenizer::Token::NEWLINE)) {
1086
push_error("Expected newline after comment string.");
1087
}
1088
break;
1089
}
1090
[[fallthrough]];
1091
default:
1092
// Display a completion with identifiers.
1093
make_completion_context(COMPLETION_IDENTIFIER, nullptr);
1094
advance();
1095
if (previous.get_identifier() == "export") {
1096
push_error(R"(The "export" keyword was removed in Godot 4. Use an export annotation ("@export", "@export_range", etc.) instead.)");
1097
} else if (previous.get_identifier() == "tool") {
1098
push_error(R"(The "tool" keyword was removed in Godot 4. Use the "@tool" annotation instead.)");
1099
} else if (previous.get_identifier() == "onready") {
1100
push_error(R"(The "onready" keyword was removed in Godot 4. Use the "@onready" annotation instead.)");
1101
} else if (previous.get_identifier() == "remote") {
1102
push_error(R"(The "remote" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" instead.)");
1103
} else if (previous.get_identifier() == "remotesync") {
1104
push_error(R"(The "remotesync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local" instead.)");
1105
} else if (previous.get_identifier() == "puppet") {
1106
push_error(R"(The "puppet" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" instead.)");
1107
} else if (previous.get_identifier() == "puppetsync") {
1108
push_error(R"(The "puppetsync" keyword was removed in Godot 4. Use the "@rpc" annotation with "authority" and "call_local" instead.)");
1109
} else if (previous.get_identifier() == "master") {
1110
push_error(R"(The "master" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and perform a check inside the function instead.)");
1111
} else if (previous.get_identifier() == "mastersync") {
1112
push_error(R"(The "mastersync" keyword was removed in Godot 4. Use the "@rpc" annotation with "any_peer" and "call_local", and perform a check inside the function instead.)");
1113
} else {
1114
push_error(vformat(R"(Unexpected %s in class body.)", previous.get_debug_name()));
1115
}
1116
break;
1117
}
1118
if (token.type != GDScriptTokenizer::Token::STATIC) {
1119
next_is_static = false;
1120
}
1121
if (panic_mode) {
1122
synchronize();
1123
}
1124
if (!p_is_multiline) {
1125
class_end = true;
1126
}
1127
}
1128
}
1129
1130
GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static) {
1131
return parse_variable(p_is_static, true);
1132
}
1133
1134
GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static, bool p_allow_property) {
1135
VariableNode *variable = alloc_node<VariableNode>();
1136
1137
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
1138
complete_extents(variable);
1139
return nullptr;
1140
}
1141
1142
variable->identifier = parse_identifier();
1143
variable->export_info.name = variable->identifier->name;
1144
variable->is_static = p_is_static;
1145
1146
if (match(GDScriptTokenizer::Token::COLON)) {
1147
if (check(GDScriptTokenizer::Token::NEWLINE)) {
1148
if (p_allow_property) {
1149
advance();
1150
return parse_property(variable, true);
1151
} else {
1152
push_error(R"(Expected type after ":")");
1153
complete_extents(variable);
1154
return nullptr;
1155
}
1156
} else if (check((GDScriptTokenizer::Token::EQUAL))) {
1157
// Infer type.
1158
variable->infer_datatype = true;
1159
} else {
1160
if (p_allow_property) {
1161
make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
1162
if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
1163
// Check if get or set.
1164
if (current.get_identifier() == "get" || current.get_identifier() == "set") {
1165
return parse_property(variable, false);
1166
}
1167
}
1168
}
1169
1170
// Parse type.
1171
variable->datatype_specifier = parse_type();
1172
}
1173
}
1174
1175
if (match(GDScriptTokenizer::Token::EQUAL)) {
1176
// Initializer.
1177
variable->initializer = parse_expression(false);
1178
if (variable->initializer == nullptr) {
1179
push_error(R"(Expected expression for variable initial value after "=".)");
1180
}
1181
variable->assignments++;
1182
}
1183
1184
if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
1185
if (match(GDScriptTokenizer::Token::NEWLINE)) {
1186
return parse_property(variable, true);
1187
} else {
1188
return parse_property(variable, false);
1189
}
1190
}
1191
1192
complete_extents(variable);
1193
end_statement("variable declaration");
1194
1195
return variable;
1196
}
1197
1198
GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
1199
if (p_need_indent) {
1200
if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
1201
complete_extents(p_variable);
1202
return nullptr;
1203
}
1204
}
1205
1206
VariableNode *property = p_variable;
1207
1208
make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
1209
1210
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
1211
complete_extents(p_variable);
1212
return nullptr;
1213
}
1214
1215
IdentifierNode *function = parse_identifier();
1216
1217
if (check(GDScriptTokenizer::Token::EQUAL)) {
1218
p_variable->property = VariableNode::PROP_SETGET;
1219
} else {
1220
p_variable->property = VariableNode::PROP_INLINE;
1221
if (!p_need_indent) {
1222
push_error("Property with inline code must go to an indented block.");
1223
}
1224
}
1225
1226
bool getter_used = false;
1227
bool setter_used = false;
1228
1229
// Run with a loop because order doesn't matter.
1230
for (int i = 0; i < 2; i++) {
1231
if (function->name == SNAME("set")) {
1232
if (setter_used) {
1233
push_error(R"(Properties can only have one setter.)");
1234
} else {
1235
parse_property_setter(property);
1236
setter_used = true;
1237
}
1238
} else if (function->name == SNAME("get")) {
1239
if (getter_used) {
1240
push_error(R"(Properties can only have one getter.)");
1241
} else {
1242
parse_property_getter(property);
1243
getter_used = true;
1244
}
1245
} else {
1246
// TODO: Update message to only have the missing one if it's the case.
1247
push_error(R"(Expected "get" or "set" for property declaration.)");
1248
}
1249
1250
if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
1251
if (match(GDScriptTokenizer::Token::COMMA)) {
1252
// Consume potential newline.
1253
if (match(GDScriptTokenizer::Token::NEWLINE)) {
1254
if (!p_need_indent) {
1255
push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
1256
}
1257
}
1258
} else {
1259
break;
1260
}
1261
}
1262
1263
if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
1264
break;
1265
}
1266
function = parse_identifier();
1267
}
1268
complete_extents(p_variable);
1269
1270
if (p_variable->property == VariableNode::PROP_SETGET) {
1271
end_statement("property declaration");
1272
}
1273
1274
if (p_need_indent) {
1275
consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
1276
}
1277
return property;
1278
}
1279
1280
void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
1281
switch (p_variable->property) {
1282
case VariableNode::PROP_INLINE: {
1283
FunctionNode *function = alloc_node<FunctionNode>();
1284
IdentifierNode *identifier = alloc_node<IdentifierNode>();
1285
complete_extents(identifier);
1286
identifier->name = "@" + p_variable->identifier->name + "_setter";
1287
function->identifier = identifier;
1288
function->is_static = p_variable->is_static;
1289
1290
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
1291
1292
ParameterNode *parameter = alloc_node<ParameterNode>();
1293
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
1294
reset_extents(parameter, previous);
1295
p_variable->setter_parameter = parse_identifier();
1296
parameter->identifier = p_variable->setter_parameter;
1297
function->parameters_indices[parameter->identifier->name] = 0;
1298
function->parameters.push_back(parameter);
1299
}
1300
complete_extents(parameter);
1301
1302
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
1303
consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
1304
1305
FunctionNode *previous_function = current_function;
1306
current_function = function;
1307
if (p_variable->setter_parameter != nullptr) {
1308
SuiteNode *body = alloc_node<SuiteNode>();
1309
body->add_local(parameter, function);
1310
function->body = parse_suite("setter declaration", body);
1311
p_variable->setter = function;
1312
}
1313
current_function = previous_function;
1314
complete_extents(function);
1315
break;
1316
}
1317
case VariableNode::PROP_SETGET:
1318
consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
1319
make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
1320
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
1321
p_variable->setter_pointer = parse_identifier();
1322
}
1323
break;
1324
case VariableNode::PROP_NONE:
1325
break; // Unreachable.
1326
}
1327
}
1328
1329
void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
1330
switch (p_variable->property) {
1331
case VariableNode::PROP_INLINE: {
1332
FunctionNode *function = alloc_node<FunctionNode>();
1333
1334
if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
1335
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after "get(".)*");
1336
consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after "get()".)*");
1337
} else {
1338
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" or "(" after "get".)");
1339
}
1340
1341
IdentifierNode *identifier = alloc_node<IdentifierNode>();
1342
complete_extents(identifier);
1343
identifier->name = "@" + p_variable->identifier->name + "_getter";
1344
function->identifier = identifier;
1345
function->is_static = p_variable->is_static;
1346
1347
FunctionNode *previous_function = current_function;
1348
current_function = function;
1349
1350
SuiteNode *body = alloc_node<SuiteNode>();
1351
function->body = parse_suite("getter declaration", body);
1352
p_variable->getter = function;
1353
1354
current_function = previous_function;
1355
complete_extents(function);
1356
break;
1357
}
1358
case VariableNode::PROP_SETGET:
1359
consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
1360
make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
1361
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
1362
p_variable->getter_pointer = parse_identifier();
1363
}
1364
break;
1365
case VariableNode::PROP_NONE:
1366
break; // Unreachable.
1367
}
1368
}
1369
1370
GDScriptParser::ConstantNode *GDScriptParser::parse_constant(bool p_is_static) {
1371
ConstantNode *constant = alloc_node<ConstantNode>();
1372
1373
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
1374
complete_extents(constant);
1375
return nullptr;
1376
}
1377
1378
constant->identifier = parse_identifier();
1379
1380
if (match(GDScriptTokenizer::Token::COLON)) {
1381
if (check((GDScriptTokenizer::Token::EQUAL))) {
1382
// Infer type.
1383
constant->infer_datatype = true;
1384
} else {
1385
// Parse type.
1386
constant->datatype_specifier = parse_type();
1387
}
1388
}
1389
1390
if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
1391
// Initializer.
1392
constant->initializer = parse_expression(false);
1393
1394
if (constant->initializer == nullptr) {
1395
push_error(R"(Expected initializer expression for constant.)");
1396
complete_extents(constant);
1397
return nullptr;
1398
}
1399
} else {
1400
complete_extents(constant);
1401
return nullptr;
1402
}
1403
1404
complete_extents(constant);
1405
end_statement("constant declaration");
1406
1407
return constant;
1408
}
1409
1410
GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
1411
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
1412
return nullptr;
1413
}
1414
1415
ParameterNode *parameter = alloc_node<ParameterNode>();
1416
parameter->identifier = parse_identifier();
1417
1418
if (match(GDScriptTokenizer::Token::COLON)) {
1419
if (check((GDScriptTokenizer::Token::EQUAL))) {
1420
// Infer type.
1421
parameter->infer_datatype = true;
1422
} else {
1423
// Parse type.
1424
make_completion_context(COMPLETION_TYPE_NAME, parameter);
1425
parameter->datatype_specifier = parse_type();
1426
}
1427
}
1428
1429
if (match(GDScriptTokenizer::Token::EQUAL)) {
1430
// Default value.
1431
parameter->initializer = parse_expression(false);
1432
}
1433
1434
complete_extents(parameter);
1435
return parameter;
1436
}
1437
1438
GDScriptParser::SignalNode *GDScriptParser::parse_signal(bool p_is_static) {
1439
SignalNode *signal = alloc_node<SignalNode>();
1440
1441
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
1442
complete_extents(signal);
1443
return nullptr;
1444
}
1445
1446
signal->identifier = parse_identifier();
1447
1448
if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
1449
push_multiline(true);
1450
advance();
1451
do {
1452
if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
1453
// Allow for trailing comma.
1454
break;
1455
}
1456
1457
ParameterNode *parameter = parse_parameter();
1458
if (parameter == nullptr) {
1459
push_error("Expected signal parameter name.");
1460
break;
1461
}
1462
if (parameter->initializer != nullptr) {
1463
push_error(R"(Signal parameters cannot have a default value.)");
1464
}
1465
if (signal->parameters_indices.has(parameter->identifier->name)) {
1466
push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
1467
} else {
1468
signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
1469
signal->parameters.push_back(parameter);
1470
}
1471
} while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
1472
1473
pop_multiline();
1474
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
1475
}
1476
1477
complete_extents(signal);
1478
end_statement("signal declaration");
1479
1480
return signal;
1481
}
1482
1483
GDScriptParser::EnumNode *GDScriptParser::parse_enum(bool p_is_static) {
1484
EnumNode *enum_node = alloc_node<EnumNode>();
1485
bool named = false;
1486
1487
if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
1488
enum_node->identifier = parse_identifier();
1489
named = true;
1490
}
1491
1492
push_multiline(true);
1493
consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
1494
#ifdef TOOLS_ENABLED
1495
int min_enum_value_doc_line = previous.end_line + 1;
1496
#endif
1497
1498
HashMap<StringName, int> elements;
1499
1500
#ifdef DEBUG_ENABLED
1501
List<MethodInfo> gdscript_funcs;
1502
GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
1503
#endif
1504
1505
do {
1506
if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
1507
break; // Allow trailing comma.
1508
}
1509
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
1510
GDScriptParser::IdentifierNode *identifier = parse_identifier();
1511
1512
EnumNode::Value item;
1513
item.identifier = identifier;
1514
item.parent_enum = enum_node;
1515
item.line = previous.start_line;
1516
item.start_column = previous.start_column;
1517
item.end_column = previous.end_column;
1518
1519
if (elements.has(item.identifier->name)) {
1520
push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
1521
} else if (!named) {
1522
if (current_class->members_indices.has(item.identifier->name)) {
1523
push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, current_class->get_member(item.identifier->name).get_type_name()));
1524
}
1525
}
1526
1527
elements[item.identifier->name] = item.line;
1528
1529
if (match(GDScriptTokenizer::Token::EQUAL)) {
1530
ExpressionNode *value = parse_expression(false);
1531
if (value == nullptr) {
1532
push_error(R"(Expected expression value after "=".)");
1533
}
1534
item.custom_value = value;
1535
}
1536
1537
item.index = enum_node->values.size();
1538
enum_node->values.push_back(item);
1539
if (!named) {
1540
// Add as member of current class.
1541
current_class->add_member(item);
1542
}
1543
}
1544
} while (match(GDScriptTokenizer::Token::COMMA));
1545
1546
#ifdef TOOLS_ENABLED
1547
// Enum values documentation.
1548
for (int i = 0; i < enum_node->values.size(); i++) {
1549
int enum_value_line = enum_node->values[i].line;
1550
int doc_comment_line = enum_value_line - 1;
1551
1552
MemberDocData doc_data;
1553
if (has_comment(enum_value_line, true)) {
1554
// Inline doc comment.
1555
if (i == enum_node->values.size() - 1 || enum_node->values[i + 1].line > enum_value_line) {
1556
doc_data = parse_doc_comment(enum_value_line, true);
1557
}
1558
} else if (doc_comment_line >= min_enum_value_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
1559
// Normal doc comment.
1560
doc_data = parse_doc_comment(doc_comment_line);
1561
}
1562
1563
if (named) {
1564
enum_node->values.write[i].doc_data = doc_data;
1565
} else {
1566
current_class->set_enum_value_doc_data(enum_node->values[i].identifier->name, doc_data);
1567
}
1568
1569
min_enum_value_doc_line = enum_value_line + 1; // Prevent multiple enum values from using the same doc comment.
1570
}
1571
#endif // TOOLS_ENABLED
1572
1573
pop_multiline();
1574
consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
1575
complete_extents(enum_node);
1576
end_statement("enum");
1577
1578
return enum_node;
1579
}
1580
1581
bool GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type, int p_signature_start) {
1582
if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
1583
bool default_used = false;
1584
do {
1585
if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
1586
// Allow for trailing comma.
1587
break;
1588
}
1589
1590
bool is_rest = false;
1591
if (match(GDScriptTokenizer::Token::PERIOD_PERIOD_PERIOD)) {
1592
is_rest = true;
1593
}
1594
1595
ParameterNode *parameter = parse_parameter();
1596
if (parameter == nullptr) {
1597
break;
1598
}
1599
1600
if (p_function->is_vararg()) {
1601
push_error("Cannot have parameters after the rest parameter.");
1602
continue;
1603
}
1604
1605
if (parameter->initializer != nullptr) {
1606
if (is_rest) {
1607
push_error("The rest parameter cannot have a default value.");
1608
continue;
1609
}
1610
default_used = true;
1611
} else {
1612
if (default_used && !is_rest) {
1613
push_error("Cannot have mandatory parameters after optional parameters.");
1614
continue;
1615
}
1616
}
1617
1618
if (p_function->parameters_indices.has(parameter->identifier->name)) {
1619
push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
1620
} else if (is_rest) {
1621
p_function->rest_parameter = parameter;
1622
p_body->add_local(parameter, current_function);
1623
} else {
1624
p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
1625
p_function->parameters.push_back(parameter);
1626
p_body->add_local(parameter, current_function);
1627
}
1628
} while (match(GDScriptTokenizer::Token::COMMA));
1629
}
1630
1631
pop_multiline();
1632
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
1633
1634
if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
1635
make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
1636
p_function->return_type = parse_type(true);
1637
if (p_function->return_type == nullptr) {
1638
push_error(R"(Expected return type or "void" after "->".)");
1639
}
1640
}
1641
1642
if (!p_function->source_lambda && p_function->identifier && p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init) {
1643
if (!p_function->is_static) {
1644
push_error(R"(Static constructor must be declared static.)");
1645
}
1646
if (!p_function->parameters.is_empty() || p_function->is_vararg()) {
1647
push_error(R"(Static constructor cannot have parameters.)");
1648
}
1649
current_class->has_static_data = true;
1650
}
1651
1652
#ifdef TOOLS_ENABLED
1653
if (p_type == "function" && p_signature_start != -1) {
1654
const int signature_end_pos = tokenizer->get_current_position() - 1;
1655
const String source_code = tokenizer->get_source_code();
1656
p_function->signature = source_code.substr(p_signature_start, signature_end_pos - p_signature_start).strip_edges(false, true);
1657
}
1658
#endif // TOOLS_ENABLED
1659
1660
// TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
1661
if (p_type == "lambda") {
1662
return consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after lambda declaration.)");
1663
}
1664
// The colon may not be present in the case of abstract functions.
1665
return match(GDScriptTokenizer::Token::COLON);
1666
}
1667
1668
GDScriptParser::FunctionNode *GDScriptParser::parse_function(bool p_is_static) {
1669
FunctionNode *function = alloc_node<FunctionNode>();
1670
function->is_static = p_is_static;
1671
1672
make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
1673
1674
#ifdef TOOLS_ENABLED
1675
// The signature is something like `(a: int, b: int = 0) -> void`.
1676
// We start one token earlier, since the parser looks one token ahead.
1677
const int signature_start_pos = tokenizer->get_current_position();
1678
#endif // TOOLS_ENABLED
1679
1680
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
1681
complete_extents(function);
1682
return nullptr;
1683
}
1684
1685
FunctionNode *previous_function = current_function;
1686
current_function = function;
1687
1688
function->identifier = parse_identifier();
1689
1690
SuiteNode *body = alloc_node<SuiteNode>();
1691
1692
SuiteNode *previous_suite = current_suite;
1693
current_suite = body;
1694
1695
push_multiline(true);
1696
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
1697
1698
#ifdef TOOLS_ENABLED
1699
const bool has_body = parse_function_signature(function, body, "function", signature_start_pos);
1700
#else // !TOOLS_ENABLED
1701
const bool has_body = parse_function_signature(function, body, "function", -1);
1702
#endif // TOOLS_ENABLED
1703
1704
current_suite = previous_suite;
1705
1706
#ifdef TOOLS_ENABLED
1707
function->min_local_doc_line = previous.end_line + 1;
1708
#endif // TOOLS_ENABLED
1709
1710
if (!has_body) {
1711
// Abstract functions do not have a body.
1712
end_statement("bodyless function declaration");
1713
reset_extents(body, current);
1714
complete_extents(body);
1715
function->body = body;
1716
} else {
1717
function->body = parse_suite("function declaration", body);
1718
}
1719
1720
current_function = previous_function;
1721
complete_extents(function);
1722
return function;
1723
}
1724
1725
GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
1726
AnnotationNode *annotation = alloc_node<AnnotationNode>();
1727
1728
annotation->name = previous.literal;
1729
1730
make_completion_context(COMPLETION_ANNOTATION, annotation);
1731
1732
bool valid = true;
1733
1734
if (!valid_annotations.has(annotation->name)) {
1735
if (annotation->name == "@deprecated") {
1736
push_error(R"("@deprecated" annotation does not exist. Use "## @deprecated: Reason here." instead.)");
1737
} else if (annotation->name == "@experimental") {
1738
push_error(R"("@experimental" annotation does not exist. Use "## @experimental: Reason here." instead.)");
1739
} else if (annotation->name == "@tutorial") {
1740
push_error(R"("@tutorial" annotation does not exist. Use "## @tutorial(Title): https://example.com" instead.)");
1741
} else {
1742
push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
1743
}
1744
valid = false;
1745
}
1746
1747
if (valid) {
1748
annotation->info = &valid_annotations[annotation->name];
1749
1750
if (!annotation->applies_to(p_valid_targets)) {
1751
if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
1752
push_error(vformat(R"(Annotation "%s" must be at the top of the script, before "extends" and "class_name".)", annotation->name));
1753
} else {
1754
push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
1755
}
1756
valid = false;
1757
}
1758
}
1759
1760
if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
1761
push_multiline(true);
1762
advance();
1763
// Arguments.
1764
push_completion_call(annotation);
1765
int argument_index = 0;
1766
do {
1767
make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
1768
set_last_completion_call_arg(argument_index);
1769
if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
1770
// Allow for trailing comma.
1771
break;
1772
}
1773
1774
ExpressionNode *argument = parse_expression(false);
1775
1776
if (argument == nullptr) {
1777
push_error("Expected expression as the annotation argument.");
1778
valid = false;
1779
} else {
1780
annotation->arguments.push_back(argument);
1781
1782
if (argument->type == Node::LITERAL) {
1783
override_completion_context(argument, COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index);
1784
}
1785
}
1786
1787
argument_index++;
1788
} while (match(GDScriptTokenizer::Token::COMMA));
1789
1790
pop_multiline();
1791
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
1792
pop_completion_call();
1793
}
1794
complete_extents(annotation);
1795
1796
match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
1797
1798
if (valid) {
1799
valid = validate_annotation_arguments(annotation);
1800
}
1801
1802
return valid ? annotation : nullptr;
1803
}
1804
1805
void GDScriptParser::clear_unused_annotations() {
1806
for (const AnnotationNode *annotation : annotation_stack) {
1807
push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
1808
}
1809
1810
annotation_stack.clear();
1811
}
1812
1813
bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, const Vector<Variant> &p_default_arguments, bool p_is_vararg) {
1814
ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
1815
1816
AnnotationInfo new_annotation;
1817
new_annotation.info = p_info;
1818
new_annotation.info.default_arguments = p_default_arguments;
1819
if (p_is_vararg) {
1820
new_annotation.info.flags |= METHOD_FLAG_VARARG;
1821
}
1822
new_annotation.apply = p_apply;
1823
new_annotation.target_kind = p_target_kinds;
1824
1825
valid_annotations[p_info.name] = new_annotation;
1826
return true;
1827
}
1828
1829
GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
1830
SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
1831
suite->parent_block = current_suite;
1832
suite->parent_function = current_function;
1833
current_suite = suite;
1834
1835
if (!p_for_lambda && suite->parent_block != nullptr && suite->parent_block->is_in_loop) {
1836
// Do not reset to false if true is set before calling parse_suite().
1837
suite->is_in_loop = true;
1838
}
1839
1840
bool multiline = false;
1841
1842
if (match(GDScriptTokenizer::Token::NEWLINE)) {
1843
multiline = true;
1844
}
1845
1846
if (multiline) {
1847
if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
1848
current_suite = suite->parent_block;
1849
complete_extents(suite);
1850
return suite;
1851
}
1852
}
1853
reset_extents(suite, current);
1854
1855
int error_count = 0;
1856
1857
do {
1858
if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
1859
break;
1860
}
1861
Node *statement = parse_statement();
1862
if (statement == nullptr) {
1863
if (error_count++ > 100) {
1864
push_error("Too many statement errors.", suite);
1865
break;
1866
}
1867
continue;
1868
}
1869
suite->statements.push_back(statement);
1870
1871
// Register locals.
1872
switch (statement->type) {
1873
case Node::VARIABLE: {
1874
VariableNode *variable = static_cast<VariableNode *>(statement);
1875
const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
1876
if (local.type != SuiteNode::Local::UNDEFINED) {
1877
push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
1878
}
1879
current_suite->add_local(variable, current_function);
1880
break;
1881
}
1882
case Node::CONSTANT: {
1883
ConstantNode *constant = static_cast<ConstantNode *>(statement);
1884
const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
1885
if (local.type != SuiteNode::Local::UNDEFINED) {
1886
String name;
1887
if (local.type == SuiteNode::Local::CONSTANT) {
1888
name = "constant";
1889
} else {
1890
name = "variable";
1891
}
1892
push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
1893
}
1894
current_suite->add_local(constant, current_function);
1895
break;
1896
}
1897
default:
1898
break;
1899
}
1900
1901
} while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
1902
1903
complete_extents(suite);
1904
1905
if (multiline) {
1906
if (!lambda_ended) {
1907
consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
1908
1909
} else {
1910
match(GDScriptTokenizer::Token::DEDENT);
1911
}
1912
} else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
1913
consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
1914
}
1915
1916
if (p_for_lambda) {
1917
lambda_ended = true;
1918
}
1919
current_suite = suite->parent_block;
1920
return suite;
1921
}
1922
1923
GDScriptParser::Node *GDScriptParser::parse_statement() {
1924
Node *result = nullptr;
1925
#ifdef DEBUG_ENABLED
1926
bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
1927
#endif
1928
1929
List<AnnotationNode *> annotations;
1930
if (current.type != GDScriptTokenizer::Token::ANNOTATION) {
1931
while (!annotation_stack.is_empty()) {
1932
AnnotationNode *last_annotation = annotation_stack.back()->get();
1933
if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
1934
annotations.push_front(last_annotation);
1935
annotation_stack.pop_back();
1936
} else {
1937
push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
1938
clear_unused_annotations();
1939
}
1940
}
1941
}
1942
1943
switch (current.type) {
1944
case GDScriptTokenizer::Token::PASS:
1945
advance();
1946
result = alloc_node<PassNode>();
1947
complete_extents(result);
1948
end_statement(R"("pass")");
1949
break;
1950
case GDScriptTokenizer::Token::VAR:
1951
advance();
1952
result = parse_variable(false, false);
1953
break;
1954
case GDScriptTokenizer::Token::TK_CONST:
1955
advance();
1956
result = parse_constant(false);
1957
break;
1958
case GDScriptTokenizer::Token::IF:
1959
advance();
1960
result = parse_if();
1961
break;
1962
case GDScriptTokenizer::Token::FOR:
1963
advance();
1964
result = parse_for();
1965
break;
1966
case GDScriptTokenizer::Token::WHILE:
1967
advance();
1968
result = parse_while();
1969
break;
1970
case GDScriptTokenizer::Token::MATCH:
1971
advance();
1972
result = parse_match();
1973
break;
1974
case GDScriptTokenizer::Token::BREAK:
1975
advance();
1976
result = parse_break();
1977
break;
1978
case GDScriptTokenizer::Token::CONTINUE:
1979
advance();
1980
result = parse_continue();
1981
break;
1982
case GDScriptTokenizer::Token::RETURN: {
1983
advance();
1984
ReturnNode *n_return = alloc_node<ReturnNode>();
1985
if (!is_statement_end()) {
1986
if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
1987
push_error(R"(Constructor cannot return a value.)");
1988
}
1989
n_return->return_value = parse_expression(false);
1990
} else if (in_lambda && !is_statement_end_token()) {
1991
// Try to parse it anyway as this might not be the statement end in a lambda.
1992
// If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
1993
n_return->return_value = parse_expression(false);
1994
}
1995
complete_extents(n_return);
1996
result = n_return;
1997
1998
current_suite->has_return = true;
1999
2000
end_statement("return statement");
2001
break;
2002
}
2003
case GDScriptTokenizer::Token::BREAKPOINT:
2004
advance();
2005
result = alloc_node<BreakpointNode>();
2006
complete_extents(result);
2007
end_statement(R"("breakpoint")");
2008
break;
2009
case GDScriptTokenizer::Token::ASSERT:
2010
advance();
2011
result = parse_assert();
2012
break;
2013
case GDScriptTokenizer::Token::ANNOTATION: {
2014
advance();
2015
AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT | AnnotationInfo::STANDALONE);
2016
if (annotation != nullptr) {
2017
if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
2018
if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
2019
push_error(R"(Expected newline after a standalone annotation.)");
2020
}
2021
if (annotation->name == SNAME("@warning_ignore_start") || annotation->name == SNAME("@warning_ignore_restore")) {
2022
// Some annotations need to be resolved and applied in the parser.
2023
annotation->apply(this, nullptr, nullptr);
2024
} else {
2025
push_error(R"(Unexpected standalone annotation.)");
2026
}
2027
} else {
2028
annotation_stack.push_back(annotation);
2029
}
2030
}
2031
break;
2032
}
2033
default: {
2034
// Expression statement.
2035
ExpressionNode *expression = parse_expression(true); // Allow assignment here.
2036
bool has_ended_lambda = false;
2037
if (expression == nullptr) {
2038
if (in_lambda) {
2039
// If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
2040
lambda_ended = true;
2041
has_ended_lambda = true;
2042
} else {
2043
advance();
2044
push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
2045
}
2046
} else {
2047
end_statement("expression");
2048
}
2049
lambda_ended = lambda_ended || has_ended_lambda;
2050
result = expression;
2051
2052
#ifdef DEBUG_ENABLED
2053
if (expression != nullptr) {
2054
switch (expression->type) {
2055
case Node::ASSIGNMENT:
2056
case Node::AWAIT:
2057
case Node::CALL:
2058
// Fine.
2059
break;
2060
case Node::PRELOAD:
2061
// `preload` is a function-like keyword.
2062
push_warning(expression, GDScriptWarning::RETURN_VALUE_DISCARDED, "preload");
2063
break;
2064
case Node::LAMBDA:
2065
// Standalone lambdas can't be used, so make this an error.
2066
push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
2067
break;
2068
case Node::LITERAL:
2069
// Allow strings as multiline comments.
2070
if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() != Variant::STRING) {
2071
push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
2072
}
2073
break;
2074
case Node::TERNARY_OPERATOR:
2075
push_warning(expression, GDScriptWarning::STANDALONE_TERNARY);
2076
break;
2077
default:
2078
push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
2079
}
2080
}
2081
#endif
2082
break;
2083
}
2084
}
2085
2086
#ifdef TOOLS_ENABLED
2087
int doc_comment_line = 0;
2088
if (result != nullptr) {
2089
doc_comment_line = result->start_line - 1;
2090
}
2091
#endif // TOOLS_ENABLED
2092
2093
if (result != nullptr && !annotations.is_empty()) {
2094
for (AnnotationNode *&annotation : annotations) {
2095
result->annotations.push_back(annotation);
2096
#ifdef TOOLS_ENABLED
2097
if (annotation->start_line <= doc_comment_line) {
2098
doc_comment_line = annotation->start_line - 1;
2099
}
2100
#endif // TOOLS_ENABLED
2101
}
2102
}
2103
2104
#ifdef TOOLS_ENABLED
2105
if (result != nullptr) {
2106
MemberDocData doc_data;
2107
if (has_comment(result->start_line, true)) {
2108
// Inline doc comment.
2109
doc_data = parse_doc_comment(result->start_line, true);
2110
} else if (doc_comment_line >= current_function->min_local_doc_line && has_comment(doc_comment_line, true) && tokenizer->get_comments()[doc_comment_line].new_line) {
2111
// Normal doc comment.
2112
doc_data = parse_doc_comment(doc_comment_line);
2113
}
2114
2115
if (result->type == Node::CONSTANT) {
2116
static_cast<ConstantNode *>(result)->doc_data = doc_data;
2117
} else if (result->type == Node::VARIABLE) {
2118
static_cast<VariableNode *>(result)->doc_data = doc_data;
2119
}
2120
2121
current_function->min_local_doc_line = result->end_line + 1; // Prevent multiple locals from using the same doc comment.
2122
}
2123
#endif // TOOLS_ENABLED
2124
2125
#ifdef DEBUG_ENABLED
2126
if (unreachable && result != nullptr) {
2127
current_suite->has_unreachable_code = true;
2128
if (current_function) {
2129
push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
2130
} else {
2131
// TODO: Properties setters and getters with unreachable code are not being warned
2132
}
2133
}
2134
#endif
2135
2136
if (panic_mode) {
2137
synchronize();
2138
}
2139
2140
return result;
2141
}
2142
2143
GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
2144
// TODO: Add assert message.
2145
AssertNode *assert = alloc_node<AssertNode>();
2146
2147
push_multiline(true);
2148
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
2149
2150
assert->condition = parse_expression(false);
2151
if (assert->condition == nullptr) {
2152
push_error("Expected expression to assert.");
2153
pop_multiline();
2154
complete_extents(assert);
2155
return nullptr;
2156
}
2157
2158
if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
2159
assert->message = parse_expression(false);
2160
if (assert->message == nullptr) {
2161
push_error(R"(Expected error message for assert after ",".)");
2162
pop_multiline();
2163
complete_extents(assert);
2164
return nullptr;
2165
}
2166
match(GDScriptTokenizer::Token::COMMA);
2167
}
2168
2169
pop_multiline();
2170
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
2171
2172
complete_extents(assert);
2173
end_statement(R"("assert")");
2174
2175
return assert;
2176
}
2177
2178
GDScriptParser::BreakNode *GDScriptParser::parse_break() {
2179
if (!can_break) {
2180
push_error(R"(Cannot use "break" outside of a loop.)");
2181
}
2182
BreakNode *break_node = alloc_node<BreakNode>();
2183
complete_extents(break_node);
2184
end_statement(R"("break")");
2185
return break_node;
2186
}
2187
2188
GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
2189
if (!can_continue) {
2190
push_error(R"(Cannot use "continue" outside of a loop.)");
2191
}
2192
current_suite->has_continue = true;
2193
ContinueNode *cont = alloc_node<ContinueNode>();
2194
complete_extents(cont);
2195
end_statement(R"("continue")");
2196
return cont;
2197
}
2198
2199
GDScriptParser::ForNode *GDScriptParser::parse_for() {
2200
ForNode *n_for = alloc_node<ForNode>();
2201
2202
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
2203
n_for->variable = parse_identifier();
2204
}
2205
2206
if (match(GDScriptTokenizer::Token::COLON)) {
2207
n_for->datatype_specifier = parse_type();
2208
if (n_for->datatype_specifier == nullptr) {
2209
push_error(R"(Expected type specifier after ":".)");
2210
}
2211
}
2212
2213
if (n_for->datatype_specifier == nullptr) {
2214
consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" or ":" after "for" variable name.)");
2215
} else {
2216
consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "for" variable type specifier.)");
2217
}
2218
2219
n_for->list = parse_expression(false);
2220
2221
if (!n_for->list) {
2222
push_error(R"(Expected iterable after "in".)");
2223
}
2224
2225
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
2226
2227
// Save break/continue state.
2228
bool could_break = can_break;
2229
bool could_continue = can_continue;
2230
2231
// Allow break/continue.
2232
can_break = true;
2233
can_continue = true;
2234
2235
SuiteNode *suite = alloc_node<SuiteNode>();
2236
if (n_for->variable) {
2237
const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
2238
if (local.type != SuiteNode::Local::UNDEFINED) {
2239
push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), n_for->variable->name), n_for->variable);
2240
}
2241
suite->add_local(SuiteNode::Local(n_for->variable, current_function));
2242
}
2243
suite->is_in_loop = true;
2244
n_for->loop = parse_suite(R"("for" block)", suite);
2245
complete_extents(n_for);
2246
2247
// Reset break/continue state.
2248
can_break = could_break;
2249
can_continue = could_continue;
2250
2251
return n_for;
2252
}
2253
2254
GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
2255
IfNode *n_if = alloc_node<IfNode>();
2256
2257
n_if->condition = parse_expression(false);
2258
if (n_if->condition == nullptr) {
2259
push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
2260
}
2261
2262
consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
2263
2264
n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
2265
n_if->true_block->parent_if = n_if;
2266
2267
if (n_if->true_block->has_continue) {
2268
current_suite->has_continue = true;
2269
}
2270
2271
if (match(GDScriptTokenizer::Token::ELIF)) {
2272
SuiteNode *else_block = alloc_node<SuiteNode>();
2273
else_block->parent_function = current_function;
2274
else_block->parent_block = current_suite;
2275
2276
SuiteNode *previous_suite = current_suite;
2277
current_suite = else_block;
2278
2279
IfNode *elif = parse_if("elif");
2280
else_block->statements.push_back(elif);
2281
complete_extents(else_block);
2282
n_if->false_block = else_block;
2283
2284
current_suite = previous_suite;
2285
} else if (match(GDScriptTokenizer::Token::ELSE)) {
2286
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
2287
n_if->false_block = parse_suite(R"("else" block)");
2288
}
2289
complete_extents(n_if);
2290
2291
if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
2292
current_suite->has_return = true;
2293
}
2294
if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
2295
current_suite->has_continue = true;
2296
}
2297
2298
return n_if;
2299
}
2300
2301
GDScriptParser::MatchNode *GDScriptParser::parse_match() {
2302
MatchNode *match_node = alloc_node<MatchNode>();
2303
2304
match_node->test = parse_expression(false);
2305
if (match_node->test == nullptr) {
2306
push_error(R"(Expected expression to test after "match".)");
2307
}
2308
2309
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
2310
consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
2311
2312
if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
2313
complete_extents(match_node);
2314
return match_node;
2315
}
2316
2317
bool all_have_return = true;
2318
bool have_wildcard = false;
2319
2320
List<AnnotationNode *> match_branch_annotation_stack;
2321
2322
while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
2323
if (match(GDScriptTokenizer::Token::PASS)) {
2324
consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after "pass".)");
2325
continue;
2326
}
2327
2328
if (match(GDScriptTokenizer::Token::ANNOTATION)) {
2329
AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
2330
if (annotation == nullptr) {
2331
continue;
2332
}
2333
if (annotation->name != SNAME("@warning_ignore")) {
2334
push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name), annotation);
2335
continue;
2336
}
2337
match_branch_annotation_stack.push_back(annotation);
2338
continue;
2339
}
2340
2341
MatchBranchNode *branch = parse_match_branch();
2342
if (branch == nullptr) {
2343
advance();
2344
continue;
2345
}
2346
2347
for (AnnotationNode *annotation : match_branch_annotation_stack) {
2348
branch->annotations.push_back(annotation);
2349
}
2350
match_branch_annotation_stack.clear();
2351
2352
#ifdef DEBUG_ENABLED
2353
if (have_wildcard && !branch->patterns.is_empty()) {
2354
push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
2355
}
2356
#endif
2357
2358
have_wildcard = have_wildcard || branch->has_wildcard;
2359
all_have_return = all_have_return && branch->block->has_return;
2360
match_node->branches.push_back(branch);
2361
}
2362
complete_extents(match_node);
2363
2364
consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
2365
2366
if (all_have_return && have_wildcard) {
2367
current_suite->has_return = true;
2368
}
2369
2370
for (const AnnotationNode *annotation : match_branch_annotation_stack) {
2371
push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
2372
}
2373
match_branch_annotation_stack.clear();
2374
2375
return match_node;
2376
}
2377
2378
GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
2379
MatchBranchNode *branch = alloc_node<MatchBranchNode>();
2380
reset_extents(branch, current);
2381
2382
bool has_bind = false;
2383
2384
do {
2385
PatternNode *pattern = parse_match_pattern();
2386
if (pattern == nullptr) {
2387
continue;
2388
}
2389
if (pattern->binds.size() > 0) {
2390
has_bind = true;
2391
}
2392
if (branch->patterns.size() > 0 && has_bind) {
2393
push_error(R"(Cannot use a variable bind with multiple patterns.)");
2394
}
2395
if (pattern->pattern_type == PatternNode::PT_REST) {
2396
push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
2397
} else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
2398
branch->has_wildcard = true;
2399
}
2400
branch->patterns.push_back(pattern);
2401
} while (match(GDScriptTokenizer::Token::COMMA));
2402
2403
if (branch->patterns.is_empty()) {
2404
push_error(R"(No pattern found for "match" branch.)");
2405
}
2406
2407
bool has_guard = false;
2408
if (match(GDScriptTokenizer::Token::WHEN)) {
2409
// Pattern guard.
2410
// Create block for guard because it also needs to access the bound variables from patterns, and we don't want to add them to the outer scope.
2411
branch->guard_body = alloc_node<SuiteNode>();
2412
if (branch->patterns.size() > 0) {
2413
for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
2414
SuiteNode::Local local(E.value, current_function);
2415
local.type = SuiteNode::Local::PATTERN_BIND;
2416
branch->guard_body->add_local(local);
2417
}
2418
}
2419
2420
SuiteNode *parent_block = current_suite;
2421
branch->guard_body->parent_block = parent_block;
2422
current_suite = branch->guard_body;
2423
2424
ExpressionNode *guard = parse_expression(false);
2425
if (guard == nullptr) {
2426
push_error(R"(Expected expression for pattern guard after "when".)");
2427
} else {
2428
branch->guard_body->statements.append(guard);
2429
}
2430
current_suite = parent_block;
2431
complete_extents(branch->guard_body);
2432
2433
has_guard = true;
2434
branch->has_wildcard = false; // If it has a guard, the wildcard might still not match.
2435
}
2436
2437
if (!consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":"%s after "match" %s.)", has_guard ? "" : R"( or "when")", has_guard ? "pattern guard" : "patterns"))) {
2438
branch->block = alloc_recovery_suite();
2439
complete_extents(branch);
2440
// Consume the whole line and treat the next one as new match branch.
2441
while (current.type != GDScriptTokenizer::Token::NEWLINE && !is_at_end()) {
2442
advance();
2443
}
2444
if (!is_at_end()) {
2445
advance();
2446
}
2447
return branch;
2448
}
2449
2450
SuiteNode *suite = alloc_node<SuiteNode>();
2451
if (branch->patterns.size() > 0) {
2452
for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
2453
SuiteNode::Local local(E.value, current_function);
2454
local.type = SuiteNode::Local::PATTERN_BIND;
2455
suite->add_local(local);
2456
}
2457
}
2458
2459
branch->block = parse_suite("match pattern block", suite);
2460
complete_extents(branch);
2461
2462
return branch;
2463
}
2464
2465
GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
2466
PatternNode *pattern = alloc_node<PatternNode>();
2467
reset_extents(pattern, current);
2468
2469
switch (current.type) {
2470
case GDScriptTokenizer::Token::VAR: {
2471
// Bind.
2472
advance();
2473
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
2474
complete_extents(pattern);
2475
return nullptr;
2476
}
2477
pattern->pattern_type = PatternNode::PT_BIND;
2478
pattern->bind = parse_identifier();
2479
2480
PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
2481
2482
if (p_root_pattern != nullptr) {
2483
if (p_root_pattern->has_bind(pattern->bind->name)) {
2484
push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
2485
complete_extents(pattern);
2486
return nullptr;
2487
}
2488
}
2489
2490
if (current_suite->has_local(pattern->bind->name)) {
2491
push_error(vformat(R"(There's already a %s named "%s" in this scope.)", current_suite->get_local(pattern->bind->name).get_name(), pattern->bind->name));
2492
complete_extents(pattern);
2493
return nullptr;
2494
}
2495
2496
root_pattern->binds[pattern->bind->name] = pattern->bind;
2497
2498
} break;
2499
case GDScriptTokenizer::Token::UNDERSCORE:
2500
// Wildcard.
2501
advance();
2502
pattern->pattern_type = PatternNode::PT_WILDCARD;
2503
break;
2504
case GDScriptTokenizer::Token::PERIOD_PERIOD:
2505
// Rest.
2506
advance();
2507
pattern->pattern_type = PatternNode::PT_REST;
2508
break;
2509
case GDScriptTokenizer::Token::BRACKET_OPEN: {
2510
// Array.
2511
push_multiline(true);
2512
advance();
2513
pattern->pattern_type = PatternNode::PT_ARRAY;
2514
do {
2515
if (is_at_end() || check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
2516
break;
2517
}
2518
PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
2519
if (sub_pattern == nullptr) {
2520
continue;
2521
}
2522
if (pattern->rest_used) {
2523
push_error(R"(The ".." pattern must be the last element in the pattern array.)");
2524
} else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
2525
pattern->rest_used = true;
2526
}
2527
pattern->array.push_back(sub_pattern);
2528
} while (match(GDScriptTokenizer::Token::COMMA));
2529
consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
2530
pop_multiline();
2531
break;
2532
}
2533
case GDScriptTokenizer::Token::BRACE_OPEN: {
2534
// Dictionary.
2535
push_multiline(true);
2536
advance();
2537
pattern->pattern_type = PatternNode::PT_DICTIONARY;
2538
do {
2539
if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
2540
break;
2541
}
2542
if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
2543
// Rest.
2544
if (pattern->rest_used) {
2545
push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
2546
} else {
2547
PatternNode *sub_pattern = alloc_node<PatternNode>();
2548
complete_extents(sub_pattern);
2549
sub_pattern->pattern_type = PatternNode::PT_REST;
2550
pattern->dictionary.push_back({ nullptr, sub_pattern });
2551
pattern->rest_used = true;
2552
}
2553
} else {
2554
ExpressionNode *key = parse_expression(false);
2555
if (key == nullptr) {
2556
push_error(R"(Expected expression as key for dictionary pattern.)");
2557
}
2558
if (match(GDScriptTokenizer::Token::COLON)) {
2559
// Value pattern.
2560
PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
2561
if (sub_pattern == nullptr) {
2562
continue;
2563
}
2564
if (pattern->rest_used) {
2565
push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
2566
} else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
2567
push_error(R"(The ".." pattern cannot be used as a value.)");
2568
} else {
2569
pattern->dictionary.push_back({ key, sub_pattern });
2570
}
2571
} else {
2572
// Key match only.
2573
pattern->dictionary.push_back({ key, nullptr });
2574
}
2575
}
2576
} while (match(GDScriptTokenizer::Token::COMMA));
2577
consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
2578
pop_multiline();
2579
break;
2580
}
2581
default: {
2582
// Expression.
2583
ExpressionNode *expression = parse_expression(false);
2584
if (expression == nullptr) {
2585
push_error(R"(Expected expression for match pattern.)");
2586
complete_extents(pattern);
2587
return nullptr;
2588
} else {
2589
if (expression->type == GDScriptParser::Node::LITERAL) {
2590
pattern->pattern_type = PatternNode::PT_LITERAL;
2591
} else {
2592
pattern->pattern_type = PatternNode::PT_EXPRESSION;
2593
}
2594
pattern->expression = expression;
2595
}
2596
break;
2597
}
2598
}
2599
complete_extents(pattern);
2600
2601
return pattern;
2602
}
2603
2604
bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
2605
return binds.has(p_name);
2606
}
2607
2608
GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
2609
return binds[p_name];
2610
}
2611
2612
GDScriptParser::WhileNode *GDScriptParser::parse_while() {
2613
WhileNode *n_while = alloc_node<WhileNode>();
2614
2615
n_while->condition = parse_expression(false);
2616
if (n_while->condition == nullptr) {
2617
push_error(R"(Expected conditional expression after "while".)");
2618
}
2619
2620
consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
2621
2622
// Save break/continue state.
2623
bool could_break = can_break;
2624
bool could_continue = can_continue;
2625
2626
// Allow break/continue.
2627
can_break = true;
2628
can_continue = true;
2629
2630
SuiteNode *suite = alloc_node<SuiteNode>();
2631
suite->is_in_loop = true;
2632
n_while->loop = parse_suite(R"("while" block)", suite);
2633
complete_extents(n_while);
2634
2635
// Reset break/continue state.
2636
can_break = could_break;
2637
can_continue = could_continue;
2638
2639
return n_while;
2640
}
2641
2642
GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
2643
// Switch multiline mode on for grouping tokens.
2644
// Do this early to avoid the tokenizer generating whitespace tokens.
2645
switch (current.type) {
2646
case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
2647
case GDScriptTokenizer::Token::BRACE_OPEN:
2648
case GDScriptTokenizer::Token::BRACKET_OPEN:
2649
push_multiline(true);
2650
break;
2651
default:
2652
break; // Nothing to do.
2653
}
2654
2655
// Completion can appear whenever an expression is expected.
2656
make_completion_context(COMPLETION_IDENTIFIER, nullptr, -1, false);
2657
2658
GDScriptTokenizer::Token token = current;
2659
GDScriptTokenizer::Token::Type token_type = token.type;
2660
if (token.is_identifier()) {
2661
// Allow keywords that can be treated as identifiers.
2662
token_type = GDScriptTokenizer::Token::IDENTIFIER;
2663
}
2664
ParseFunction prefix_rule = get_rule(token_type)->prefix;
2665
2666
if (prefix_rule == nullptr) {
2667
// Expected expression. Let the caller give the proper error message.
2668
return nullptr;
2669
}
2670
2671
advance(); // Only consume the token if there's a valid rule.
2672
2673
// After a token was consumed, update the completion context regardless of a previously set context.
2674
2675
ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
2676
2677
#ifdef TOOLS_ENABLED
2678
// HACK: We can't create a context in parse_identifier since it is used in places were we don't want completion.
2679
if (previous_operand != nullptr && previous_operand->type == GDScriptParser::Node::IDENTIFIER && prefix_rule == static_cast<ParseFunction>(&GDScriptParser::parse_identifier)) {
2680
make_completion_context(COMPLETION_IDENTIFIER, previous_operand);
2681
}
2682
#endif
2683
2684
while (p_precedence <= get_rule(current.type)->precedence) {
2685
if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || lambda_ended) {
2686
return previous_operand;
2687
}
2688
// Also switch multiline mode on here for infix operators.
2689
switch (current.type) {
2690
// case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
2691
case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
2692
case GDScriptTokenizer::Token::BRACKET_OPEN:
2693
push_multiline(true);
2694
break;
2695
default:
2696
break; // Nothing to do.
2697
}
2698
token = advance();
2699
ParseFunction infix_rule = get_rule(token.type)->infix;
2700
previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
2701
}
2702
2703
return previous_operand;
2704
}
2705
2706
GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
2707
return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
2708
}
2709
2710
GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
2711
IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
2712
#ifdef DEBUG_ENABLED
2713
// Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
2714
if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name)) {
2715
push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
2716
}
2717
#endif
2718
return identifier;
2719
}
2720
2721
GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
2722
if (!previous.is_identifier()) {
2723
ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
2724
}
2725
IdentifierNode *identifier = alloc_node<IdentifierNode>();
2726
complete_extents(identifier);
2727
identifier->name = previous.get_identifier();
2728
if (identifier->name.operator String().is_empty()) {
2729
print_line("Empty identifier found.");
2730
}
2731
identifier->suite = current_suite;
2732
2733
if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
2734
const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
2735
2736
identifier->source_function = declaration.source_function;
2737
switch (declaration.type) {
2738
case SuiteNode::Local::CONSTANT:
2739
identifier->source = IdentifierNode::LOCAL_CONSTANT;
2740
identifier->constant_source = declaration.constant;
2741
declaration.constant->usages++;
2742
break;
2743
case SuiteNode::Local::VARIABLE:
2744
identifier->source = IdentifierNode::LOCAL_VARIABLE;
2745
identifier->variable_source = declaration.variable;
2746
declaration.variable->usages++;
2747
break;
2748
case SuiteNode::Local::PARAMETER:
2749
identifier->source = IdentifierNode::FUNCTION_PARAMETER;
2750
identifier->parameter_source = declaration.parameter;
2751
declaration.parameter->usages++;
2752
break;
2753
case SuiteNode::Local::FOR_VARIABLE:
2754
identifier->source = IdentifierNode::LOCAL_ITERATOR;
2755
identifier->bind_source = declaration.bind;
2756
declaration.bind->usages++;
2757
break;
2758
case SuiteNode::Local::PATTERN_BIND:
2759
identifier->source = IdentifierNode::LOCAL_BIND;
2760
identifier->bind_source = declaration.bind;
2761
declaration.bind->usages++;
2762
break;
2763
case SuiteNode::Local::UNDEFINED:
2764
ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
2765
}
2766
}
2767
2768
return identifier;
2769
}
2770
2771
GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
2772
return static_cast<LiteralNode *>(parse_literal(nullptr, false));
2773
}
2774
2775
GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
2776
if (previous.type != GDScriptTokenizer::Token::LITERAL) {
2777
push_error("Parser bug: parsing literal node without literal token.");
2778
ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
2779
}
2780
2781
LiteralNode *literal = alloc_node<LiteralNode>();
2782
literal->value = previous.literal;
2783
reset_extents(literal, p_previous_operand);
2784
update_extents(literal);
2785
make_completion_context(COMPLETION_NONE, literal, -1);
2786
complete_extents(literal);
2787
return literal;
2788
}
2789
2790
GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
2791
if (current_function && current_function->is_static) {
2792
push_error(R"(Cannot use "self" inside a static function.)");
2793
}
2794
SelfNode *self = alloc_node<SelfNode>();
2795
complete_extents(self);
2796
self->current_class = current_class;
2797
return self;
2798
}
2799
2800
GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
2801
GDScriptTokenizer::Token::Type op_type = previous.type;
2802
LiteralNode *constant = alloc_node<LiteralNode>();
2803
complete_extents(constant);
2804
2805
switch (op_type) {
2806
case GDScriptTokenizer::Token::CONST_PI:
2807
constant->value = Math::PI;
2808
break;
2809
case GDScriptTokenizer::Token::CONST_TAU:
2810
constant->value = Math::TAU;
2811
break;
2812
case GDScriptTokenizer::Token::CONST_INF:
2813
constant->value = Math::INF;
2814
break;
2815
case GDScriptTokenizer::Token::CONST_NAN:
2816
constant->value = Math::NaN;
2817
break;
2818
default:
2819
return nullptr; // Unreachable.
2820
}
2821
2822
return constant;
2823
}
2824
2825
GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
2826
GDScriptTokenizer::Token::Type op_type = previous.type;
2827
UnaryOpNode *operation = alloc_node<UnaryOpNode>();
2828
2829
switch (op_type) {
2830
case GDScriptTokenizer::Token::MINUS:
2831
operation->operation = UnaryOpNode::OP_NEGATIVE;
2832
operation->variant_op = Variant::OP_NEGATE;
2833
operation->operand = parse_precedence(PREC_SIGN, false);
2834
if (operation->operand == nullptr) {
2835
push_error(R"(Expected expression after "-" operator.)");
2836
}
2837
break;
2838
case GDScriptTokenizer::Token::PLUS:
2839
operation->operation = UnaryOpNode::OP_POSITIVE;
2840
operation->variant_op = Variant::OP_POSITIVE;
2841
operation->operand = parse_precedence(PREC_SIGN, false);
2842
if (operation->operand == nullptr) {
2843
push_error(R"(Expected expression after "+" operator.)");
2844
}
2845
break;
2846
case GDScriptTokenizer::Token::TILDE:
2847
operation->operation = UnaryOpNode::OP_COMPLEMENT;
2848
operation->variant_op = Variant::OP_BIT_NEGATE;
2849
operation->operand = parse_precedence(PREC_BIT_NOT, false);
2850
if (operation->operand == nullptr) {
2851
push_error(R"(Expected expression after "~" operator.)");
2852
}
2853
break;
2854
case GDScriptTokenizer::Token::NOT:
2855
case GDScriptTokenizer::Token::BANG:
2856
operation->operation = UnaryOpNode::OP_LOGIC_NOT;
2857
operation->variant_op = Variant::OP_NOT;
2858
operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
2859
if (operation->operand == nullptr) {
2860
push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
2861
}
2862
break;
2863
default:
2864
complete_extents(operation);
2865
return nullptr; // Unreachable.
2866
}
2867
complete_extents(operation);
2868
2869
return operation;
2870
}
2871
2872
GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
2873
// check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
2874
UnaryOpNode *operation = alloc_node<UnaryOpNode>();
2875
reset_extents(operation, p_previous_operand);
2876
update_extents(operation);
2877
consume(GDScriptTokenizer::Token::TK_IN, R"(Expected "in" after "not" in content-test operator.)");
2878
ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
2879
operation->operation = UnaryOpNode::OP_LOGIC_NOT;
2880
operation->variant_op = Variant::OP_NOT;
2881
operation->operand = in_operation;
2882
complete_extents(operation);
2883
return operation;
2884
}
2885
2886
GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
2887
GDScriptTokenizer::Token op = previous;
2888
BinaryOpNode *operation = alloc_node<BinaryOpNode>();
2889
reset_extents(operation, p_previous_operand);
2890
update_extents(operation);
2891
2892
Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
2893
operation->left_operand = p_previous_operand;
2894
operation->right_operand = parse_precedence(precedence, false);
2895
complete_extents(operation);
2896
2897
if (operation->right_operand == nullptr) {
2898
push_error(vformat(R"(Expected expression after "%s" operator.)", op.get_name()));
2899
}
2900
2901
// TODO: Also for unary, ternary, and assignment.
2902
switch (op.type) {
2903
case GDScriptTokenizer::Token::PLUS:
2904
operation->operation = BinaryOpNode::OP_ADDITION;
2905
operation->variant_op = Variant::OP_ADD;
2906
break;
2907
case GDScriptTokenizer::Token::MINUS:
2908
operation->operation = BinaryOpNode::OP_SUBTRACTION;
2909
operation->variant_op = Variant::OP_SUBTRACT;
2910
break;
2911
case GDScriptTokenizer::Token::STAR:
2912
operation->operation = BinaryOpNode::OP_MULTIPLICATION;
2913
operation->variant_op = Variant::OP_MULTIPLY;
2914
break;
2915
case GDScriptTokenizer::Token::SLASH:
2916
operation->operation = BinaryOpNode::OP_DIVISION;
2917
operation->variant_op = Variant::OP_DIVIDE;
2918
break;
2919
case GDScriptTokenizer::Token::PERCENT:
2920
operation->operation = BinaryOpNode::OP_MODULO;
2921
operation->variant_op = Variant::OP_MODULE;
2922
break;
2923
case GDScriptTokenizer::Token::STAR_STAR:
2924
operation->operation = BinaryOpNode::OP_POWER;
2925
operation->variant_op = Variant::OP_POWER;
2926
break;
2927
case GDScriptTokenizer::Token::LESS_LESS:
2928
operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
2929
operation->variant_op = Variant::OP_SHIFT_LEFT;
2930
break;
2931
case GDScriptTokenizer::Token::GREATER_GREATER:
2932
operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
2933
operation->variant_op = Variant::OP_SHIFT_RIGHT;
2934
break;
2935
case GDScriptTokenizer::Token::AMPERSAND:
2936
operation->operation = BinaryOpNode::OP_BIT_AND;
2937
operation->variant_op = Variant::OP_BIT_AND;
2938
break;
2939
case GDScriptTokenizer::Token::PIPE:
2940
operation->operation = BinaryOpNode::OP_BIT_OR;
2941
operation->variant_op = Variant::OP_BIT_OR;
2942
break;
2943
case GDScriptTokenizer::Token::CARET:
2944
operation->operation = BinaryOpNode::OP_BIT_XOR;
2945
operation->variant_op = Variant::OP_BIT_XOR;
2946
break;
2947
case GDScriptTokenizer::Token::AND:
2948
case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
2949
operation->operation = BinaryOpNode::OP_LOGIC_AND;
2950
operation->variant_op = Variant::OP_AND;
2951
break;
2952
case GDScriptTokenizer::Token::OR:
2953
case GDScriptTokenizer::Token::PIPE_PIPE:
2954
operation->operation = BinaryOpNode::OP_LOGIC_OR;
2955
operation->variant_op = Variant::OP_OR;
2956
break;
2957
case GDScriptTokenizer::Token::TK_IN:
2958
operation->operation = BinaryOpNode::OP_CONTENT_TEST;
2959
operation->variant_op = Variant::OP_IN;
2960
break;
2961
case GDScriptTokenizer::Token::EQUAL_EQUAL:
2962
operation->operation = BinaryOpNode::OP_COMP_EQUAL;
2963
operation->variant_op = Variant::OP_EQUAL;
2964
break;
2965
case GDScriptTokenizer::Token::BANG_EQUAL:
2966
operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
2967
operation->variant_op = Variant::OP_NOT_EQUAL;
2968
break;
2969
case GDScriptTokenizer::Token::LESS:
2970
operation->operation = BinaryOpNode::OP_COMP_LESS;
2971
operation->variant_op = Variant::OP_LESS;
2972
break;
2973
case GDScriptTokenizer::Token::LESS_EQUAL:
2974
operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
2975
operation->variant_op = Variant::OP_LESS_EQUAL;
2976
break;
2977
case GDScriptTokenizer::Token::GREATER:
2978
operation->operation = BinaryOpNode::OP_COMP_GREATER;
2979
operation->variant_op = Variant::OP_GREATER;
2980
break;
2981
case GDScriptTokenizer::Token::GREATER_EQUAL:
2982
operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
2983
operation->variant_op = Variant::OP_GREATER_EQUAL;
2984
break;
2985
default:
2986
return nullptr; // Unreachable.
2987
}
2988
2989
return operation;
2990
}
2991
2992
GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
2993
// Only one ternary operation exists, so no abstraction here.
2994
TernaryOpNode *operation = alloc_node<TernaryOpNode>();
2995
reset_extents(operation, p_previous_operand);
2996
update_extents(operation);
2997
2998
operation->true_expr = p_previous_operand;
2999
operation->condition = parse_precedence(PREC_TERNARY, false);
3000
3001
if (operation->condition == nullptr) {
3002
push_error(R"(Expected expression as ternary condition after "if".)");
3003
}
3004
3005
consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
3006
3007
operation->false_expr = parse_precedence(PREC_TERNARY, false);
3008
3009
if (operation->false_expr == nullptr) {
3010
push_error(R"(Expected expression after "else".)");
3011
}
3012
3013
complete_extents(operation);
3014
return operation;
3015
}
3016
3017
GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
3018
if (!p_can_assign) {
3019
push_error("Assignment is not allowed inside an expression.");
3020
return parse_expression(false); // Return the following expression.
3021
}
3022
if (p_previous_operand == nullptr) {
3023
return parse_expression(false); // Return the following expression.
3024
}
3025
3026
switch (p_previous_operand->type) {
3027
case Node::IDENTIFIER: {
3028
#ifdef DEBUG_ENABLED
3029
// Get source to store assignment count.
3030
// Also remove one usage since assignment isn't usage.
3031
IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
3032
switch (id->source) {
3033
case IdentifierNode::LOCAL_VARIABLE:
3034
id->variable_source->usages--;
3035
break;
3036
case IdentifierNode::LOCAL_CONSTANT:
3037
id->constant_source->usages--;
3038
break;
3039
case IdentifierNode::FUNCTION_PARAMETER:
3040
id->parameter_source->usages--;
3041
break;
3042
case IdentifierNode::LOCAL_ITERATOR:
3043
case IdentifierNode::LOCAL_BIND:
3044
id->bind_source->usages--;
3045
break;
3046
default:
3047
break;
3048
}
3049
#endif
3050
} break;
3051
case Node::SUBSCRIPT:
3052
// Okay.
3053
break;
3054
default:
3055
push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
3056
return parse_expression(false); // Return the following expression.
3057
}
3058
3059
AssignmentNode *assignment = alloc_node<AssignmentNode>();
3060
reset_extents(assignment, p_previous_operand);
3061
update_extents(assignment);
3062
3063
make_completion_context(COMPLETION_ASSIGN, assignment);
3064
switch (previous.type) {
3065
case GDScriptTokenizer::Token::EQUAL:
3066
assignment->operation = AssignmentNode::OP_NONE;
3067
assignment->variant_op = Variant::OP_MAX;
3068
break;
3069
case GDScriptTokenizer::Token::PLUS_EQUAL:
3070
assignment->operation = AssignmentNode::OP_ADDITION;
3071
assignment->variant_op = Variant::OP_ADD;
3072
break;
3073
case GDScriptTokenizer::Token::MINUS_EQUAL:
3074
assignment->operation = AssignmentNode::OP_SUBTRACTION;
3075
assignment->variant_op = Variant::OP_SUBTRACT;
3076
break;
3077
case GDScriptTokenizer::Token::STAR_EQUAL:
3078
assignment->operation = AssignmentNode::OP_MULTIPLICATION;
3079
assignment->variant_op = Variant::OP_MULTIPLY;
3080
break;
3081
case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
3082
assignment->operation = AssignmentNode::OP_POWER;
3083
assignment->variant_op = Variant::OP_POWER;
3084
break;
3085
case GDScriptTokenizer::Token::SLASH_EQUAL:
3086
assignment->operation = AssignmentNode::OP_DIVISION;
3087
assignment->variant_op = Variant::OP_DIVIDE;
3088
break;
3089
case GDScriptTokenizer::Token::PERCENT_EQUAL:
3090
assignment->operation = AssignmentNode::OP_MODULO;
3091
assignment->variant_op = Variant::OP_MODULE;
3092
break;
3093
case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
3094
assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
3095
assignment->variant_op = Variant::OP_SHIFT_LEFT;
3096
break;
3097
case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
3098
assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
3099
assignment->variant_op = Variant::OP_SHIFT_RIGHT;
3100
break;
3101
case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
3102
assignment->operation = AssignmentNode::OP_BIT_AND;
3103
assignment->variant_op = Variant::OP_BIT_AND;
3104
break;
3105
case GDScriptTokenizer::Token::PIPE_EQUAL:
3106
assignment->operation = AssignmentNode::OP_BIT_OR;
3107
assignment->variant_op = Variant::OP_BIT_OR;
3108
break;
3109
case GDScriptTokenizer::Token::CARET_EQUAL:
3110
assignment->operation = AssignmentNode::OP_BIT_XOR;
3111
assignment->variant_op = Variant::OP_BIT_XOR;
3112
break;
3113
default:
3114
break; // Unreachable.
3115
}
3116
assignment->assignee = p_previous_operand;
3117
assignment->assigned_value = parse_expression(false);
3118
#ifdef TOOLS_ENABLED
3119
if (assignment->assigned_value != nullptr && assignment->assigned_value->type == GDScriptParser::Node::IDENTIFIER) {
3120
override_completion_context(assignment->assigned_value, COMPLETION_ASSIGN, assignment);
3121
}
3122
#endif
3123
if (assignment->assigned_value == nullptr) {
3124
push_error(R"(Expected an expression after "=".)");
3125
}
3126
complete_extents(assignment);
3127
3128
return assignment;
3129
}
3130
3131
GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
3132
AwaitNode *await = alloc_node<AwaitNode>();
3133
ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
3134
if (element == nullptr) {
3135
push_error(R"(Expected signal or coroutine after "await".)");
3136
}
3137
await->to_await = element;
3138
complete_extents(await);
3139
3140
if (current_function) { // Might be null in a getter or setter.
3141
current_function->is_coroutine = true;
3142
}
3143
3144
return await;
3145
}
3146
3147
GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
3148
ArrayNode *array = alloc_node<ArrayNode>();
3149
3150
if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
3151
do {
3152
if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
3153
// Allow for trailing comma.
3154
break;
3155
}
3156
3157
ExpressionNode *element = parse_expression(false);
3158
if (element == nullptr) {
3159
push_error(R"(Expected expression as array element.)");
3160
} else {
3161
array->elements.push_back(element);
3162
}
3163
} while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
3164
}
3165
pop_multiline();
3166
consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
3167
complete_extents(array);
3168
3169
return array;
3170
}
3171
3172
GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
3173
DictionaryNode *dictionary = alloc_node<DictionaryNode>();
3174
3175
bool decided_style = false;
3176
if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
3177
do {
3178
if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
3179
// Allow for trailing comma.
3180
break;
3181
}
3182
3183
// Key.
3184
ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
3185
3186
if (key == nullptr) {
3187
push_error(R"(Expected expression as dictionary key.)");
3188
}
3189
3190
if (!decided_style) {
3191
switch (current.type) {
3192
case GDScriptTokenizer::Token::COLON:
3193
dictionary->style = DictionaryNode::PYTHON_DICT;
3194
break;
3195
case GDScriptTokenizer::Token::EQUAL:
3196
dictionary->style = DictionaryNode::LUA_TABLE;
3197
break;
3198
default:
3199
push_error(R"(Expected ":" or "=" after dictionary key.)");
3200
break;
3201
}
3202
decided_style = true;
3203
}
3204
3205
switch (dictionary->style) {
3206
case DictionaryNode::LUA_TABLE:
3207
if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
3208
push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
3209
}
3210
if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
3211
push_error(R"(Expected identifier or string as Lua-style dictionary key (e.g "{ key = value }").)");
3212
}
3213
if (!match(GDScriptTokenizer::Token::EQUAL)) {
3214
if (match(GDScriptTokenizer::Token::COLON)) {
3215
push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
3216
advance(); // Consume wrong separator anyway.
3217
} else {
3218
push_error(R"(Expected "=" after dictionary key.)");
3219
}
3220
}
3221
if (key != nullptr) {
3222
key->is_constant = true;
3223
if (key->type == Node::IDENTIFIER) {
3224
key->reduced_value = static_cast<IdentifierNode *>(key)->name;
3225
} else if (key->type == Node::LITERAL) {
3226
key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
3227
}
3228
}
3229
break;
3230
case DictionaryNode::PYTHON_DICT:
3231
if (!match(GDScriptTokenizer::Token::COLON)) {
3232
if (match(GDScriptTokenizer::Token::EQUAL)) {
3233
push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
3234
advance(); // Consume wrong separator anyway.
3235
} else {
3236
push_error(R"(Expected ":" after dictionary key.)");
3237
}
3238
}
3239
break;
3240
}
3241
3242
// Value.
3243
ExpressionNode *value = parse_expression(false);
3244
if (value == nullptr) {
3245
push_error(R"(Expected expression as dictionary value.)");
3246
}
3247
3248
if (key != nullptr && value != nullptr) {
3249
dictionary->elements.push_back({ key, value });
3250
}
3251
3252
// Do phrase level recovery by inserting an imaginary expression for missing keys or values.
3253
// This ensures the successfully parsed expression is part of the AST and can be analyzed.
3254
if (key != nullptr && value == nullptr) {
3255
LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
3256
dummy->value = Variant();
3257
3258
dictionary->elements.push_back({ key, dummy });
3259
} else if (key == nullptr && value != nullptr) {
3260
LiteralNode *dummy = alloc_recovery_node<LiteralNode>();
3261
dummy->value = Variant();
3262
3263
dictionary->elements.push_back({ dummy, value });
3264
}
3265
3266
} while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
3267
}
3268
pop_multiline();
3269
consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
3270
complete_extents(dictionary);
3271
3272
return dictionary;
3273
}
3274
3275
GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
3276
ExpressionNode *grouped = parse_expression(false);
3277
pop_multiline();
3278
if (grouped == nullptr) {
3279
push_error(R"(Expected grouping expression.)");
3280
} else {
3281
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
3282
}
3283
return grouped;
3284
}
3285
3286
GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
3287
SubscriptNode *attribute = alloc_node<SubscriptNode>();
3288
reset_extents(attribute, p_previous_operand);
3289
update_extents(attribute);
3290
3291
if (for_completion) {
3292
bool is_builtin = false;
3293
if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
3294
const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
3295
Variant::Type builtin_type = get_builtin_type(id->name);
3296
if (builtin_type < Variant::VARIANT_MAX) {
3297
make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type);
3298
is_builtin = true;
3299
}
3300
}
3301
if (!is_builtin) {
3302
make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1);
3303
}
3304
}
3305
3306
attribute->base = p_previous_operand;
3307
3308
if (current.is_node_name()) {
3309
current.type = GDScriptTokenizer::Token::IDENTIFIER;
3310
}
3311
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
3312
complete_extents(attribute);
3313
return attribute;
3314
}
3315
3316
attribute->is_attribute = true;
3317
attribute->attribute = parse_identifier();
3318
3319
complete_extents(attribute);
3320
return attribute;
3321
}
3322
3323
GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
3324
SubscriptNode *subscript = alloc_node<SubscriptNode>();
3325
reset_extents(subscript, p_previous_operand);
3326
update_extents(subscript);
3327
3328
make_completion_context(COMPLETION_SUBSCRIPT, subscript);
3329
3330
subscript->base = p_previous_operand;
3331
subscript->index = parse_expression(false);
3332
3333
#ifdef TOOLS_ENABLED
3334
if (subscript->index != nullptr && subscript->index->type == Node::LITERAL) {
3335
override_completion_context(subscript->index, COMPLETION_SUBSCRIPT, subscript);
3336
}
3337
#endif
3338
3339
if (subscript->index == nullptr) {
3340
push_error(R"(Expected expression after "[".)");
3341
}
3342
3343
pop_multiline();
3344
consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
3345
complete_extents(subscript);
3346
3347
return subscript;
3348
}
3349
3350
GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
3351
CastNode *cast = alloc_node<CastNode>();
3352
reset_extents(cast, p_previous_operand);
3353
update_extents(cast);
3354
3355
cast->operand = p_previous_operand;
3356
cast->cast_type = parse_type();
3357
complete_extents(cast);
3358
3359
if (cast->cast_type == nullptr) {
3360
push_error(R"(Expected type specifier after "as".)");
3361
return p_previous_operand;
3362
}
3363
3364
return cast;
3365
}
3366
3367
GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
3368
CallNode *call = alloc_node<CallNode>();
3369
reset_extents(call, p_previous_operand);
3370
3371
if (previous.type == GDScriptTokenizer::Token::SUPER) {
3372
// Super call.
3373
call->is_super = true;
3374
if (!check(GDScriptTokenizer::Token::PERIOD)) {
3375
make_completion_context(COMPLETION_SUPER, call);
3376
}
3377
push_multiline(true);
3378
if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
3379
// Implicit call to the parent method of the same name.
3380
if (current_function == nullptr) {
3381
push_error(R"(Cannot use implicit "super" call outside of a function.)");
3382
pop_multiline();
3383
complete_extents(call);
3384
return nullptr;
3385
}
3386
if (current_function->identifier) {
3387
call->function_name = current_function->identifier->name;
3388
} else {
3389
call->function_name = SNAME("<anonymous>");
3390
}
3391
} else {
3392
consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
3393
make_completion_context(COMPLETION_SUPER_METHOD, call);
3394
if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
3395
pop_multiline();
3396
complete_extents(call);
3397
return nullptr;
3398
}
3399
IdentifierNode *identifier = parse_identifier();
3400
call->callee = identifier;
3401
call->function_name = identifier->name;
3402
if (!consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)")) {
3403
pop_multiline();
3404
complete_extents(call);
3405
return nullptr;
3406
}
3407
}
3408
} else {
3409
call->callee = p_previous_operand;
3410
3411
if (call->callee == nullptr) {
3412
push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
3413
} else if (call->callee->type == Node::IDENTIFIER) {
3414
call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
3415
make_completion_context(COMPLETION_METHOD, call->callee);
3416
} else if (call->callee->type == Node::SUBSCRIPT) {
3417
SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
3418
if (attribute->is_attribute) {
3419
if (attribute->attribute) {
3420
call->function_name = attribute->attribute->name;
3421
}
3422
make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
3423
} else {
3424
// TODO: The analyzer can see if this is actually a Callable and give better error message.
3425
push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
3426
}
3427
} else {
3428
push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
3429
}
3430
}
3431
3432
// Arguments.
3433
CompletionType ct = COMPLETION_CALL_ARGUMENTS;
3434
if (call->function_name == SNAME("load")) {
3435
ct = COMPLETION_RESOURCE_PATH;
3436
}
3437
push_completion_call(call);
3438
int argument_index = 0;
3439
do {
3440
make_completion_context(ct, call, argument_index);
3441
set_last_completion_call_arg(argument_index);
3442
if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
3443
// Allow for trailing comma.
3444
break;
3445
}
3446
ExpressionNode *argument = parse_expression(false);
3447
if (argument == nullptr) {
3448
push_error(R"(Expected expression as the function argument.)");
3449
} else {
3450
call->arguments.push_back(argument);
3451
3452
if (argument->type == Node::LITERAL) {
3453
override_completion_context(argument, ct, call, argument_index);
3454
}
3455
}
3456
3457
ct = COMPLETION_CALL_ARGUMENTS;
3458
argument_index++;
3459
} while (match(GDScriptTokenizer::Token::COMMA));
3460
pop_completion_call();
3461
3462
pop_multiline();
3463
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
3464
complete_extents(call);
3465
3466
return call;
3467
}
3468
3469
GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
3470
// We want code completion after a DOLLAR even if the current code is invalid.
3471
make_completion_context(COMPLETION_GET_NODE, nullptr, -1);
3472
3473
if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
3474
push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
3475
return nullptr;
3476
}
3477
3478
if (check(GDScriptTokenizer::Token::LITERAL)) {
3479
if (current.literal.get_type() != Variant::STRING) {
3480
push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
3481
return nullptr;
3482
}
3483
}
3484
3485
GetNodeNode *get_node = alloc_node<GetNodeNode>();
3486
3487
// Store the last item in the path so the parser knows what to expect.
3488
// Allow allows more specific error messages.
3489
enum PathState {
3490
PATH_STATE_START,
3491
PATH_STATE_SLASH,
3492
PATH_STATE_PERCENT,
3493
PATH_STATE_NODE_NAME,
3494
} path_state = PATH_STATE_START;
3495
3496
if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
3497
// Detect initial slash, which will be handled in the loop if it matches.
3498
match(GDScriptTokenizer::Token::SLASH);
3499
} else {
3500
get_node->use_dollar = false;
3501
}
3502
3503
int context_argument = 0;
3504
3505
do {
3506
if (previous.type == GDScriptTokenizer::Token::PERCENT) {
3507
if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
3508
push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
3509
complete_extents(get_node);
3510
return nullptr;
3511
}
3512
3513
get_node->full_path += "%";
3514
3515
path_state = PATH_STATE_PERCENT;
3516
} else if (previous.type == GDScriptTokenizer::Token::SLASH) {
3517
if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
3518
push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
3519
complete_extents(get_node);
3520
return nullptr;
3521
}
3522
3523
get_node->full_path += "/";
3524
3525
path_state = PATH_STATE_SLASH;
3526
}
3527
3528
make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
3529
3530
if (match(GDScriptTokenizer::Token::LITERAL)) {
3531
if (previous.literal.get_type() != Variant::STRING) {
3532
String previous_token;
3533
switch (path_state) {
3534
case PATH_STATE_START:
3535
previous_token = "$";
3536
break;
3537
case PATH_STATE_PERCENT:
3538
previous_token = "%";
3539
break;
3540
case PATH_STATE_SLASH:
3541
previous_token = "/";
3542
break;
3543
default:
3544
break;
3545
}
3546
push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
3547
complete_extents(get_node);
3548
return nullptr;
3549
}
3550
3551
get_node->full_path += previous.literal.operator String();
3552
3553
path_state = PATH_STATE_NODE_NAME;
3554
} else if (current.is_node_name()) {
3555
advance();
3556
3557
String identifier = previous.get_identifier();
3558
#ifdef DEBUG_ENABLED
3559
// Check spoofing.
3560
if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
3561
push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
3562
}
3563
#endif
3564
get_node->full_path += identifier;
3565
3566
path_state = PATH_STATE_NODE_NAME;
3567
} else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
3568
push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
3569
complete_extents(get_node);
3570
return nullptr;
3571
}
3572
} while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
3573
3574
complete_extents(get_node);
3575
return get_node;
3576
}
3577
3578
GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
3579
PreloadNode *preload = alloc_node<PreloadNode>();
3580
preload->resolved_path = "<missing path>";
3581
3582
push_multiline(true);
3583
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
3584
3585
make_completion_context(COMPLETION_RESOURCE_PATH, preload);
3586
push_completion_call(preload);
3587
3588
preload->path = parse_expression(false);
3589
3590
if (preload->path == nullptr) {
3591
push_error(R"(Expected resource path after "(".)");
3592
} else if (preload->path->type == Node::LITERAL) {
3593
override_completion_context(preload->path, COMPLETION_RESOURCE_PATH, preload);
3594
}
3595
3596
pop_completion_call();
3597
3598
pop_multiline();
3599
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
3600
complete_extents(preload);
3601
3602
return preload;
3603
}
3604
3605
GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
3606
LambdaNode *lambda = alloc_node<LambdaNode>();
3607
lambda->parent_function = current_function;
3608
lambda->parent_lambda = current_lambda;
3609
3610
FunctionNode *function = alloc_node<FunctionNode>();
3611
function->source_lambda = lambda;
3612
3613
function->is_static = current_function != nullptr ? current_function->is_static : false;
3614
3615
if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
3616
function->identifier = parse_identifier();
3617
}
3618
3619
bool multiline_context = multiline_stack.back()->get();
3620
3621
push_completion_call(nullptr);
3622
3623
// Reset the multiline stack since we don't want the multiline mode one in the lambda body.
3624
push_multiline(false);
3625
if (multiline_context) {
3626
tokenizer->push_expression_indented_block();
3627
}
3628
3629
push_multiline(true); // For the parameters.
3630
if (function->identifier) {
3631
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
3632
} else {
3633
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
3634
}
3635
3636
FunctionNode *previous_function = current_function;
3637
current_function = function;
3638
3639
LambdaNode *previous_lambda = current_lambda;
3640
current_lambda = lambda;
3641
3642
SuiteNode *body = alloc_node<SuiteNode>();
3643
body->parent_function = current_function;
3644
body->parent_block = current_suite;
3645
3646
SuiteNode *previous_suite = current_suite;
3647
current_suite = body;
3648
3649
parse_function_signature(function, body, "lambda", -1);
3650
3651
current_suite = previous_suite;
3652
3653
bool previous_in_lambda = in_lambda;
3654
in_lambda = true;
3655
3656
// Save break/continue state.
3657
bool could_break = can_break;
3658
bool could_continue = can_continue;
3659
3660
// Disallow break/continue.
3661
can_break = false;
3662
can_continue = false;
3663
3664
function->body = parse_suite("lambda declaration", body, true);
3665
complete_extents(function);
3666
complete_extents(lambda);
3667
3668
pop_multiline();
3669
3670
pop_completion_call();
3671
3672
if (multiline_context) {
3673
// If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
3674
while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
3675
current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
3676
}
3677
tokenizer->pop_expression_indented_block();
3678
}
3679
3680
current_function = previous_function;
3681
current_lambda = previous_lambda;
3682
in_lambda = previous_in_lambda;
3683
lambda->function = function;
3684
3685
// Reset break/continue state.
3686
can_break = could_break;
3687
can_continue = could_continue;
3688
3689
return lambda;
3690
}
3691
3692
GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
3693
// x is not int
3694
// ^ ^^^ ExpressionNode, TypeNode
3695
// ^^^^^^^^^^^^ TypeTestNode
3696
// ^^^^^^^^^^^^ UnaryOpNode
3697
UnaryOpNode *not_node = nullptr;
3698
if (match(GDScriptTokenizer::Token::NOT)) {
3699
not_node = alloc_node<UnaryOpNode>();
3700
not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
3701
not_node->variant_op = Variant::OP_NOT;
3702
reset_extents(not_node, p_previous_operand);
3703
update_extents(not_node);
3704
}
3705
3706
TypeTestNode *type_test = alloc_node<TypeTestNode>();
3707
reset_extents(type_test, p_previous_operand);
3708
update_extents(type_test);
3709
3710
type_test->operand = p_previous_operand;
3711
type_test->test_type = parse_type();
3712
complete_extents(type_test);
3713
3714
if (not_node != nullptr) {
3715
not_node->operand = type_test;
3716
complete_extents(not_node);
3717
}
3718
3719
if (type_test->test_type == nullptr) {
3720
if (not_node == nullptr) {
3721
push_error(R"(Expected type specifier after "is".)");
3722
} else {
3723
push_error(R"(Expected type specifier after "is not".)");
3724
}
3725
}
3726
3727
if (not_node != nullptr) {
3728
return not_node;
3729
}
3730
3731
return type_test;
3732
}
3733
3734
GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
3735
push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
3736
return nullptr;
3737
}
3738
3739
GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
3740
// Just for better error messages.
3741
GDScriptTokenizer::Token::Type invalid = previous.type;
3742
3743
switch (invalid) {
3744
case GDScriptTokenizer::Token::QUESTION_MARK:
3745
push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
3746
break;
3747
default:
3748
return nullptr; // Unreachable.
3749
}
3750
3751
// Return the previous expression.
3752
return p_previous_operand;
3753
}
3754
3755
GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
3756
TypeNode *type = alloc_node<TypeNode>();
3757
make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
3758
if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
3759
if (match(GDScriptTokenizer::Token::TK_VOID)) {
3760
if (p_allow_void) {
3761
complete_extents(type);
3762
TypeNode *void_type = type;
3763
return void_type;
3764
} else {
3765
push_error(R"("void" is only allowed for a function return type.)");
3766
}
3767
}
3768
// Leave error message to the caller who knows the context.
3769
complete_extents(type);
3770
return nullptr;
3771
}
3772
3773
IdentifierNode *type_element = parse_identifier();
3774
3775
type->type_chain.push_back(type_element);
3776
3777
if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
3778
// Typed collection (like Array[int], Dictionary[String, int]).
3779
bool first_pass = true;
3780
do {
3781
TypeNode *container_type = parse_type(false); // Don't allow void for element type.
3782
if (container_type == nullptr) {
3783
push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
3784
complete_extents(type);
3785
type = nullptr;
3786
break;
3787
} else if (container_type->container_types.size() > 0) {
3788
push_error("Nested typed collections are not supported.");
3789
} else {
3790
type->container_types.append(container_type);
3791
}
3792
first_pass = false;
3793
} while (match(GDScriptTokenizer::Token::COMMA));
3794
consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
3795
if (type != nullptr) {
3796
complete_extents(type);
3797
}
3798
return type;
3799
}
3800
3801
int chain_index = 1;
3802
while (match(GDScriptTokenizer::Token::PERIOD)) {
3803
make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
3804
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
3805
type_element = parse_identifier();
3806
type->type_chain.push_back(type_element);
3807
}
3808
}
3809
3810
complete_extents(type);
3811
return type;
3812
}
3813
3814
#ifdef TOOLS_ENABLED
3815
enum DocLineState {
3816
DOC_LINE_NORMAL,
3817
DOC_LINE_IN_CODE,
3818
DOC_LINE_IN_CODEBLOCK,
3819
DOC_LINE_IN_KBD,
3820
};
3821
3822
static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
3823
String line = p_line;
3824
if (r_state == DOC_LINE_NORMAL) {
3825
line = line.strip_edges(true, false);
3826
} else {
3827
line = line.trim_prefix(p_space_prefix);
3828
}
3829
3830
String line_join;
3831
if (!p_text.is_empty()) {
3832
if (r_state == DOC_LINE_NORMAL) {
3833
if (p_text.ends_with("[/codeblock]")) {
3834
line_join = "\n";
3835
} else if (!p_text.ends_with("[br]")) {
3836
line_join = " ";
3837
}
3838
} else {
3839
line_join = "\n";
3840
}
3841
}
3842
3843
String result;
3844
int from = 0;
3845
int buffer_start = 0;
3846
const int len = line.length();
3847
bool process = true;
3848
while (process) {
3849
switch (r_state) {
3850
case DOC_LINE_NORMAL: {
3851
int lb_pos = line.find_char('[', from);
3852
if (lb_pos < 0) {
3853
process = false;
3854
break;
3855
}
3856
int rb_pos = line.find_char(']', lb_pos + 1);
3857
if (rb_pos < 0) {
3858
process = false;
3859
break;
3860
}
3861
3862
from = rb_pos + 1;
3863
3864
String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
3865
if (tag == "code" || tag.begins_with("code ")) {
3866
r_state = DOC_LINE_IN_CODE;
3867
} else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
3868
if (lb_pos == 0) {
3869
line_join = "\n";
3870
} else {
3871
result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
3872
}
3873
result += "[" + tag + "]";
3874
if (from < len) {
3875
result += '\n';
3876
}
3877
3878
r_state = DOC_LINE_IN_CODEBLOCK;
3879
buffer_start = from;
3880
} else if (tag == "kbd") {
3881
r_state = DOC_LINE_IN_KBD;
3882
}
3883
} break;
3884
case DOC_LINE_IN_CODE: {
3885
int pos = line.find("[/code]", from);
3886
if (pos < 0) {
3887
process = false;
3888
break;
3889
}
3890
3891
from = pos + 7; // `len("[/code]")`.
3892
3893
r_state = DOC_LINE_NORMAL;
3894
} break;
3895
case DOC_LINE_IN_CODEBLOCK: {
3896
int pos = line.find("[/codeblock]", from);
3897
if (pos < 0) {
3898
process = false;
3899
break;
3900
}
3901
3902
from = pos + 12; // `len("[/codeblock]")`.
3903
3904
if (pos == 0) {
3905
line_join = "\n";
3906
} else {
3907
result += line.substr(buffer_start, pos - buffer_start) + '\n';
3908
}
3909
result += "[/codeblock]";
3910
if (from < len) {
3911
result += '\n';
3912
}
3913
3914
r_state = DOC_LINE_NORMAL;
3915
buffer_start = from;
3916
} break;
3917
case DOC_LINE_IN_KBD: {
3918
int pos = line.find("[/kbd]", from);
3919
if (pos < 0) {
3920
process = false;
3921
break;
3922
}
3923
3924
from = pos + 6; // `len("[/kbd]")`.
3925
3926
r_state = DOC_LINE_NORMAL;
3927
} break;
3928
}
3929
}
3930
3931
result += line.substr(buffer_start);
3932
if (r_state == DOC_LINE_NORMAL) {
3933
result = result.strip_edges(false, true);
3934
}
3935
3936
return line_join + result;
3937
}
3938
3939
bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
3940
bool has_comment = tokenizer->get_comments().has(p_line);
3941
// If there are no comments or if we don't care whether the comment
3942
// is a docstring, we have our result.
3943
if (!p_must_be_doc || !has_comment) {
3944
return has_comment;
3945
}
3946
3947
return tokenizer->get_comments()[p_line].comment.begins_with("##");
3948
}
3949
3950
GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
3951
ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
3952
3953
const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
3954
int line = p_line;
3955
3956
if (!p_single_line) {
3957
while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
3958
line--;
3959
}
3960
}
3961
3962
max_script_doc_line = MIN(max_script_doc_line, line - 1);
3963
3964
String space_prefix;
3965
{
3966
int i = 2;
3967
for (; i < comments[line].comment.length(); i++) {
3968
if (comments[line].comment[i] != ' ') {
3969
break;
3970
}
3971
}
3972
space_prefix = String(" ").repeat(i - 2);
3973
}
3974
3975
DocLineState state = DOC_LINE_NORMAL;
3976
MemberDocData result;
3977
3978
while (line <= p_line) {
3979
String doc_line = comments[line].comment.trim_prefix("##");
3980
line++;
3981
3982
if (state == DOC_LINE_NORMAL) {
3983
String stripped_line = doc_line.strip_edges();
3984
if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
3985
result.is_deprecated = true;
3986
if (stripped_line.begins_with("@deprecated:")) {
3987
result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
3988
}
3989
continue;
3990
} else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
3991
result.is_experimental = true;
3992
if (stripped_line.begins_with("@experimental:")) {
3993
result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
3994
}
3995
continue;
3996
}
3997
}
3998
3999
result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
4000
}
4001
4002
return result;
4003
}
4004
4005
GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
4006
ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
4007
4008
const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
4009
int line = p_line;
4010
4011
if (!p_single_line) {
4012
while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
4013
line--;
4014
}
4015
}
4016
4017
max_script_doc_line = MIN(max_script_doc_line, line - 1);
4018
4019
String space_prefix;
4020
{
4021
int i = 2;
4022
for (; i < comments[line].comment.length(); i++) {
4023
if (comments[line].comment[i] != ' ') {
4024
break;
4025
}
4026
}
4027
space_prefix = String(" ").repeat(i - 2);
4028
}
4029
4030
DocLineState state = DOC_LINE_NORMAL;
4031
bool is_in_brief = true;
4032
ClassDocData result;
4033
4034
while (line <= p_line) {
4035
String doc_line = comments[line].comment.trim_prefix("##");
4036
line++;
4037
4038
if (state == DOC_LINE_NORMAL) {
4039
String stripped_line = doc_line.strip_edges();
4040
4041
// A blank line separates the description from the brief.
4042
if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
4043
is_in_brief = false;
4044
continue;
4045
}
4046
4047
if (stripped_line.begins_with("@tutorial")) {
4048
String title, link;
4049
4050
int begin_scan = String("@tutorial").length();
4051
if (begin_scan >= stripped_line.length()) {
4052
continue; // Invalid syntax.
4053
}
4054
4055
if (stripped_line[begin_scan] == ':') { // No title.
4056
// Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
4057
title = "";
4058
link = stripped_line.trim_prefix("@tutorial:").strip_edges();
4059
} else {
4060
/* Syntax:
4061
* @tutorial ( The Title Here ) : https://the.url/
4062
* ^ open ^ close ^ colon ^ url
4063
*/
4064
int open_bracket_pos = begin_scan, close_bracket_pos = 0;
4065
while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
4066
open_bracket_pos++;
4067
}
4068
if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
4069
continue; // Invalid syntax.
4070
}
4071
close_bracket_pos = open_bracket_pos;
4072
while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
4073
close_bracket_pos++;
4074
}
4075
if (close_bracket_pos == stripped_line.length()) {
4076
continue; // Invalid syntax.
4077
}
4078
4079
int colon_pos = close_bracket_pos + 1;
4080
while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
4081
colon_pos++;
4082
}
4083
if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
4084
continue; // Invalid syntax.
4085
}
4086
4087
title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
4088
link = stripped_line.substr(colon_pos).strip_edges();
4089
}
4090
4091
result.tutorials.append(Pair<String, String>(title, link));
4092
continue;
4093
} else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
4094
result.is_deprecated = true;
4095
if (stripped_line.begins_with("@deprecated:")) {
4096
result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
4097
}
4098
continue;
4099
} else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
4100
result.is_experimental = true;
4101
if (stripped_line.begins_with("@experimental:")) {
4102
result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
4103
}
4104
continue;
4105
}
4106
}
4107
4108
if (is_in_brief) {
4109
result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
4110
} else {
4111
result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
4112
}
4113
}
4114
4115
return result;
4116
}
4117
#endif // TOOLS_ENABLED
4118
4119
GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
4120
// Function table for expression parsing.
4121
// clang-format destroys the alignment here, so turn off for the table.
4122
/* clang-format off */
4123
static ParseRule rules[] = {
4124
// PREFIX INFIX PRECEDENCE (for infix)
4125
{ nullptr, nullptr, PREC_NONE }, // EMPTY,
4126
// Basic
4127
{ nullptr, nullptr, PREC_NONE }, // ANNOTATION,
4128
{ &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
4129
{ &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
4130
// Comparison
4131
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
4132
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
4133
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
4134
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
4135
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
4136
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
4137
// Logical
4138
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
4139
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
4140
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
4141
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
4142
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
4143
{ &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
4144
// Bitwise
4145
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
4146
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
4147
{ &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
4148
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
4149
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
4150
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
4151
// Math
4152
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
4153
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
4154
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
4155
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
4156
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
4157
{ &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
4158
// Assignment
4159
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
4160
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
4161
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
4162
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
4163
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
4164
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
4165
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
4166
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
4167
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
4168
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
4169
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
4170
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
4171
// Control flow
4172
{ nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
4173
{ nullptr, nullptr, PREC_NONE }, // ELIF,
4174
{ nullptr, nullptr, PREC_NONE }, // ELSE,
4175
{ nullptr, nullptr, PREC_NONE }, // FOR,
4176
{ nullptr, nullptr, PREC_NONE }, // WHILE,
4177
{ nullptr, nullptr, PREC_NONE }, // BREAK,
4178
{ nullptr, nullptr, PREC_NONE }, // CONTINUE,
4179
{ nullptr, nullptr, PREC_NONE }, // PASS,
4180
{ nullptr, nullptr, PREC_NONE }, // RETURN,
4181
{ nullptr, nullptr, PREC_NONE }, // MATCH,
4182
{ nullptr, nullptr, PREC_NONE }, // WHEN,
4183
// Keywords
4184
{ nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
4185
{ nullptr, nullptr, PREC_NONE }, // ASSERT,
4186
{ &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
4187
{ nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
4188
{ nullptr, nullptr, PREC_NONE }, // CLASS,
4189
{ nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
4190
{ nullptr, nullptr, PREC_NONE }, // TK_CONST,
4191
{ nullptr, nullptr, PREC_NONE }, // ENUM,
4192
{ nullptr, nullptr, PREC_NONE }, // EXTENDS,
4193
{ &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
4194
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // TK_IN,
4195
{ nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
4196
{ nullptr, nullptr, PREC_NONE }, // NAMESPACE,
4197
{ &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
4198
{ &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
4199
{ nullptr, nullptr, PREC_NONE }, // SIGNAL,
4200
{ nullptr, nullptr, PREC_NONE }, // STATIC,
4201
{ &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
4202
{ nullptr, nullptr, PREC_NONE }, // TRAIT,
4203
{ nullptr, nullptr, PREC_NONE }, // VAR,
4204
{ nullptr, nullptr, PREC_NONE }, // TK_VOID,
4205
{ &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
4206
// Punctuation
4207
{ &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
4208
{ nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
4209
{ &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
4210
{ nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
4211
{ &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
4212
{ nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
4213
{ nullptr, nullptr, PREC_NONE }, // COMMA,
4214
{ nullptr, nullptr, PREC_NONE }, // SEMICOLON,
4215
{ nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
4216
{ nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
4217
{ nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD_PERIOD,
4218
{ nullptr, nullptr, PREC_NONE }, // COLON,
4219
{ &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
4220
{ nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
4221
{ nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
4222
// Whitespace
4223
{ nullptr, nullptr, PREC_NONE }, // NEWLINE,
4224
{ nullptr, nullptr, PREC_NONE }, // INDENT,
4225
{ nullptr, nullptr, PREC_NONE }, // DEDENT,
4226
// Constants
4227
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
4228
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
4229
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
4230
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
4231
// Error message improvement
4232
{ nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
4233
{ nullptr, nullptr, PREC_NONE }, // BACKTICK,
4234
{ nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
4235
// Special
4236
{ nullptr, nullptr, PREC_NONE }, // ERROR,
4237
{ nullptr, nullptr, PREC_NONE }, // TK_EOF,
4238
};
4239
/* clang-format on */
4240
// Avoid desync.
4241
static_assert(std::size(rules) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
4242
4243
// Let's assume this is never invalid, since nothing generates a TK_MAX.
4244
return &rules[p_token_type];
4245
}
4246
4247
bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
4248
if (locals_indices.has(p_name)) {
4249
return true;
4250
}
4251
if (parent_block != nullptr) {
4252
return parent_block->has_local(p_name);
4253
}
4254
return false;
4255
}
4256
4257
const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
4258
if (locals_indices.has(p_name)) {
4259
return locals[locals_indices[p_name]];
4260
}
4261
if (parent_block != nullptr) {
4262
return parent_block->get_local(p_name);
4263
}
4264
return empty;
4265
}
4266
4267
bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
4268
if (is_applied) {
4269
return true;
4270
}
4271
is_applied = true;
4272
return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
4273
}
4274
4275
bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
4276
return (info->target_kind & p_target_kinds) > 0;
4277
}
4278
4279
bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
4280
ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
4281
4282
const MethodInfo &info = valid_annotations[p_annotation->name].info;
4283
4284
if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
4285
push_error(vformat(R"(Annotation "%s" requires at most %d arguments, but %d were given.)", p_annotation->name, info.arguments.size(), p_annotation->arguments.size()));
4286
return false;
4287
}
4288
4289
if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
4290
push_error(vformat(R"(Annotation "%s" requires at least %d arguments, but %d were given.)", p_annotation->name, info.arguments.size() - info.default_arguments.size(), p_annotation->arguments.size()));
4291
return false;
4292
}
4293
4294
// Some annotations need to be resolved and applied in the parser.
4295
if (p_annotation->name == SNAME("@icon") || p_annotation->name == SNAME("@warning_ignore_start") || p_annotation->name == SNAME("@warning_ignore_restore")) {
4296
for (int i = 0; i < p_annotation->arguments.size(); i++) {
4297
ExpressionNode *argument = p_annotation->arguments[i];
4298
4299
if (argument->type != Node::LITERAL) {
4300
push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
4301
return false;
4302
}
4303
4304
Variant value = static_cast<LiteralNode *>(argument)->value;
4305
4306
if (value.get_type() != Variant::STRING) {
4307
push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
4308
return false;
4309
}
4310
4311
p_annotation->resolved_arguments.push_back(value);
4312
}
4313
}
4314
4315
// For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
4316
4317
return true;
4318
}
4319
4320
bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4321
#ifdef DEBUG_ENABLED
4322
if (_is_tool) {
4323
push_error(R"("@tool" annotation can only be used once.)", p_annotation);
4324
return false;
4325
}
4326
#endif // DEBUG_ENABLED
4327
_is_tool = true;
4328
return true;
4329
}
4330
4331
bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4332
ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
4333
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4334
4335
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4336
String path = p_annotation->resolved_arguments[0];
4337
4338
#ifdef DEBUG_ENABLED
4339
if (!class_node->icon_path.is_empty()) {
4340
push_error(R"("@icon" annotation can only be used once.)", p_annotation);
4341
return false;
4342
}
4343
if (path.is_empty()) {
4344
push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
4345
return false;
4346
}
4347
#endif // DEBUG_ENABLED
4348
4349
class_node->icon_path = path;
4350
4351
if (path.is_empty() || path.is_absolute_path()) {
4352
class_node->simplified_icon_path = path.simplify_path();
4353
} else if (path.is_relative_path()) {
4354
class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
4355
} else {
4356
class_node->simplified_icon_path = path;
4357
}
4358
4359
return true;
4360
}
4361
4362
bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4363
ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
4364
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4365
if (class_node->annotated_static_unload) {
4366
push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
4367
return false;
4368
}
4369
class_node->annotated_static_unload = true;
4370
return true;
4371
}
4372
4373
bool GDScriptParser::abstract_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4374
// NOTE: Use `p_target`, **not** `p_class`, because when `p_target` is a class then `p_class` refers to the outer class.
4375
if (p_target->type == Node::CLASS) {
4376
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4377
if (class_node->is_abstract) {
4378
push_error(R"("@abstract" annotation can only be used once per class.)", p_annotation);
4379
return false;
4380
}
4381
class_node->is_abstract = true;
4382
return true;
4383
}
4384
if (p_target->type == Node::FUNCTION) {
4385
FunctionNode *function_node = static_cast<FunctionNode *>(p_target);
4386
if (function_node->is_static) {
4387
push_error(R"("@abstract" annotation cannot be applied to static functions.)", p_annotation);
4388
return false;
4389
}
4390
if (function_node->is_abstract) {
4391
push_error(R"("@abstract" annotation can only be used once per function.)", p_annotation);
4392
return false;
4393
}
4394
function_node->is_abstract = true;
4395
return true;
4396
}
4397
ERR_FAIL_V_MSG(false, R"("@abstract" annotation can only be applied to classes and functions.)");
4398
}
4399
4400
bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4401
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
4402
4403
if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
4404
push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
4405
return false;
4406
}
4407
4408
VariableNode *variable = static_cast<VariableNode *>(p_target);
4409
if (variable->is_static) {
4410
push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
4411
return false;
4412
}
4413
if (variable->onready) {
4414
push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
4415
return false;
4416
}
4417
variable->onready = true;
4418
current_class->onready_used = true;
4419
return true;
4420
}
4421
4422
static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
4423
Vector<String> types;
4424
for (int i = 0; i < p_expected_types.size(); i++) {
4425
const Variant::Type &type = p_expected_types[i];
4426
types.push_back(Variant::get_type_name(type));
4427
types.push_back("Array[" + Variant::get_type_name(type) + "]");
4428
switch (type) {
4429
case Variant::INT:
4430
types.push_back("PackedByteArray");
4431
types.push_back("PackedInt32Array");
4432
types.push_back("PackedInt64Array");
4433
break;
4434
case Variant::FLOAT:
4435
types.push_back("PackedFloat32Array");
4436
types.push_back("PackedFloat64Array");
4437
break;
4438
case Variant::STRING:
4439
types.push_back("PackedStringArray");
4440
break;
4441
case Variant::VECTOR2:
4442
types.push_back("PackedVector2Array");
4443
break;
4444
case Variant::VECTOR3:
4445
types.push_back("PackedVector3Array");
4446
break;
4447
case Variant::COLOR:
4448
types.push_back("PackedColorArray");
4449
break;
4450
case Variant::VECTOR4:
4451
types.push_back("PackedVector4Array");
4452
break;
4453
default:
4454
break;
4455
}
4456
}
4457
4458
String string;
4459
if (types.size() == 1) {
4460
string = types[0].quote();
4461
} else if (types.size() == 2) {
4462
string = types[0].quote() + " or " + types[1].quote();
4463
} else if (types.size() >= 3) {
4464
string = types[0].quote();
4465
for (int i = 1; i < types.size() - 1; i++) {
4466
string += ", " + types[i].quote();
4467
}
4468
string += ", or " + types[types.size() - 1].quote();
4469
}
4470
4471
return vformat(R"("%s" annotation requires a variable of type %s, but type "%s" was given instead.)", p_annotation_name, string, p_provided_type.to_string());
4472
}
4473
4474
static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
4475
switch (p_type.kind) {
4476
case GDScriptParser::DataType::NATIVE: {
4477
if (p_type.is_meta_type) {
4478
return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
4479
}
4480
return p_type.native_type;
4481
} break;
4482
case GDScriptParser::DataType::SCRIPT: {
4483
Ref<Script> script;
4484
if (p_type.script_type.is_valid()) {
4485
script = p_type.script_type;
4486
} else {
4487
script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
4488
}
4489
4490
if (p_type.is_meta_type) {
4491
return script.is_valid() ? script->get_class_name() : Script::get_class_static();
4492
}
4493
if (script.is_null()) {
4494
return p_type.native_type;
4495
}
4496
if (script->get_global_name() != StringName()) {
4497
return script->get_global_name();
4498
}
4499
4500
Ref<Script> base_script = script->get_base_script();
4501
if (base_script.is_null()) {
4502
return script->get_instance_base_type();
4503
}
4504
4505
GDScriptParser::DataType base_type;
4506
base_type.kind = GDScriptParser::DataType::SCRIPT;
4507
base_type.builtin_type = Variant::OBJECT;
4508
base_type.native_type = base_script->get_instance_base_type();
4509
base_type.script_type = base_script;
4510
base_type.script_path = base_script->get_path();
4511
4512
return _find_narrowest_native_or_global_class(base_type);
4513
} break;
4514
case GDScriptParser::DataType::CLASS: {
4515
if (p_type.is_meta_type) {
4516
return GDScript::get_class_static();
4517
}
4518
if (p_type.class_type == nullptr) {
4519
return p_type.native_type;
4520
}
4521
if (p_type.class_type->get_global_name() != StringName()) {
4522
return p_type.class_type->get_global_name();
4523
}
4524
return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
4525
} break;
4526
default: {
4527
ERR_FAIL_V(StringName());
4528
} break;
4529
}
4530
}
4531
4532
template <PropertyHint t_hint, Variant::Type t_type>
4533
bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4534
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4535
ERR_FAIL_NULL_V(p_class, false);
4536
4537
VariableNode *variable = static_cast<VariableNode *>(p_target);
4538
if (variable->is_static) {
4539
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4540
return false;
4541
}
4542
if (variable->exported) {
4543
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4544
return false;
4545
}
4546
4547
variable->exported = true;
4548
4549
variable->export_info.type = t_type;
4550
variable->export_info.hint = t_hint;
4551
4552
String hint_string;
4553
for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
4554
String arg_string = String(p_annotation->resolved_arguments[i]);
4555
4556
if (p_annotation->name != SNAME("@export_placeholder")) {
4557
if (arg_string.is_empty()) {
4558
push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
4559
return false;
4560
}
4561
if (arg_string.contains_char(',')) {
4562
push_error(vformat(R"(Argument %d of annotation "%s" contains a comma. Use separate arguments instead.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
4563
return false;
4564
}
4565
}
4566
4567
// WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
4568
if (p_annotation->name == SNAME("@export_flags")) {
4569
const int64_t max_flags = 32;
4570
Vector<String> t = arg_string.split(":", true, 1);
4571
if (t[0].is_empty()) {
4572
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
4573
return false;
4574
}
4575
if (t.size() == 2) {
4576
if (t[1].is_empty()) {
4577
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
4578
return false;
4579
}
4580
if (!t[1].is_valid_int()) {
4581
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be a valid integer.)", i + 1), p_annotation->arguments[i]);
4582
return false;
4583
}
4584
int64_t value = t[1].to_int();
4585
if (value < 1 || value >= (1LL << max_flags)) {
4586
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": The flag value must be at least 1 and at most 2 ** %d - 1.)", i + 1, max_flags), p_annotation->arguments[i]);
4587
return false;
4588
}
4589
} else if (i >= max_flags) {
4590
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Starting from argument %d, the flag value must be specified explicitly.)", i + 1, max_flags + 1), p_annotation->arguments[i]);
4591
return false;
4592
}
4593
} else if (p_annotation->name == SNAME("@export_node_path")) {
4594
String native_class = arg_string;
4595
if (ScriptServer::is_global_class(arg_string)) {
4596
native_class = ScriptServer::get_global_class_native_base(arg_string);
4597
}
4598
if (!ClassDB::class_exists(native_class)) {
4599
push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" was not found in the global scope.)", i + 1, arg_string), p_annotation->arguments[i]);
4600
return false;
4601
} else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
4602
push_error(vformat(R"(Invalid argument %d of annotation "@export_node_path": The class "%s" does not inherit "Node".)", i + 1, arg_string), p_annotation->arguments[i]);
4603
return false;
4604
}
4605
}
4606
4607
if (i > 0) {
4608
hint_string += ",";
4609
}
4610
hint_string += arg_string;
4611
}
4612
variable->export_info.hint_string = hint_string;
4613
4614
// This is called after the analyzer is done finding the type, so this should be set here.
4615
DataType export_type = variable->get_datatype();
4616
4617
// Use initializer type if specified type is `Variant`.
4618
if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
4619
export_type = variable->initializer->get_datatype();
4620
export_type.type_source = DataType::INFERRED;
4621
}
4622
4623
const Variant::Type original_export_type_builtin = export_type.builtin_type;
4624
4625
// Process array and packed array annotations on the element type.
4626
bool is_array = false;
4627
if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
4628
is_array = true;
4629
export_type = export_type.get_container_element_type(0);
4630
} else if (export_type.is_typed_container_type()) {
4631
is_array = true;
4632
export_type = export_type.get_typed_container_type();
4633
export_type.type_source = variable->datatype.type_source;
4634
}
4635
4636
bool is_dict = false;
4637
if (export_type.builtin_type == Variant::DICTIONARY && export_type.has_container_element_types()) {
4638
is_dict = true;
4639
DataType inner_type = export_type.get_container_element_type_or_variant(1);
4640
export_type = export_type.get_container_element_type_or_variant(0);
4641
export_type.set_container_element_type(0, inner_type); // Store earlier extracted value within key to separately parse after.
4642
}
4643
4644
bool use_default_variable_type_check = true;
4645
4646
if (p_annotation->name == SNAME("@export_range")) {
4647
if (export_type.builtin_type == Variant::INT) {
4648
variable->export_info.type = Variant::INT;
4649
}
4650
} else if (p_annotation->name == SNAME("@export_multiline")) {
4651
use_default_variable_type_check = false;
4652
4653
if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
4654
Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
4655
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4656
return false;
4657
}
4658
4659
if (export_type.builtin_type == Variant::DICTIONARY) {
4660
variable->export_info.type = Variant::DICTIONARY;
4661
}
4662
} else if (p_annotation->name == SNAME("@export")) {
4663
use_default_variable_type_check = false;
4664
4665
if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
4666
push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
4667
return false;
4668
}
4669
4670
if (export_type.has_no_type()) {
4671
push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
4672
return false;
4673
}
4674
4675
switch (export_type.kind) {
4676
case GDScriptParser::DataType::BUILTIN:
4677
variable->export_info.type = export_type.builtin_type;
4678
variable->export_info.hint = PROPERTY_HINT_NONE;
4679
variable->export_info.hint_string = String();
4680
break;
4681
case GDScriptParser::DataType::NATIVE:
4682
case GDScriptParser::DataType::SCRIPT:
4683
case GDScriptParser::DataType::CLASS: {
4684
const StringName class_name = _find_narrowest_native_or_global_class(export_type);
4685
if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
4686
variable->export_info.type = Variant::OBJECT;
4687
variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
4688
variable->export_info.hint_string = class_name;
4689
} else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
4690
variable->export_info.type = Variant::OBJECT;
4691
variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
4692
variable->export_info.hint_string = class_name;
4693
} else {
4694
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4695
return false;
4696
}
4697
} break;
4698
case GDScriptParser::DataType::ENUM: {
4699
if (export_type.is_meta_type) {
4700
variable->export_info.type = Variant::DICTIONARY;
4701
} else {
4702
variable->export_info.type = Variant::INT;
4703
variable->export_info.hint = PROPERTY_HINT_ENUM;
4704
4705
String enum_hint_string;
4706
bool first = true;
4707
for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
4708
if (!first) {
4709
enum_hint_string += ",";
4710
} else {
4711
first = false;
4712
}
4713
enum_hint_string += E.key.operator String().capitalize().xml_escape();
4714
enum_hint_string += ":";
4715
enum_hint_string += String::num_int64(E.value).xml_escape();
4716
}
4717
4718
variable->export_info.hint_string = enum_hint_string;
4719
variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
4720
variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
4721
}
4722
} break;
4723
case GDScriptParser::DataType::VARIANT: {
4724
if (export_type.is_variant()) {
4725
variable->export_info.type = Variant::NIL;
4726
variable->export_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
4727
}
4728
} break;
4729
default:
4730
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4731
return false;
4732
}
4733
4734
if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
4735
push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
4736
return false;
4737
}
4738
4739
if (is_dict) {
4740
String key_prefix = itos(variable->export_info.type);
4741
if (variable->export_info.hint) {
4742
key_prefix += "/" + itos(variable->export_info.hint);
4743
}
4744
key_prefix += ":" + variable->export_info.hint_string;
4745
4746
// Now parse value.
4747
export_type = export_type.get_container_element_type(0);
4748
4749
if (export_type.is_variant() || export_type.has_no_type()) {
4750
export_type.kind = GDScriptParser::DataType::BUILTIN;
4751
}
4752
switch (export_type.kind) {
4753
case GDScriptParser::DataType::BUILTIN:
4754
variable->export_info.type = export_type.builtin_type;
4755
variable->export_info.hint = PROPERTY_HINT_NONE;
4756
variable->export_info.hint_string = String();
4757
break;
4758
case GDScriptParser::DataType::NATIVE:
4759
case GDScriptParser::DataType::SCRIPT:
4760
case GDScriptParser::DataType::CLASS: {
4761
const StringName class_name = _find_narrowest_native_or_global_class(export_type);
4762
if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
4763
variable->export_info.type = Variant::OBJECT;
4764
variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
4765
variable->export_info.hint_string = class_name;
4766
} else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
4767
variable->export_info.type = Variant::OBJECT;
4768
variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
4769
variable->export_info.hint_string = class_name;
4770
} else {
4771
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4772
return false;
4773
}
4774
} break;
4775
case GDScriptParser::DataType::ENUM: {
4776
if (export_type.is_meta_type) {
4777
variable->export_info.type = Variant::DICTIONARY;
4778
} else {
4779
variable->export_info.type = Variant::INT;
4780
variable->export_info.hint = PROPERTY_HINT_ENUM;
4781
4782
String enum_hint_string;
4783
bool first = true;
4784
for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
4785
if (!first) {
4786
enum_hint_string += ",";
4787
} else {
4788
first = false;
4789
}
4790
enum_hint_string += E.key.operator String().capitalize().xml_escape();
4791
enum_hint_string += ":";
4792
enum_hint_string += String::num_int64(E.value).xml_escape();
4793
}
4794
4795
variable->export_info.hint_string = enum_hint_string;
4796
variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
4797
variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
4798
}
4799
} break;
4800
default:
4801
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4802
return false;
4803
}
4804
4805
if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
4806
push_error(vformat(R"(Node export is only supported in Node-derived classes, but the current class inherits "%s".)", p_class->base_type.to_string()), p_annotation);
4807
return false;
4808
}
4809
4810
String value_prefix = itos(variable->export_info.type);
4811
if (variable->export_info.hint) {
4812
value_prefix += "/" + itos(variable->export_info.hint);
4813
}
4814
value_prefix += ":" + variable->export_info.hint_string;
4815
4816
variable->export_info.type = Variant::DICTIONARY;
4817
variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
4818
variable->export_info.hint_string = key_prefix + ";" + value_prefix;
4819
variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
4820
variable->export_info.class_name = StringName();
4821
}
4822
} else if (p_annotation->name == SNAME("@export_enum")) {
4823
use_default_variable_type_check = false;
4824
4825
Variant::Type enum_type = Variant::INT;
4826
4827
if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
4828
enum_type = Variant::STRING;
4829
}
4830
4831
variable->export_info.type = enum_type;
4832
4833
if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
4834
Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
4835
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4836
return false;
4837
}
4838
}
4839
4840
if (use_default_variable_type_check) {
4841
// Validate variable type with export.
4842
if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
4843
// Allow float/int conversion.
4844
if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
4845
Vector<Variant::Type> expected_types = { t_type };
4846
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4847
return false;
4848
}
4849
}
4850
}
4851
4852
if (is_array) {
4853
String hint_prefix = itos(variable->export_info.type);
4854
if (variable->export_info.hint) {
4855
hint_prefix += "/" + itos(variable->export_info.hint);
4856
}
4857
variable->export_info.type = original_export_type_builtin;
4858
variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
4859
variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
4860
variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
4861
variable->export_info.class_name = StringName();
4862
}
4863
4864
return true;
4865
}
4866
4867
// For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
4868
// or handle array exports in a special way, so they are implemented as separate methods.
4869
4870
bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4871
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4872
4873
VariableNode *variable = static_cast<VariableNode *>(p_target);
4874
if (variable->is_static) {
4875
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4876
return false;
4877
}
4878
if (variable->exported) {
4879
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4880
return false;
4881
}
4882
4883
variable->exported = true;
4884
4885
// Save the info because the compiler uses export info for overwriting member info.
4886
variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
4887
variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
4888
4889
return true;
4890
}
4891
4892
bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4893
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4894
ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
4895
4896
VariableNode *variable = static_cast<VariableNode *>(p_target);
4897
if (variable->is_static) {
4898
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4899
return false;
4900
}
4901
if (variable->exported) {
4902
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4903
return false;
4904
}
4905
4906
variable->exported = true;
4907
4908
DataType export_type = variable->get_datatype();
4909
4910
variable->export_info.type = export_type.builtin_type;
4911
variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
4912
variable->export_info.hint_string = p_annotation->resolved_arguments[1];
4913
4914
if (p_annotation->resolved_arguments.size() >= 3) {
4915
variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
4916
}
4917
return true;
4918
}
4919
4920
bool GDScriptParser::export_tool_button_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4921
#ifdef TOOLS_ENABLED
4922
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4923
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4924
4925
if (!is_tool()) {
4926
push_error(R"(Tool buttons can only be used in tool scripts (add "@tool" to the top of the script).)", p_annotation);
4927
return false;
4928
}
4929
4930
VariableNode *variable = static_cast<VariableNode *>(p_target);
4931
4932
if (variable->is_static) {
4933
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4934
return false;
4935
}
4936
if (variable->exported) {
4937
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4938
return false;
4939
}
4940
4941
const DataType variable_type = variable->get_datatype();
4942
if (!variable_type.is_variant() && variable_type.is_hard_type()) {
4943
if (variable_type.kind != DataType::BUILTIN || variable_type.builtin_type != Variant::CALLABLE) {
4944
push_error(vformat(R"("@export_tool_button" annotation requires a variable of type "Callable", but type "%s" was given instead.)", variable_type.to_string()), p_annotation);
4945
return false;
4946
}
4947
}
4948
4949
variable->exported = true;
4950
4951
// Build the hint string (format: `<text>[,<icon>]`).
4952
String hint_string = p_annotation->resolved_arguments[0].operator String(); // Button text.
4953
if (p_annotation->resolved_arguments.size() > 1) {
4954
hint_string += "," + p_annotation->resolved_arguments[1].operator String(); // Button icon.
4955
}
4956
4957
variable->export_info.type = Variant::CALLABLE;
4958
variable->export_info.hint = PROPERTY_HINT_TOOL_BUTTON;
4959
variable->export_info.hint_string = hint_string;
4960
variable->export_info.usage = PROPERTY_USAGE_EDITOR;
4961
#endif // TOOLS_ENABLED
4962
4963
return true; // Only available in editor.
4964
}
4965
4966
template <PropertyUsageFlags t_usage>
4967
bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4968
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4969
4970
p_annotation->export_info.name = p_annotation->resolved_arguments[0];
4971
4972
switch (t_usage) {
4973
case PROPERTY_USAGE_CATEGORY: {
4974
p_annotation->export_info.usage = t_usage;
4975
} break;
4976
4977
case PROPERTY_USAGE_GROUP: {
4978
p_annotation->export_info.usage = t_usage;
4979
if (p_annotation->resolved_arguments.size() == 2) {
4980
p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
4981
}
4982
} break;
4983
4984
case PROPERTY_USAGE_SUBGROUP: {
4985
p_annotation->export_info.usage = t_usage;
4986
if (p_annotation->resolved_arguments.size() == 2) {
4987
p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
4988
}
4989
} break;
4990
}
4991
4992
return true;
4993
}
4994
4995
bool GDScriptParser::warning_ignore_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4996
#ifdef DEBUG_ENABLED
4997
if (is_ignoring_warnings) {
4998
return true; // We already ignore all warnings, let's optimize it.
4999
}
5000
5001
bool has_error = false;
5002
for (const Variant &warning_name : p_annotation->resolved_arguments) {
5003
GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
5004
if (warning_code == GDScriptWarning::WARNING_MAX) {
5005
push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
5006
has_error = true;
5007
} else {
5008
int start_line = p_annotation->start_line;
5009
int end_line = p_target->end_line;
5010
5011
switch (p_target->type) {
5012
#define SIMPLE_CASE(m_type, m_class, m_property) \
5013
case m_type: { \
5014
m_class *node = static_cast<m_class *>(p_target); \
5015
if (node->m_property == nullptr) { \
5016
end_line = node->start_line; \
5017
} else { \
5018
end_line = node->m_property->end_line; \
5019
} \
5020
} break;
5021
5022
// Can contain properties (set/get).
5023
SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
5024
5025
// Contain bodies.
5026
SIMPLE_CASE(Node::FOR, ForNode, list)
5027
SIMPLE_CASE(Node::IF, IfNode, condition)
5028
SIMPLE_CASE(Node::MATCH, MatchNode, test)
5029
SIMPLE_CASE(Node::WHILE, WhileNode, condition)
5030
#undef SIMPLE_CASE
5031
5032
case Node::CLASS: {
5033
end_line = p_target->start_line;
5034
for (const AnnotationNode *annotation : p_target->annotations) {
5035
start_line = MIN(start_line, annotation->start_line);
5036
end_line = MAX(end_line, annotation->end_line);
5037
}
5038
} break;
5039
5040
case Node::FUNCTION: {
5041
FunctionNode *function = static_cast<FunctionNode *>(p_target);
5042
end_line = function->start_line;
5043
for (int i = 0; i < function->parameters.size(); i++) {
5044
end_line = MAX(end_line, function->parameters[i]->end_line);
5045
if (function->parameters[i]->initializer != nullptr) {
5046
end_line = MAX(end_line, function->parameters[i]->initializer->end_line);
5047
}
5048
}
5049
} break;
5050
5051
case Node::MATCH_BRANCH: {
5052
MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
5053
end_line = branch->start_line;
5054
for (int i = 0; i < branch->patterns.size(); i++) {
5055
end_line = MAX(end_line, branch->patterns[i]->end_line);
5056
}
5057
} break;
5058
5059
default: {
5060
} break;
5061
}
5062
5063
end_line = MAX(start_line, end_line); // Prevent infinite loop.
5064
for (int line = start_line; line <= end_line; line++) {
5065
warning_ignored_lines[warning_code].insert(line);
5066
}
5067
}
5068
}
5069
return !has_error;
5070
#else // !DEBUG_ENABLED
5071
// Only available in debug builds.
5072
return true;
5073
#endif // DEBUG_ENABLED
5074
}
5075
5076
bool GDScriptParser::warning_ignore_region_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
5077
#ifdef DEBUG_ENABLED
5078
bool has_error = false;
5079
const bool is_start = p_annotation->name == SNAME("@warning_ignore_start");
5080
for (const Variant &warning_name : p_annotation->resolved_arguments) {
5081
GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
5082
if (warning_code == GDScriptWarning::WARNING_MAX) {
5083
push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
5084
has_error = true;
5085
continue;
5086
}
5087
if (is_start) {
5088
if (warning_ignore_start_lines[warning_code] != INT_MAX) {
5089
push_error(vformat(R"(Warning "%s" is already being ignored by "@warning_ignore_start" at line %d.)", String(warning_name).to_upper(), warning_ignore_start_lines[warning_code]), p_annotation);
5090
has_error = true;
5091
continue;
5092
}
5093
warning_ignore_start_lines[warning_code] = p_annotation->start_line;
5094
} else {
5095
if (warning_ignore_start_lines[warning_code] == INT_MAX) {
5096
push_error(vformat(R"(Warning "%s" is not being ignored by "@warning_ignore_start".)", String(warning_name).to_upper()), p_annotation);
5097
has_error = true;
5098
continue;
5099
}
5100
const int start_line = warning_ignore_start_lines[warning_code];
5101
const int end_line = MAX(start_line, p_annotation->start_line); // Prevent infinite loop.
5102
for (int i = start_line; i <= end_line; i++) {
5103
warning_ignored_lines[warning_code].insert(i);
5104
}
5105
warning_ignore_start_lines[warning_code] = INT_MAX;
5106
}
5107
}
5108
return !has_error;
5109
#else // !DEBUG_ENABLED
5110
// Only available in debug builds.
5111
return true;
5112
#endif // DEBUG_ENABLED
5113
}
5114
5115
bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
5116
ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
5117
5118
FunctionNode *function = static_cast<FunctionNode *>(p_target);
5119
if (function->rpc_config.get_type() != Variant::NIL) {
5120
push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
5121
return false;
5122
}
5123
5124
Dictionary rpc_config;
5125
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
5126
if (!p_annotation->resolved_arguments.is_empty()) {
5127
unsigned char locality_args = 0;
5128
unsigned char permission_args = 0;
5129
unsigned char transfer_mode_args = 0;
5130
5131
for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
5132
if (i == 3) {
5133
rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
5134
continue;
5135
}
5136
5137
String arg = p_annotation->resolved_arguments[i].operator String();
5138
if (arg == "call_local") {
5139
locality_args++;
5140
rpc_config["call_local"] = true;
5141
} else if (arg == "call_remote") {
5142
locality_args++;
5143
rpc_config["call_local"] = false;
5144
} else if (arg == "any_peer") {
5145
permission_args++;
5146
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
5147
} else if (arg == "authority") {
5148
permission_args++;
5149
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
5150
} else if (arg == "reliable") {
5151
transfer_mode_args++;
5152
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
5153
} else if (arg == "unreliable") {
5154
transfer_mode_args++;
5155
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
5156
} else if (arg == "unreliable_ordered") {
5157
transfer_mode_args++;
5158
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
5159
} else {
5160
push_error(R"(Invalid RPC argument. Must be one of: "call_local"/"call_remote" (local calls), "any_peer"/"authority" (permission), "reliable"/"unreliable"/"unreliable_ordered" (transfer mode).)", p_annotation);
5161
}
5162
}
5163
5164
if (locality_args > 1) {
5165
push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
5166
} else if (permission_args > 1) {
5167
push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
5168
} else if (transfer_mode_args > 1) {
5169
push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
5170
}
5171
}
5172
function->rpc_config = rpc_config;
5173
return true;
5174
}
5175
5176
GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
5177
switch (type) {
5178
case CONSTANT:
5179
return constant->get_datatype();
5180
case VARIABLE:
5181
return variable->get_datatype();
5182
case PARAMETER:
5183
return parameter->get_datatype();
5184
case FOR_VARIABLE:
5185
case PATTERN_BIND:
5186
return bind->get_datatype();
5187
case UNDEFINED:
5188
return DataType();
5189
}
5190
return DataType();
5191
}
5192
5193
String GDScriptParser::SuiteNode::Local::get_name() const {
5194
switch (type) {
5195
case SuiteNode::Local::PARAMETER:
5196
return "parameter";
5197
case SuiteNode::Local::CONSTANT:
5198
return "constant";
5199
case SuiteNode::Local::VARIABLE:
5200
return "variable";
5201
case SuiteNode::Local::FOR_VARIABLE:
5202
return "for loop iterator";
5203
case SuiteNode::Local::PATTERN_BIND:
5204
return "pattern bind";
5205
case SuiteNode::Local::UNDEFINED:
5206
return "<undefined>";
5207
default:
5208
return String();
5209
}
5210
}
5211
5212
String GDScriptParser::DataType::to_string() const {
5213
switch (kind) {
5214
case VARIANT:
5215
return "Variant";
5216
case BUILTIN:
5217
if (builtin_type == Variant::NIL) {
5218
return "null";
5219
}
5220
if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
5221
return vformat("Array[%s]", get_container_element_type(0).to_string());
5222
}
5223
if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
5224
return vformat("Dictionary[%s, %s]", get_container_element_type_or_variant(0).to_string(), get_container_element_type_or_variant(1).to_string());
5225
}
5226
return Variant::get_type_name(builtin_type);
5227
case NATIVE:
5228
if (is_meta_type) {
5229
return GDScriptNativeClass::get_class_static();
5230
}
5231
return native_type.operator String();
5232
case CLASS:
5233
if (class_type->identifier != nullptr) {
5234
return class_type->identifier->name.operator String();
5235
}
5236
return class_type->fqcn;
5237
case SCRIPT: {
5238
if (is_meta_type) {
5239
return script_type.is_valid() ? script_type->get_class_name().operator String() : "";
5240
}
5241
String name = script_type.is_valid() ? script_type->get_name() : "";
5242
if (!name.is_empty()) {
5243
return name;
5244
}
5245
name = script_path;
5246
if (!name.is_empty()) {
5247
return name;
5248
}
5249
return native_type.operator String();
5250
}
5251
case ENUM: {
5252
// native_type contains either the native class defining the enum
5253
// or the fully qualified class name of the script defining the enum
5254
return String(native_type).get_file(); // Remove path, keep filename
5255
}
5256
case RESOLVING:
5257
case UNRESOLVED:
5258
return "<unresolved type>";
5259
}
5260
5261
ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
5262
}
5263
5264
PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
5265
PropertyInfo result;
5266
result.name = p_name;
5267
result.usage = PROPERTY_USAGE_NONE;
5268
5269
if (!is_hard_type()) {
5270
result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
5271
return result;
5272
}
5273
5274
switch (kind) {
5275
case BUILTIN:
5276
result.type = builtin_type;
5277
if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
5278
const DataType elem_type = get_container_element_type(0);
5279
switch (elem_type.kind) {
5280
case BUILTIN:
5281
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5282
result.hint_string = Variant::get_type_name(elem_type.builtin_type);
5283
break;
5284
case NATIVE:
5285
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5286
result.hint_string = elem_type.native_type;
5287
break;
5288
case SCRIPT:
5289
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5290
if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
5291
result.hint_string = elem_type.script_type->get_global_name();
5292
} else {
5293
result.hint_string = elem_type.native_type;
5294
}
5295
break;
5296
case CLASS:
5297
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5298
if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
5299
result.hint_string = elem_type.class_type->get_global_name();
5300
} else {
5301
result.hint_string = elem_type.native_type;
5302
}
5303
break;
5304
case ENUM:
5305
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5306
result.hint_string = String(elem_type.native_type).replace("::", ".");
5307
break;
5308
case VARIANT:
5309
case RESOLVING:
5310
case UNRESOLVED:
5311
break;
5312
}
5313
} else if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
5314
const DataType key_type = get_container_element_type_or_variant(0);
5315
const DataType value_type = get_container_element_type_or_variant(1);
5316
if ((key_type.kind == VARIANT && value_type.kind == VARIANT) || key_type.kind == RESOLVING ||
5317
key_type.kind == UNRESOLVED || value_type.kind == RESOLVING || value_type.kind == UNRESOLVED) {
5318
break;
5319
}
5320
String key_hint, value_hint;
5321
switch (key_type.kind) {
5322
case BUILTIN:
5323
key_hint = Variant::get_type_name(key_type.builtin_type);
5324
break;
5325
case NATIVE:
5326
key_hint = key_type.native_type;
5327
break;
5328
case SCRIPT:
5329
if (key_type.script_type.is_valid() && key_type.script_type->get_global_name() != StringName()) {
5330
key_hint = key_type.script_type->get_global_name();
5331
} else {
5332
key_hint = key_type.native_type;
5333
}
5334
break;
5335
case CLASS:
5336
if (key_type.class_type != nullptr && key_type.class_type->get_global_name() != StringName()) {
5337
key_hint = key_type.class_type->get_global_name();
5338
} else {
5339
key_hint = key_type.native_type;
5340
}
5341
break;
5342
case ENUM:
5343
key_hint = String(key_type.native_type).replace("::", ".");
5344
break;
5345
default:
5346
key_hint = "Variant";
5347
break;
5348
}
5349
switch (value_type.kind) {
5350
case BUILTIN:
5351
value_hint = Variant::get_type_name(value_type.builtin_type);
5352
break;
5353
case NATIVE:
5354
value_hint = value_type.native_type;
5355
break;
5356
case SCRIPT:
5357
if (value_type.script_type.is_valid() && value_type.script_type->get_global_name() != StringName()) {
5358
value_hint = value_type.script_type->get_global_name();
5359
} else {
5360
value_hint = value_type.native_type;
5361
}
5362
break;
5363
case CLASS:
5364
if (value_type.class_type != nullptr && value_type.class_type->get_global_name() != StringName()) {
5365
value_hint = value_type.class_type->get_global_name();
5366
} else {
5367
value_hint = value_type.native_type;
5368
}
5369
break;
5370
case ENUM:
5371
value_hint = String(value_type.native_type).replace("::", ".");
5372
break;
5373
default:
5374
value_hint = "Variant";
5375
break;
5376
}
5377
result.hint = PROPERTY_HINT_DICTIONARY_TYPE;
5378
result.hint_string = key_hint + ";" + value_hint;
5379
}
5380
break;
5381
case NATIVE:
5382
result.type = Variant::OBJECT;
5383
if (is_meta_type) {
5384
result.class_name = GDScriptNativeClass::get_class_static();
5385
} else {
5386
result.class_name = native_type;
5387
}
5388
break;
5389
case SCRIPT:
5390
result.type = Variant::OBJECT;
5391
if (is_meta_type) {
5392
result.class_name = script_type.is_valid() ? script_type->get_class_name() : Script::get_class_static();
5393
} else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
5394
result.class_name = script_type->get_global_name();
5395
} else {
5396
result.class_name = native_type;
5397
}
5398
break;
5399
case CLASS:
5400
result.type = Variant::OBJECT;
5401
if (is_meta_type) {
5402
result.class_name = GDScript::get_class_static();
5403
} else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
5404
result.class_name = class_type->get_global_name();
5405
} else {
5406
result.class_name = native_type;
5407
}
5408
break;
5409
case ENUM:
5410
if (is_meta_type) {
5411
result.type = Variant::DICTIONARY;
5412
} else {
5413
result.type = Variant::INT;
5414
result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
5415
result.class_name = String(native_type).replace("::", ".");
5416
}
5417
break;
5418
case VARIANT:
5419
case RESOLVING:
5420
case UNRESOLVED:
5421
result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
5422
break;
5423
}
5424
5425
return result;
5426
}
5427
5428
static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
5429
switch (p_type) {
5430
case Variant::PACKED_BYTE_ARRAY:
5431
case Variant::PACKED_INT32_ARRAY:
5432
case Variant::PACKED_INT64_ARRAY:
5433
return Variant::INT;
5434
case Variant::PACKED_FLOAT32_ARRAY:
5435
case Variant::PACKED_FLOAT64_ARRAY:
5436
return Variant::FLOAT;
5437
case Variant::PACKED_STRING_ARRAY:
5438
return Variant::STRING;
5439
case Variant::PACKED_VECTOR2_ARRAY:
5440
return Variant::VECTOR2;
5441
case Variant::PACKED_VECTOR3_ARRAY:
5442
return Variant::VECTOR3;
5443
case Variant::PACKED_COLOR_ARRAY:
5444
return Variant::COLOR;
5445
case Variant::PACKED_VECTOR4_ARRAY:
5446
return Variant::VECTOR4;
5447
default:
5448
return Variant::NIL;
5449
}
5450
}
5451
5452
bool GDScriptParser::DataType::is_typed_container_type() const {
5453
return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
5454
}
5455
5456
GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
5457
GDScriptParser::DataType type;
5458
type.kind = GDScriptParser::DataType::BUILTIN;
5459
type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
5460
return type;
5461
}
5462
5463
bool GDScriptParser::DataType::can_reference(const GDScriptParser::DataType &p_other) const {
5464
if (p_other.is_meta_type) {
5465
return false;
5466
} else if (builtin_type != p_other.builtin_type) {
5467
return false;
5468
} else if (builtin_type != Variant::OBJECT) {
5469
return true;
5470
}
5471
5472
if (native_type == StringName()) {
5473
return true;
5474
} else if (p_other.native_type == StringName()) {
5475
return false;
5476
} else if (native_type != p_other.native_type && !ClassDB::is_parent_class(p_other.native_type, native_type)) {
5477
return false;
5478
}
5479
5480
Ref<Script> script = script_type;
5481
if (kind == GDScriptParser::DataType::CLASS && script.is_null()) {
5482
Error err = OK;
5483
Ref<GDScript> scr = GDScriptCache::get_shallow_script(script_path, err);
5484
ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", script_path));
5485
script.reference_ptr(scr->find_class(class_type->fqcn));
5486
}
5487
5488
Ref<Script> script_other = p_other.script_type;
5489
if (p_other.kind == GDScriptParser::DataType::CLASS && script_other.is_null()) {
5490
Error err = OK;
5491
Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_other.script_path, err);
5492
ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", p_other.script_path));
5493
script_other.reference_ptr(scr->find_class(p_other.class_type->fqcn));
5494
}
5495
5496
if (script.is_null()) {
5497
return true;
5498
} else if (script_other.is_null()) {
5499
return false;
5500
} else if (script != script_other && !script_other->inherits_script(script)) {
5501
return false;
5502
}
5503
5504
return true;
5505
}
5506
5507
void GDScriptParser::complete_extents(Node *p_node) {
5508
while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
5509
ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
5510
nodes_in_progress.pop_back();
5511
}
5512
if (nodes_in_progress.is_empty()) {
5513
ERR_PRINT("Parser bug: Extents tracking stack is empty.");
5514
} else {
5515
nodes_in_progress.pop_back();
5516
}
5517
}
5518
5519
void GDScriptParser::update_extents(Node *p_node) {
5520
p_node->end_line = previous.end_line;
5521
p_node->end_column = previous.end_column;
5522
}
5523
5524
void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
5525
p_node->start_line = p_token.start_line;
5526
p_node->end_line = p_token.end_line;
5527
p_node->start_column = p_token.start_column;
5528
p_node->end_column = p_token.end_column;
5529
}
5530
5531
void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
5532
if (p_from == nullptr) {
5533
return;
5534
}
5535
p_node->start_line = p_from->start_line;
5536
p_node->end_line = p_from->end_line;
5537
p_node->start_column = p_from->start_column;
5538
p_node->end_column = p_from->end_column;
5539
}
5540
5541
/*---------- PRETTY PRINT FOR DEBUG ----------*/
5542
5543
#ifdef DEBUG_ENABLED
5544
5545
void GDScriptParser::TreePrinter::increase_indent() {
5546
indent_level++;
5547
indent = "";
5548
for (int i = 0; i < indent_level * 4; i++) {
5549
if (i % 4 == 0) {
5550
indent += "|";
5551
} else {
5552
indent += " ";
5553
}
5554
}
5555
}
5556
5557
void GDScriptParser::TreePrinter::decrease_indent() {
5558
indent_level--;
5559
indent = "";
5560
for (int i = 0; i < indent_level * 4; i++) {
5561
if (i % 4 == 0) {
5562
indent += "|";
5563
} else {
5564
indent += " ";
5565
}
5566
}
5567
}
5568
5569
void GDScriptParser::TreePrinter::push_line(const String &p_line) {
5570
if (!p_line.is_empty()) {
5571
push_text(p_line);
5572
}
5573
printed += "\n";
5574
pending_indent = true;
5575
}
5576
5577
void GDScriptParser::TreePrinter::push_text(const String &p_text) {
5578
if (pending_indent) {
5579
printed += indent;
5580
pending_indent = false;
5581
}
5582
printed += p_text;
5583
}
5584
5585
void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
5586
push_text(p_annotation->name);
5587
push_text(" (");
5588
for (int i = 0; i < p_annotation->arguments.size(); i++) {
5589
if (i > 0) {
5590
push_text(" , ");
5591
}
5592
print_expression(p_annotation->arguments[i]);
5593
}
5594
push_line(")");
5595
}
5596
5597
void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
5598
push_text("[ ");
5599
for (int i = 0; i < p_array->elements.size(); i++) {
5600
if (i > 0) {
5601
push_text(" , ");
5602
}
5603
print_expression(p_array->elements[i]);
5604
}
5605
push_text(" ]");
5606
}
5607
5608
void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
5609
push_text("Assert ( ");
5610
print_expression(p_assert->condition);
5611
push_line(" )");
5612
}
5613
5614
void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
5615
switch (p_assignment->assignee->type) {
5616
case Node::IDENTIFIER:
5617
print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
5618
break;
5619
case Node::SUBSCRIPT:
5620
print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
5621
break;
5622
default:
5623
break; // Unreachable.
5624
}
5625
5626
push_text(" ");
5627
switch (p_assignment->operation) {
5628
case AssignmentNode::OP_ADDITION:
5629
push_text("+");
5630
break;
5631
case AssignmentNode::OP_SUBTRACTION:
5632
push_text("-");
5633
break;
5634
case AssignmentNode::OP_MULTIPLICATION:
5635
push_text("*");
5636
break;
5637
case AssignmentNode::OP_DIVISION:
5638
push_text("/");
5639
break;
5640
case AssignmentNode::OP_MODULO:
5641
push_text("%");
5642
break;
5643
case AssignmentNode::OP_POWER:
5644
push_text("**");
5645
break;
5646
case AssignmentNode::OP_BIT_SHIFT_LEFT:
5647
push_text("<<");
5648
break;
5649
case AssignmentNode::OP_BIT_SHIFT_RIGHT:
5650
push_text(">>");
5651
break;
5652
case AssignmentNode::OP_BIT_AND:
5653
push_text("&");
5654
break;
5655
case AssignmentNode::OP_BIT_OR:
5656
push_text("|");
5657
break;
5658
case AssignmentNode::OP_BIT_XOR:
5659
push_text("^");
5660
break;
5661
case AssignmentNode::OP_NONE:
5662
break;
5663
}
5664
push_text("= ");
5665
print_expression(p_assignment->assigned_value);
5666
push_line();
5667
}
5668
5669
void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
5670
push_text("Await ");
5671
print_expression(p_await->to_await);
5672
}
5673
5674
void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
5675
// Surround in parenthesis for disambiguation.
5676
push_text("(");
5677
print_expression(p_binary_op->left_operand);
5678
switch (p_binary_op->operation) {
5679
case BinaryOpNode::OP_ADDITION:
5680
push_text(" + ");
5681
break;
5682
case BinaryOpNode::OP_SUBTRACTION:
5683
push_text(" - ");
5684
break;
5685
case BinaryOpNode::OP_MULTIPLICATION:
5686
push_text(" * ");
5687
break;
5688
case BinaryOpNode::OP_DIVISION:
5689
push_text(" / ");
5690
break;
5691
case BinaryOpNode::OP_MODULO:
5692
push_text(" % ");
5693
break;
5694
case BinaryOpNode::OP_POWER:
5695
push_text(" ** ");
5696
break;
5697
case BinaryOpNode::OP_BIT_LEFT_SHIFT:
5698
push_text(" << ");
5699
break;
5700
case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
5701
push_text(" >> ");
5702
break;
5703
case BinaryOpNode::OP_BIT_AND:
5704
push_text(" & ");
5705
break;
5706
case BinaryOpNode::OP_BIT_OR:
5707
push_text(" | ");
5708
break;
5709
case BinaryOpNode::OP_BIT_XOR:
5710
push_text(" ^ ");
5711
break;
5712
case BinaryOpNode::OP_LOGIC_AND:
5713
push_text(" AND ");
5714
break;
5715
case BinaryOpNode::OP_LOGIC_OR:
5716
push_text(" OR ");
5717
break;
5718
case BinaryOpNode::OP_CONTENT_TEST:
5719
push_text(" IN ");
5720
break;
5721
case BinaryOpNode::OP_COMP_EQUAL:
5722
push_text(" == ");
5723
break;
5724
case BinaryOpNode::OP_COMP_NOT_EQUAL:
5725
push_text(" != ");
5726
break;
5727
case BinaryOpNode::OP_COMP_LESS:
5728
push_text(" < ");
5729
break;
5730
case BinaryOpNode::OP_COMP_LESS_EQUAL:
5731
push_text(" <= ");
5732
break;
5733
case BinaryOpNode::OP_COMP_GREATER:
5734
push_text(" > ");
5735
break;
5736
case BinaryOpNode::OP_COMP_GREATER_EQUAL:
5737
push_text(" >= ");
5738
break;
5739
}
5740
print_expression(p_binary_op->right_operand);
5741
// Surround in parenthesis for disambiguation.
5742
push_text(")");
5743
}
5744
5745
void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
5746
if (p_call->is_super) {
5747
push_text("super");
5748
if (p_call->callee != nullptr) {
5749
push_text(".");
5750
print_expression(p_call->callee);
5751
}
5752
} else {
5753
print_expression(p_call->callee);
5754
}
5755
push_text("( ");
5756
for (int i = 0; i < p_call->arguments.size(); i++) {
5757
if (i > 0) {
5758
push_text(" , ");
5759
}
5760
print_expression(p_call->arguments[i]);
5761
}
5762
push_text(" )");
5763
}
5764
5765
void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
5766
print_expression(p_cast->operand);
5767
push_text(" AS ");
5768
print_type(p_cast->cast_type);
5769
}
5770
5771
void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
5772
for (const AnnotationNode *E : p_class->annotations) {
5773
print_annotation(E);
5774
}
5775
push_text("Class ");
5776
if (p_class->identifier == nullptr) {
5777
push_text("<unnamed>");
5778
} else {
5779
print_identifier(p_class->identifier);
5780
}
5781
5782
if (p_class->extends_used) {
5783
bool first = true;
5784
push_text(" Extends ");
5785
if (!p_class->extends_path.is_empty()) {
5786
push_text(vformat(R"("%s")", p_class->extends_path));
5787
first = false;
5788
}
5789
for (int i = 0; i < p_class->extends.size(); i++) {
5790
if (!first) {
5791
push_text(".");
5792
} else {
5793
first = false;
5794
}
5795
push_text(p_class->extends[i]->name);
5796
}
5797
}
5798
5799
push_line(" :");
5800
5801
increase_indent();
5802
5803
for (int i = 0; i < p_class->members.size(); i++) {
5804
const ClassNode::Member &m = p_class->members[i];
5805
5806
switch (m.type) {
5807
case ClassNode::Member::CLASS:
5808
print_class(m.m_class);
5809
break;
5810
case ClassNode::Member::VARIABLE:
5811
print_variable(m.variable);
5812
break;
5813
case ClassNode::Member::CONSTANT:
5814
print_constant(m.constant);
5815
break;
5816
case ClassNode::Member::SIGNAL:
5817
print_signal(m.signal);
5818
break;
5819
case ClassNode::Member::FUNCTION:
5820
print_function(m.function);
5821
break;
5822
case ClassNode::Member::ENUM:
5823
print_enum(m.m_enum);
5824
break;
5825
case ClassNode::Member::ENUM_VALUE:
5826
break; // Nothing. Will be printed by enum.
5827
case ClassNode::Member::GROUP:
5828
break; // Nothing. Groups are only used by inspector.
5829
case ClassNode::Member::UNDEFINED:
5830
push_line("<unknown member>");
5831
break;
5832
}
5833
}
5834
5835
decrease_indent();
5836
}
5837
5838
void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
5839
push_text("Constant ");
5840
print_identifier(p_constant->identifier);
5841
5842
increase_indent();
5843
5844
push_line();
5845
push_text("= ");
5846
if (p_constant->initializer == nullptr) {
5847
push_text("<missing value>");
5848
} else {
5849
print_expression(p_constant->initializer);
5850
}
5851
decrease_indent();
5852
push_line();
5853
}
5854
5855
void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
5856
push_line("{");
5857
increase_indent();
5858
for (int i = 0; i < p_dictionary->elements.size(); i++) {
5859
print_expression(p_dictionary->elements[i].key);
5860
if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
5861
push_text(" : ");
5862
} else {
5863
push_text(" = ");
5864
}
5865
print_expression(p_dictionary->elements[i].value);
5866
push_line(" ,");
5867
}
5868
decrease_indent();
5869
push_text("}");
5870
}
5871
5872
void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
5873
if (p_expression == nullptr) {
5874
push_text("<invalid expression>");
5875
return;
5876
}
5877
switch (p_expression->type) {
5878
case Node::ARRAY:
5879
print_array(static_cast<ArrayNode *>(p_expression));
5880
break;
5881
case Node::ASSIGNMENT:
5882
print_assignment(static_cast<AssignmentNode *>(p_expression));
5883
break;
5884
case Node::AWAIT:
5885
print_await(static_cast<AwaitNode *>(p_expression));
5886
break;
5887
case Node::BINARY_OPERATOR:
5888
print_binary_op(static_cast<BinaryOpNode *>(p_expression));
5889
break;
5890
case Node::CALL:
5891
print_call(static_cast<CallNode *>(p_expression));
5892
break;
5893
case Node::CAST:
5894
print_cast(static_cast<CastNode *>(p_expression));
5895
break;
5896
case Node::DICTIONARY:
5897
print_dictionary(static_cast<DictionaryNode *>(p_expression));
5898
break;
5899
case Node::GET_NODE:
5900
print_get_node(static_cast<GetNodeNode *>(p_expression));
5901
break;
5902
case Node::IDENTIFIER:
5903
print_identifier(static_cast<IdentifierNode *>(p_expression));
5904
break;
5905
case Node::LAMBDA:
5906
print_lambda(static_cast<LambdaNode *>(p_expression));
5907
break;
5908
case Node::LITERAL:
5909
print_literal(static_cast<LiteralNode *>(p_expression));
5910
break;
5911
case Node::PRELOAD:
5912
print_preload(static_cast<PreloadNode *>(p_expression));
5913
break;
5914
case Node::SELF:
5915
print_self(static_cast<SelfNode *>(p_expression));
5916
break;
5917
case Node::SUBSCRIPT:
5918
print_subscript(static_cast<SubscriptNode *>(p_expression));
5919
break;
5920
case Node::TERNARY_OPERATOR:
5921
print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
5922
break;
5923
case Node::TYPE_TEST:
5924
print_type_test(static_cast<TypeTestNode *>(p_expression));
5925
break;
5926
case Node::UNARY_OPERATOR:
5927
print_unary_op(static_cast<UnaryOpNode *>(p_expression));
5928
break;
5929
default:
5930
push_text(vformat("<unknown expression %d>", p_expression->type));
5931
break;
5932
}
5933
}
5934
5935
void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
5936
push_text("Enum ");
5937
if (p_enum->identifier != nullptr) {
5938
print_identifier(p_enum->identifier);
5939
} else {
5940
push_text("<unnamed>");
5941
}
5942
5943
push_line(" {");
5944
increase_indent();
5945
for (int i = 0; i < p_enum->values.size(); i++) {
5946
const EnumNode::Value &item = p_enum->values[i];
5947
print_identifier(item.identifier);
5948
push_text(" = ");
5949
push_text(itos(item.value));
5950
push_line(" ,");
5951
}
5952
decrease_indent();
5953
push_line("}");
5954
}
5955
5956
void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
5957
push_text("For ");
5958
print_identifier(p_for->variable);
5959
push_text(" IN ");
5960
print_expression(p_for->list);
5961
push_line(" :");
5962
5963
increase_indent();
5964
5965
print_suite(p_for->loop);
5966
5967
decrease_indent();
5968
}
5969
5970
void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
5971
for (const AnnotationNode *E : p_function->annotations) {
5972
print_annotation(E);
5973
}
5974
if (p_function->is_static) {
5975
push_text("Static ");
5976
}
5977
push_text(p_context);
5978
push_text(" ");
5979
if (p_function->identifier) {
5980
print_identifier(p_function->identifier);
5981
} else {
5982
push_text("<anonymous>");
5983
}
5984
push_text("( ");
5985
for (int i = 0; i < p_function->parameters.size(); i++) {
5986
if (i > 0) {
5987
push_text(" , ");
5988
}
5989
print_parameter(p_function->parameters[i]);
5990
}
5991
push_line(" ) :");
5992
increase_indent();
5993
print_suite(p_function->body);
5994
decrease_indent();
5995
}
5996
5997
void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
5998
if (p_get_node->use_dollar) {
5999
push_text("$");
6000
}
6001
push_text(p_get_node->full_path);
6002
}
6003
6004
void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
6005
if (p_identifier != nullptr) {
6006
push_text(p_identifier->name);
6007
} else {
6008
push_text("<invalid identifier>");
6009
}
6010
}
6011
6012
void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
6013
if (p_is_elif) {
6014
push_text("Elif ");
6015
} else {
6016
push_text("If ");
6017
}
6018
print_expression(p_if->condition);
6019
push_line(" :");
6020
6021
increase_indent();
6022
print_suite(p_if->true_block);
6023
decrease_indent();
6024
6025
// FIXME: Properly detect "elif" blocks.
6026
if (p_if->false_block != nullptr) {
6027
push_line("Else :");
6028
increase_indent();
6029
print_suite(p_if->false_block);
6030
decrease_indent();
6031
}
6032
}
6033
6034
void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
6035
print_function(p_lambda->function, "Lambda");
6036
push_text("| captures [ ");
6037
for (int i = 0; i < p_lambda->captures.size(); i++) {
6038
if (i > 0) {
6039
push_text(" , ");
6040
}
6041
push_text(p_lambda->captures[i]->name.operator String());
6042
}
6043
push_line(" ]");
6044
}
6045
6046
void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
6047
// Prefix for string types.
6048
switch (p_literal->value.get_type()) {
6049
case Variant::NODE_PATH:
6050
push_text("^\"");
6051
break;
6052
case Variant::STRING:
6053
push_text("\"");
6054
break;
6055
case Variant::STRING_NAME:
6056
push_text("&\"");
6057
break;
6058
default:
6059
break;
6060
}
6061
push_text(p_literal->value);
6062
// Suffix for string types.
6063
switch (p_literal->value.get_type()) {
6064
case Variant::NODE_PATH:
6065
case Variant::STRING:
6066
case Variant::STRING_NAME:
6067
push_text("\"");
6068
break;
6069
default:
6070
break;
6071
}
6072
}
6073
6074
void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
6075
push_text("Match ");
6076
print_expression(p_match->test);
6077
push_line(" :");
6078
6079
increase_indent();
6080
for (int i = 0; i < p_match->branches.size(); i++) {
6081
print_match_branch(p_match->branches[i]);
6082
}
6083
decrease_indent();
6084
}
6085
6086
void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
6087
for (int i = 0; i < p_match_branch->patterns.size(); i++) {
6088
if (i > 0) {
6089
push_text(" , ");
6090
}
6091
print_match_pattern(p_match_branch->patterns[i]);
6092
}
6093
6094
push_line(" :");
6095
6096
increase_indent();
6097
print_suite(p_match_branch->block);
6098
decrease_indent();
6099
}
6100
6101
void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
6102
switch (p_match_pattern->pattern_type) {
6103
case PatternNode::PT_LITERAL:
6104
print_literal(p_match_pattern->literal);
6105
break;
6106
case PatternNode::PT_WILDCARD:
6107
push_text("_");
6108
break;
6109
case PatternNode::PT_REST:
6110
push_text("..");
6111
break;
6112
case PatternNode::PT_BIND:
6113
push_text("Var ");
6114
print_identifier(p_match_pattern->bind);
6115
break;
6116
case PatternNode::PT_EXPRESSION:
6117
print_expression(p_match_pattern->expression);
6118
break;
6119
case PatternNode::PT_ARRAY:
6120
push_text("[ ");
6121
for (int i = 0; i < p_match_pattern->array.size(); i++) {
6122
if (i > 0) {
6123
push_text(" , ");
6124
}
6125
print_match_pattern(p_match_pattern->array[i]);
6126
}
6127
push_text(" ]");
6128
break;
6129
case PatternNode::PT_DICTIONARY:
6130
push_text("{ ");
6131
for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
6132
if (i > 0) {
6133
push_text(" , ");
6134
}
6135
if (p_match_pattern->dictionary[i].key != nullptr) {
6136
// Key can be null for rest pattern.
6137
print_expression(p_match_pattern->dictionary[i].key);
6138
push_text(" : ");
6139
}
6140
print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
6141
}
6142
push_text(" }");
6143
break;
6144
}
6145
}
6146
6147
void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
6148
print_identifier(p_parameter->identifier);
6149
if (p_parameter->datatype_specifier != nullptr) {
6150
push_text(" : ");
6151
print_type(p_parameter->datatype_specifier);
6152
}
6153
if (p_parameter->initializer != nullptr) {
6154
push_text(" = ");
6155
print_expression(p_parameter->initializer);
6156
}
6157
}
6158
6159
void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
6160
push_text(R"(Preload ( ")");
6161
push_text(p_preload->resolved_path);
6162
push_text(R"(" )");
6163
}
6164
6165
void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
6166
push_text("Return");
6167
if (p_return->return_value != nullptr) {
6168
push_text(" ");
6169
print_expression(p_return->return_value);
6170
}
6171
push_line();
6172
}
6173
6174
void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
6175
push_text("Self(");
6176
if (p_self->current_class->identifier != nullptr) {
6177
print_identifier(p_self->current_class->identifier);
6178
} else {
6179
push_text("<main class>");
6180
}
6181
push_text(")");
6182
}
6183
6184
void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
6185
push_text("Signal ");
6186
print_identifier(p_signal->identifier);
6187
push_text("( ");
6188
for (int i = 0; i < p_signal->parameters.size(); i++) {
6189
print_parameter(p_signal->parameters[i]);
6190
}
6191
push_line(" )");
6192
}
6193
6194
void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
6195
print_expression(p_subscript->base);
6196
if (p_subscript->is_attribute) {
6197
push_text(".");
6198
print_identifier(p_subscript->attribute);
6199
} else {
6200
push_text("[ ");
6201
print_expression(p_subscript->index);
6202
push_text(" ]");
6203
}
6204
}
6205
6206
void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
6207
switch (p_statement->type) {
6208
case Node::ASSERT:
6209
print_assert(static_cast<AssertNode *>(p_statement));
6210
break;
6211
case Node::VARIABLE:
6212
print_variable(static_cast<VariableNode *>(p_statement));
6213
break;
6214
case Node::CONSTANT:
6215
print_constant(static_cast<ConstantNode *>(p_statement));
6216
break;
6217
case Node::IF:
6218
print_if(static_cast<IfNode *>(p_statement));
6219
break;
6220
case Node::FOR:
6221
print_for(static_cast<ForNode *>(p_statement));
6222
break;
6223
case Node::WHILE:
6224
print_while(static_cast<WhileNode *>(p_statement));
6225
break;
6226
case Node::MATCH:
6227
print_match(static_cast<MatchNode *>(p_statement));
6228
break;
6229
case Node::RETURN:
6230
print_return(static_cast<ReturnNode *>(p_statement));
6231
break;
6232
case Node::BREAK:
6233
push_line("Break");
6234
break;
6235
case Node::CONTINUE:
6236
push_line("Continue");
6237
break;
6238
case Node::PASS:
6239
push_line("Pass");
6240
break;
6241
case Node::BREAKPOINT:
6242
push_line("Breakpoint");
6243
break;
6244
case Node::ASSIGNMENT:
6245
print_assignment(static_cast<AssignmentNode *>(p_statement));
6246
break;
6247
default:
6248
if (p_statement->is_expression()) {
6249
print_expression(static_cast<ExpressionNode *>(p_statement));
6250
push_line();
6251
} else {
6252
push_line(vformat("<unknown statement %d>", p_statement->type));
6253
}
6254
break;
6255
}
6256
}
6257
6258
void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
6259
for (int i = 0; i < p_suite->statements.size(); i++) {
6260
print_statement(p_suite->statements[i]);
6261
}
6262
}
6263
6264
void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
6265
// Surround in parenthesis for disambiguation.
6266
push_text("(");
6267
print_expression(p_ternary_op->true_expr);
6268
push_text(") IF (");
6269
print_expression(p_ternary_op->condition);
6270
push_text(") ELSE (");
6271
print_expression(p_ternary_op->false_expr);
6272
push_text(")");
6273
}
6274
6275
void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
6276
if (p_type->type_chain.is_empty()) {
6277
push_text("Void");
6278
} else {
6279
for (int i = 0; i < p_type->type_chain.size(); i++) {
6280
if (i > 0) {
6281
push_text(".");
6282
}
6283
print_identifier(p_type->type_chain[i]);
6284
}
6285
}
6286
}
6287
6288
void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
6289
print_expression(p_test->operand);
6290
push_text(" IS ");
6291
print_type(p_test->test_type);
6292
}
6293
6294
void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
6295
// Surround in parenthesis for disambiguation.
6296
push_text("(");
6297
switch (p_unary_op->operation) {
6298
case UnaryOpNode::OP_POSITIVE:
6299
push_text("+");
6300
break;
6301
case UnaryOpNode::OP_NEGATIVE:
6302
push_text("-");
6303
break;
6304
case UnaryOpNode::OP_LOGIC_NOT:
6305
push_text("NOT");
6306
break;
6307
case UnaryOpNode::OP_COMPLEMENT:
6308
push_text("~");
6309
break;
6310
}
6311
print_expression(p_unary_op->operand);
6312
// Surround in parenthesis for disambiguation.
6313
push_text(")");
6314
}
6315
6316
void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
6317
for (const AnnotationNode *E : p_variable->annotations) {
6318
print_annotation(E);
6319
}
6320
6321
if (p_variable->is_static) {
6322
push_text("Static ");
6323
}
6324
push_text("Variable ");
6325
print_identifier(p_variable->identifier);
6326
6327
push_text(" : ");
6328
if (p_variable->datatype_specifier != nullptr) {
6329
print_type(p_variable->datatype_specifier);
6330
} else if (p_variable->infer_datatype) {
6331
push_text("<inferred type>");
6332
} else {
6333
push_text("Variant");
6334
}
6335
6336
increase_indent();
6337
6338
push_line();
6339
push_text("= ");
6340
if (p_variable->initializer == nullptr) {
6341
push_text("<default value>");
6342
} else {
6343
print_expression(p_variable->initializer);
6344
}
6345
push_line();
6346
6347
if (p_variable->property != VariableNode::PROP_NONE) {
6348
if (p_variable->getter != nullptr) {
6349
push_text("Get");
6350
if (p_variable->property == VariableNode::PROP_INLINE) {
6351
push_line(":");
6352
increase_indent();
6353
print_suite(p_variable->getter->body);
6354
decrease_indent();
6355
} else {
6356
push_line(" =");
6357
increase_indent();
6358
print_identifier(p_variable->getter_pointer);
6359
push_line();
6360
decrease_indent();
6361
}
6362
}
6363
if (p_variable->setter != nullptr) {
6364
push_text("Set (");
6365
if (p_variable->property == VariableNode::PROP_INLINE) {
6366
if (p_variable->setter_parameter != nullptr) {
6367
print_identifier(p_variable->setter_parameter);
6368
} else {
6369
push_text("<missing>");
6370
}
6371
push_line("):");
6372
increase_indent();
6373
print_suite(p_variable->setter->body);
6374
decrease_indent();
6375
} else {
6376
push_line(" =");
6377
increase_indent();
6378
print_identifier(p_variable->setter_pointer);
6379
push_line();
6380
decrease_indent();
6381
}
6382
}
6383
}
6384
6385
decrease_indent();
6386
push_line();
6387
}
6388
6389
void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
6390
push_text("While ");
6391
print_expression(p_while->condition);
6392
push_line(" :");
6393
6394
increase_indent();
6395
print_suite(p_while->loop);
6396
decrease_indent();
6397
}
6398
6399
void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
6400
ClassNode *class_tree = p_parser.get_tree();
6401
ERR_FAIL_NULL_MSG(class_tree, "Parse the code before printing the parse tree.");
6402
6403
if (p_parser.is_tool()) {
6404
push_line("@tool");
6405
}
6406
if (!class_tree->icon_path.is_empty()) {
6407
push_text(R"(@icon (")");
6408
push_text(class_tree->icon_path);
6409
push_line("\")");
6410
}
6411
print_class(class_tree);
6412
6413
print_line(String(printed));
6414
}
6415
6416
#endif // DEBUG_ENABLED
6417
6418