Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/gdscript_parser.cpp
11351 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/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
// Allow trailing comma.
3599
match(GDScriptTokenizer::Token::COMMA);
3600
3601
pop_multiline();
3602
consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
3603
complete_extents(preload);
3604
3605
return preload;
3606
}
3607
3608
GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
3609
LambdaNode *lambda = alloc_node<LambdaNode>();
3610
lambda->parent_function = current_function;
3611
lambda->parent_lambda = current_lambda;
3612
3613
FunctionNode *function = alloc_node<FunctionNode>();
3614
function->source_lambda = lambda;
3615
3616
function->is_static = current_function != nullptr ? current_function->is_static : false;
3617
3618
if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
3619
function->identifier = parse_identifier();
3620
}
3621
3622
bool multiline_context = multiline_stack.back()->get();
3623
3624
push_completion_call(nullptr);
3625
3626
// Reset the multiline stack since we don't want the multiline mode one in the lambda body.
3627
push_multiline(false);
3628
if (multiline_context) {
3629
tokenizer->push_expression_indented_block();
3630
}
3631
3632
push_multiline(true); // For the parameters.
3633
if (function->identifier) {
3634
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
3635
} else {
3636
consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
3637
}
3638
3639
FunctionNode *previous_function = current_function;
3640
current_function = function;
3641
3642
LambdaNode *previous_lambda = current_lambda;
3643
current_lambda = lambda;
3644
3645
SuiteNode *body = alloc_node<SuiteNode>();
3646
body->parent_function = current_function;
3647
body->parent_block = current_suite;
3648
3649
SuiteNode *previous_suite = current_suite;
3650
current_suite = body;
3651
3652
parse_function_signature(function, body, "lambda", -1);
3653
3654
current_suite = previous_suite;
3655
3656
bool previous_in_lambda = in_lambda;
3657
in_lambda = true;
3658
3659
// Save break/continue state.
3660
bool could_break = can_break;
3661
bool could_continue = can_continue;
3662
3663
// Disallow break/continue.
3664
can_break = false;
3665
can_continue = false;
3666
3667
function->body = parse_suite("lambda declaration", body, true);
3668
complete_extents(function);
3669
complete_extents(lambda);
3670
3671
pop_multiline();
3672
3673
pop_completion_call();
3674
3675
if (multiline_context) {
3676
// If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
3677
while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
3678
current = tokenizer->scan(); // Not advance() since we don't want to change the previous token.
3679
}
3680
tokenizer->pop_expression_indented_block();
3681
}
3682
3683
current_function = previous_function;
3684
current_lambda = previous_lambda;
3685
in_lambda = previous_in_lambda;
3686
lambda->function = function;
3687
3688
// Reset break/continue state.
3689
can_break = could_break;
3690
can_continue = could_continue;
3691
3692
return lambda;
3693
}
3694
3695
GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
3696
// x is not int
3697
// ^ ^^^ ExpressionNode, TypeNode
3698
// ^^^^^^^^^^^^ TypeTestNode
3699
// ^^^^^^^^^^^^ UnaryOpNode
3700
UnaryOpNode *not_node = nullptr;
3701
if (match(GDScriptTokenizer::Token::NOT)) {
3702
not_node = alloc_node<UnaryOpNode>();
3703
not_node->operation = UnaryOpNode::OP_LOGIC_NOT;
3704
not_node->variant_op = Variant::OP_NOT;
3705
reset_extents(not_node, p_previous_operand);
3706
update_extents(not_node);
3707
}
3708
3709
TypeTestNode *type_test = alloc_node<TypeTestNode>();
3710
reset_extents(type_test, p_previous_operand);
3711
update_extents(type_test);
3712
3713
type_test->operand = p_previous_operand;
3714
type_test->test_type = parse_type();
3715
complete_extents(type_test);
3716
3717
if (not_node != nullptr) {
3718
not_node->operand = type_test;
3719
complete_extents(not_node);
3720
}
3721
3722
if (type_test->test_type == nullptr) {
3723
if (not_node == nullptr) {
3724
push_error(R"(Expected type specifier after "is".)");
3725
} else {
3726
push_error(R"(Expected type specifier after "is not".)");
3727
}
3728
}
3729
3730
if (not_node != nullptr) {
3731
return not_node;
3732
}
3733
3734
return type_test;
3735
}
3736
3737
GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
3738
push_error(R"("yield" was removed in Godot 4. Use "await" instead.)");
3739
return nullptr;
3740
}
3741
3742
GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
3743
// Just for better error messages.
3744
GDScriptTokenizer::Token::Type invalid = previous.type;
3745
3746
switch (invalid) {
3747
case GDScriptTokenizer::Token::QUESTION_MARK:
3748
push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
3749
break;
3750
default:
3751
return nullptr; // Unreachable.
3752
}
3753
3754
// Return the previous expression.
3755
return p_previous_operand;
3756
}
3757
3758
GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
3759
TypeNode *type = alloc_node<TypeNode>();
3760
make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
3761
if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
3762
if (match(GDScriptTokenizer::Token::TK_VOID)) {
3763
if (p_allow_void) {
3764
complete_extents(type);
3765
TypeNode *void_type = type;
3766
return void_type;
3767
} else {
3768
push_error(R"("void" is only allowed for a function return type.)");
3769
}
3770
}
3771
// Leave error message to the caller who knows the context.
3772
complete_extents(type);
3773
return nullptr;
3774
}
3775
3776
IdentifierNode *type_element = parse_identifier();
3777
3778
type->type_chain.push_back(type_element);
3779
3780
if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
3781
// Typed collection (like Array[int], Dictionary[String, int]).
3782
bool first_pass = true;
3783
do {
3784
TypeNode *container_type = parse_type(false); // Don't allow void for element type.
3785
if (container_type == nullptr) {
3786
push_error(vformat(R"(Expected type for collection after "%s".)", first_pass ? "[" : ","));
3787
complete_extents(type);
3788
type = nullptr;
3789
break;
3790
} else if (container_type->container_types.size() > 0) {
3791
push_error("Nested typed collections are not supported.");
3792
} else {
3793
type->container_types.append(container_type);
3794
}
3795
first_pass = false;
3796
} while (match(GDScriptTokenizer::Token::COMMA));
3797
consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
3798
if (type != nullptr) {
3799
complete_extents(type);
3800
}
3801
return type;
3802
}
3803
3804
int chain_index = 1;
3805
while (match(GDScriptTokenizer::Token::PERIOD)) {
3806
make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
3807
if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
3808
type_element = parse_identifier();
3809
type->type_chain.push_back(type_element);
3810
}
3811
}
3812
3813
complete_extents(type);
3814
return type;
3815
}
3816
3817
#ifdef TOOLS_ENABLED
3818
enum DocLineState {
3819
DOC_LINE_NORMAL,
3820
DOC_LINE_IN_CODE,
3821
DOC_LINE_IN_CODEBLOCK,
3822
DOC_LINE_IN_KBD,
3823
};
3824
3825
static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
3826
String line = p_line;
3827
if (r_state == DOC_LINE_NORMAL) {
3828
line = line.strip_edges(true, false);
3829
} else {
3830
line = line.trim_prefix(p_space_prefix);
3831
}
3832
3833
String line_join;
3834
if (!p_text.is_empty()) {
3835
if (r_state == DOC_LINE_NORMAL) {
3836
if (p_text.ends_with("[/codeblock]")) {
3837
line_join = "\n";
3838
} else if (!p_text.ends_with("[br]")) {
3839
line_join = " ";
3840
}
3841
} else {
3842
line_join = "\n";
3843
}
3844
}
3845
3846
String result;
3847
int from = 0;
3848
int buffer_start = 0;
3849
const int len = line.length();
3850
bool process = true;
3851
while (process) {
3852
switch (r_state) {
3853
case DOC_LINE_NORMAL: {
3854
int lb_pos = line.find_char('[', from);
3855
if (lb_pos < 0) {
3856
process = false;
3857
break;
3858
}
3859
int rb_pos = line.find_char(']', lb_pos + 1);
3860
if (rb_pos < 0) {
3861
process = false;
3862
break;
3863
}
3864
3865
from = rb_pos + 1;
3866
3867
String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
3868
if (tag == "code" || tag.begins_with("code ")) {
3869
r_state = DOC_LINE_IN_CODE;
3870
} else if (tag == "codeblock" || tag.begins_with("codeblock ")) {
3871
if (lb_pos == 0) {
3872
line_join = "\n";
3873
} else {
3874
result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
3875
}
3876
result += "[" + tag + "]";
3877
if (from < len) {
3878
result += '\n';
3879
}
3880
3881
r_state = DOC_LINE_IN_CODEBLOCK;
3882
buffer_start = from;
3883
} else if (tag == "kbd") {
3884
r_state = DOC_LINE_IN_KBD;
3885
}
3886
} break;
3887
case DOC_LINE_IN_CODE: {
3888
int pos = line.find("[/code]", from);
3889
if (pos < 0) {
3890
process = false;
3891
break;
3892
}
3893
3894
from = pos + 7; // `len("[/code]")`.
3895
3896
r_state = DOC_LINE_NORMAL;
3897
} break;
3898
case DOC_LINE_IN_CODEBLOCK: {
3899
int pos = line.find("[/codeblock]", from);
3900
if (pos < 0) {
3901
process = false;
3902
break;
3903
}
3904
3905
from = pos + 12; // `len("[/codeblock]")`.
3906
3907
if (pos == 0) {
3908
line_join = "\n";
3909
} else {
3910
result += line.substr(buffer_start, pos - buffer_start) + '\n';
3911
}
3912
result += "[/codeblock]";
3913
if (from < len) {
3914
result += '\n';
3915
}
3916
3917
r_state = DOC_LINE_NORMAL;
3918
buffer_start = from;
3919
} break;
3920
case DOC_LINE_IN_KBD: {
3921
int pos = line.find("[/kbd]", from);
3922
if (pos < 0) {
3923
process = false;
3924
break;
3925
}
3926
3927
from = pos + 6; // `len("[/kbd]")`.
3928
3929
r_state = DOC_LINE_NORMAL;
3930
} break;
3931
}
3932
}
3933
3934
result += line.substr(buffer_start);
3935
if (r_state == DOC_LINE_NORMAL) {
3936
result = result.strip_edges(false, true);
3937
}
3938
3939
return line_join + result;
3940
}
3941
3942
bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
3943
bool has_comment = tokenizer->get_comments().has(p_line);
3944
// If there are no comments or if we don't care whether the comment
3945
// is a docstring, we have our result.
3946
if (!p_must_be_doc || !has_comment) {
3947
return has_comment;
3948
}
3949
3950
return tokenizer->get_comments()[p_line].comment.begins_with("##");
3951
}
3952
3953
GDScriptParser::MemberDocData GDScriptParser::parse_doc_comment(int p_line, bool p_single_line) {
3954
ERR_FAIL_COND_V(!has_comment(p_line, true), MemberDocData());
3955
3956
const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
3957
int line = p_line;
3958
3959
if (!p_single_line) {
3960
while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
3961
line--;
3962
}
3963
}
3964
3965
max_script_doc_line = MIN(max_script_doc_line, line - 1);
3966
3967
String space_prefix;
3968
{
3969
int i = 2;
3970
for (; i < comments[line].comment.length(); i++) {
3971
if (comments[line].comment[i] != ' ') {
3972
break;
3973
}
3974
}
3975
space_prefix = String(" ").repeat(i - 2);
3976
}
3977
3978
DocLineState state = DOC_LINE_NORMAL;
3979
MemberDocData result;
3980
3981
while (line <= p_line) {
3982
String doc_line = comments[line].comment.trim_prefix("##");
3983
line++;
3984
3985
if (state == DOC_LINE_NORMAL) {
3986
String stripped_line = doc_line.strip_edges();
3987
if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
3988
result.is_deprecated = true;
3989
if (stripped_line.begins_with("@deprecated:")) {
3990
result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
3991
}
3992
continue;
3993
} else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
3994
result.is_experimental = true;
3995
if (stripped_line.begins_with("@experimental:")) {
3996
result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
3997
}
3998
continue;
3999
}
4000
}
4001
4002
result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
4003
}
4004
4005
return result;
4006
}
4007
4008
GDScriptParser::ClassDocData GDScriptParser::parse_class_doc_comment(int p_line, bool p_single_line) {
4009
ERR_FAIL_COND_V(!has_comment(p_line, true), ClassDocData());
4010
4011
const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer->get_comments();
4012
int line = p_line;
4013
4014
if (!p_single_line) {
4015
while (comments.has(line - 1) && comments[line - 1].new_line && comments[line - 1].comment.begins_with("##")) {
4016
line--;
4017
}
4018
}
4019
4020
max_script_doc_line = MIN(max_script_doc_line, line - 1);
4021
4022
String space_prefix;
4023
{
4024
int i = 2;
4025
for (; i < comments[line].comment.length(); i++) {
4026
if (comments[line].comment[i] != ' ') {
4027
break;
4028
}
4029
}
4030
space_prefix = String(" ").repeat(i - 2);
4031
}
4032
4033
DocLineState state = DOC_LINE_NORMAL;
4034
bool is_in_brief = true;
4035
ClassDocData result;
4036
4037
while (line <= p_line) {
4038
String doc_line = comments[line].comment.trim_prefix("##");
4039
line++;
4040
4041
if (state == DOC_LINE_NORMAL) {
4042
String stripped_line = doc_line.strip_edges();
4043
4044
// A blank line separates the description from the brief.
4045
if (is_in_brief && !result.brief.is_empty() && stripped_line.is_empty()) {
4046
is_in_brief = false;
4047
continue;
4048
}
4049
4050
if (stripped_line.begins_with("@tutorial")) {
4051
String title, link;
4052
4053
int begin_scan = String("@tutorial").length();
4054
if (begin_scan >= stripped_line.length()) {
4055
continue; // Invalid syntax.
4056
}
4057
4058
if (stripped_line[begin_scan] == ':') { // No title.
4059
// Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
4060
title = "";
4061
link = stripped_line.trim_prefix("@tutorial:").strip_edges();
4062
} else {
4063
/* Syntax:
4064
* @tutorial ( The Title Here ) : https://the.url/
4065
* ^ open ^ close ^ colon ^ url
4066
*/
4067
int open_bracket_pos = begin_scan, close_bracket_pos = 0;
4068
while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
4069
open_bracket_pos++;
4070
}
4071
if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
4072
continue; // Invalid syntax.
4073
}
4074
close_bracket_pos = open_bracket_pos;
4075
while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
4076
close_bracket_pos++;
4077
}
4078
if (close_bracket_pos == stripped_line.length()) {
4079
continue; // Invalid syntax.
4080
}
4081
4082
int colon_pos = close_bracket_pos + 1;
4083
while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
4084
colon_pos++;
4085
}
4086
if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
4087
continue; // Invalid syntax.
4088
}
4089
4090
title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
4091
link = stripped_line.substr(colon_pos).strip_edges();
4092
}
4093
4094
result.tutorials.append(Pair<String, String>(title, link));
4095
continue;
4096
} else if (stripped_line == "@deprecated" || stripped_line.begins_with("@deprecated:")) {
4097
result.is_deprecated = true;
4098
if (stripped_line.begins_with("@deprecated:")) {
4099
result.deprecated_message = stripped_line.trim_prefix("@deprecated:").strip_edges();
4100
}
4101
continue;
4102
} else if (stripped_line == "@experimental" || stripped_line.begins_with("@experimental:")) {
4103
result.is_experimental = true;
4104
if (stripped_line.begins_with("@experimental:")) {
4105
result.experimental_message = stripped_line.trim_prefix("@experimental:").strip_edges();
4106
}
4107
continue;
4108
}
4109
}
4110
4111
if (is_in_brief) {
4112
result.brief += _process_doc_line(doc_line, result.brief, space_prefix, state);
4113
} else {
4114
result.description += _process_doc_line(doc_line, result.description, space_prefix, state);
4115
}
4116
}
4117
4118
return result;
4119
}
4120
#endif // TOOLS_ENABLED
4121
4122
GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
4123
// Function table for expression parsing.
4124
// clang-format destroys the alignment here, so turn off for the table.
4125
/* clang-format off */
4126
static ParseRule rules[] = {
4127
// PREFIX INFIX PRECEDENCE (for infix)
4128
{ nullptr, nullptr, PREC_NONE }, // EMPTY,
4129
// Basic
4130
{ nullptr, nullptr, PREC_NONE }, // ANNOTATION,
4131
{ &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
4132
{ &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
4133
// Comparison
4134
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
4135
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
4136
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
4137
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
4138
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
4139
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
4140
// Logical
4141
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
4142
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
4143
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
4144
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
4145
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
4146
{ &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
4147
// Bitwise
4148
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
4149
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
4150
{ &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
4151
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
4152
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
4153
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
4154
// Math
4155
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
4156
{ &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
4157
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
4158
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
4159
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
4160
{ &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
4161
// Assignment
4162
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
4163
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
4164
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
4165
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
4166
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
4167
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
4168
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
4169
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
4170
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
4171
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
4172
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
4173
{ nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
4174
// Control flow
4175
{ nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
4176
{ nullptr, nullptr, PREC_NONE }, // ELIF,
4177
{ nullptr, nullptr, PREC_NONE }, // ELSE,
4178
{ nullptr, nullptr, PREC_NONE }, // FOR,
4179
{ nullptr, nullptr, PREC_NONE }, // WHILE,
4180
{ nullptr, nullptr, PREC_NONE }, // BREAK,
4181
{ nullptr, nullptr, PREC_NONE }, // CONTINUE,
4182
{ nullptr, nullptr, PREC_NONE }, // PASS,
4183
{ nullptr, nullptr, PREC_NONE }, // RETURN,
4184
{ nullptr, nullptr, PREC_NONE }, // MATCH,
4185
{ nullptr, nullptr, PREC_NONE }, // WHEN,
4186
// Keywords
4187
{ nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
4188
{ nullptr, nullptr, PREC_NONE }, // ASSERT,
4189
{ &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
4190
{ nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
4191
{ nullptr, nullptr, PREC_NONE }, // CLASS,
4192
{ nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
4193
{ nullptr, nullptr, PREC_NONE }, // TK_CONST,
4194
{ nullptr, nullptr, PREC_NONE }, // ENUM,
4195
{ nullptr, nullptr, PREC_NONE }, // EXTENDS,
4196
{ &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
4197
{ nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // TK_IN,
4198
{ nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
4199
{ nullptr, nullptr, PREC_NONE }, // NAMESPACE,
4200
{ &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
4201
{ &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
4202
{ nullptr, nullptr, PREC_NONE }, // SIGNAL,
4203
{ nullptr, nullptr, PREC_NONE }, // STATIC,
4204
{ &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
4205
{ nullptr, nullptr, PREC_NONE }, // TRAIT,
4206
{ nullptr, nullptr, PREC_NONE }, // VAR,
4207
{ nullptr, nullptr, PREC_NONE }, // TK_VOID,
4208
{ &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
4209
// Punctuation
4210
{ &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
4211
{ nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
4212
{ &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
4213
{ nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
4214
{ &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
4215
{ nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
4216
{ nullptr, nullptr, PREC_NONE }, // COMMA,
4217
{ nullptr, nullptr, PREC_NONE }, // SEMICOLON,
4218
{ nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
4219
{ nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
4220
{ nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD_PERIOD,
4221
{ nullptr, nullptr, PREC_NONE }, // COLON,
4222
{ &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
4223
{ nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
4224
{ nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
4225
// Whitespace
4226
{ nullptr, nullptr, PREC_NONE }, // NEWLINE,
4227
{ nullptr, nullptr, PREC_NONE }, // INDENT,
4228
{ nullptr, nullptr, PREC_NONE }, // DEDENT,
4229
// Constants
4230
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
4231
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
4232
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
4233
{ &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
4234
// Error message improvement
4235
{ nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
4236
{ nullptr, nullptr, PREC_NONE }, // BACKTICK,
4237
{ nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
4238
// Special
4239
{ nullptr, nullptr, PREC_NONE }, // ERROR,
4240
{ nullptr, nullptr, PREC_NONE }, // TK_EOF,
4241
};
4242
/* clang-format on */
4243
// Avoid desync.
4244
static_assert(std_size(rules) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
4245
4246
// Let's assume this is never invalid, since nothing generates a TK_MAX.
4247
return &rules[p_token_type];
4248
}
4249
4250
bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
4251
if (locals_indices.has(p_name)) {
4252
return true;
4253
}
4254
if (parent_block != nullptr) {
4255
return parent_block->has_local(p_name);
4256
}
4257
return false;
4258
}
4259
4260
const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
4261
if (locals_indices.has(p_name)) {
4262
return locals[locals_indices[p_name]];
4263
}
4264
if (parent_block != nullptr) {
4265
return parent_block->get_local(p_name);
4266
}
4267
return empty;
4268
}
4269
4270
bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target, ClassNode *p_class) {
4271
if (is_applied) {
4272
return true;
4273
}
4274
is_applied = true;
4275
return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target, p_class);
4276
}
4277
4278
bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
4279
return (info->target_kind & p_target_kinds) > 0;
4280
}
4281
4282
bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
4283
ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
4284
4285
const MethodInfo &info = valid_annotations[p_annotation->name].info;
4286
4287
if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
4288
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()));
4289
return false;
4290
}
4291
4292
if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
4293
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()));
4294
return false;
4295
}
4296
4297
// Some annotations need to be resolved and applied in the parser.
4298
if (p_annotation->name == SNAME("@icon") || p_annotation->name == SNAME("@warning_ignore_start") || p_annotation->name == SNAME("@warning_ignore_restore")) {
4299
for (int i = 0; i < p_annotation->arguments.size(); i++) {
4300
ExpressionNode *argument = p_annotation->arguments[i];
4301
4302
if (argument->type != Node::LITERAL) {
4303
push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
4304
return false;
4305
}
4306
4307
Variant value = static_cast<LiteralNode *>(argument)->value;
4308
4309
if (value.get_type() != Variant::STRING) {
4310
push_error(vformat(R"(Argument %d of annotation "%s" must be a string literal.)", i + 1, p_annotation->name), argument);
4311
return false;
4312
}
4313
4314
p_annotation->resolved_arguments.push_back(value);
4315
}
4316
}
4317
4318
// For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
4319
4320
return true;
4321
}
4322
4323
bool GDScriptParser::tool_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4324
#ifdef DEBUG_ENABLED
4325
if (_is_tool) {
4326
push_error(R"("@tool" annotation can only be used once.)", p_annotation);
4327
return false;
4328
}
4329
#endif // DEBUG_ENABLED
4330
_is_tool = true;
4331
return true;
4332
}
4333
4334
bool GDScriptParser::icon_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4335
ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
4336
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4337
4338
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4339
String path = p_annotation->resolved_arguments[0];
4340
4341
#ifdef DEBUG_ENABLED
4342
if (!class_node->icon_path.is_empty()) {
4343
push_error(R"("@icon" annotation can only be used once.)", p_annotation);
4344
return false;
4345
}
4346
if (path.is_empty()) {
4347
push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
4348
return false;
4349
}
4350
#endif // DEBUG_ENABLED
4351
4352
class_node->icon_path = path;
4353
4354
if (path.is_empty() || path.is_absolute_path()) {
4355
class_node->simplified_icon_path = path.simplify_path();
4356
} else if (path.is_relative_path()) {
4357
class_node->simplified_icon_path = script_path.get_base_dir().path_join(path).simplify_path();
4358
} else {
4359
class_node->simplified_icon_path = path;
4360
}
4361
4362
return true;
4363
}
4364
4365
bool GDScriptParser::static_unload_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4366
ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
4367
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4368
if (class_node->annotated_static_unload) {
4369
push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
4370
return false;
4371
}
4372
class_node->annotated_static_unload = true;
4373
return true;
4374
}
4375
4376
bool GDScriptParser::abstract_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4377
// NOTE: Use `p_target`, **not** `p_class`, because when `p_target` is a class then `p_class` refers to the outer class.
4378
if (p_target->type == Node::CLASS) {
4379
ClassNode *class_node = static_cast<ClassNode *>(p_target);
4380
if (class_node->is_abstract) {
4381
push_error(R"("@abstract" annotation can only be used once per class.)", p_annotation);
4382
return false;
4383
}
4384
class_node->is_abstract = true;
4385
return true;
4386
}
4387
if (p_target->type == Node::FUNCTION) {
4388
FunctionNode *function_node = static_cast<FunctionNode *>(p_target);
4389
if (function_node->is_static) {
4390
push_error(R"("@abstract" annotation cannot be applied to static functions.)", p_annotation);
4391
return false;
4392
}
4393
if (function_node->is_abstract) {
4394
push_error(R"("@abstract" annotation can only be used once per function.)", p_annotation);
4395
return false;
4396
}
4397
function_node->is_abstract = true;
4398
return true;
4399
}
4400
ERR_FAIL_V_MSG(false, R"("@abstract" annotation can only be applied to classes and functions.)");
4401
}
4402
4403
bool GDScriptParser::onready_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4404
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
4405
4406
if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
4407
push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
4408
return false;
4409
}
4410
4411
VariableNode *variable = static_cast<VariableNode *>(p_target);
4412
if (variable->is_static) {
4413
push_error(R"("@onready" annotation cannot be applied to a static variable.)", p_annotation);
4414
return false;
4415
}
4416
if (variable->onready) {
4417
push_error(R"("@onready" annotation can only be used once per variable.)", p_annotation);
4418
return false;
4419
}
4420
variable->onready = true;
4421
current_class->onready_used = true;
4422
return true;
4423
}
4424
4425
static String _get_annotation_error_string(const StringName &p_annotation_name, const Vector<Variant::Type> &p_expected_types, const GDScriptParser::DataType &p_provided_type) {
4426
Vector<String> types;
4427
for (int i = 0; i < p_expected_types.size(); i++) {
4428
const Variant::Type &type = p_expected_types[i];
4429
types.push_back(Variant::get_type_name(type));
4430
types.push_back("Array[" + Variant::get_type_name(type) + "]");
4431
switch (type) {
4432
case Variant::INT:
4433
types.push_back("PackedByteArray");
4434
types.push_back("PackedInt32Array");
4435
types.push_back("PackedInt64Array");
4436
break;
4437
case Variant::FLOAT:
4438
types.push_back("PackedFloat32Array");
4439
types.push_back("PackedFloat64Array");
4440
break;
4441
case Variant::STRING:
4442
types.push_back("PackedStringArray");
4443
break;
4444
case Variant::VECTOR2:
4445
types.push_back("PackedVector2Array");
4446
break;
4447
case Variant::VECTOR3:
4448
types.push_back("PackedVector3Array");
4449
break;
4450
case Variant::COLOR:
4451
types.push_back("PackedColorArray");
4452
break;
4453
case Variant::VECTOR4:
4454
types.push_back("PackedVector4Array");
4455
break;
4456
default:
4457
break;
4458
}
4459
}
4460
4461
String string;
4462
if (types.size() == 1) {
4463
string = types[0].quote();
4464
} else if (types.size() == 2) {
4465
string = types[0].quote() + " or " + types[1].quote();
4466
} else if (types.size() >= 3) {
4467
string = types[0].quote();
4468
for (int i = 1; i < types.size() - 1; i++) {
4469
string += ", " + types[i].quote();
4470
}
4471
string += ", or " + types[types.size() - 1].quote();
4472
}
4473
4474
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());
4475
}
4476
4477
static StringName _find_narrowest_native_or_global_class(const GDScriptParser::DataType &p_type) {
4478
switch (p_type.kind) {
4479
case GDScriptParser::DataType::NATIVE: {
4480
if (p_type.is_meta_type) {
4481
return Object::get_class_static(); // `GDScriptNativeClass` is not an exposed class.
4482
}
4483
return p_type.native_type;
4484
} break;
4485
case GDScriptParser::DataType::SCRIPT: {
4486
Ref<Script> script;
4487
if (p_type.script_type.is_valid()) {
4488
script = p_type.script_type;
4489
} else {
4490
script = ResourceLoader::load(p_type.script_path, SNAME("Script"));
4491
}
4492
4493
if (p_type.is_meta_type) {
4494
return script.is_valid() ? script->get_class_name() : Script::get_class_static();
4495
}
4496
if (script.is_null()) {
4497
return p_type.native_type;
4498
}
4499
if (script->get_global_name() != StringName()) {
4500
return script->get_global_name();
4501
}
4502
4503
Ref<Script> base_script = script->get_base_script();
4504
if (base_script.is_null()) {
4505
return script->get_instance_base_type();
4506
}
4507
4508
GDScriptParser::DataType base_type;
4509
base_type.kind = GDScriptParser::DataType::SCRIPT;
4510
base_type.builtin_type = Variant::OBJECT;
4511
base_type.native_type = base_script->get_instance_base_type();
4512
base_type.script_type = base_script;
4513
base_type.script_path = base_script->get_path();
4514
4515
return _find_narrowest_native_or_global_class(base_type);
4516
} break;
4517
case GDScriptParser::DataType::CLASS: {
4518
if (p_type.is_meta_type) {
4519
return GDScript::get_class_static();
4520
}
4521
if (p_type.class_type == nullptr) {
4522
return p_type.native_type;
4523
}
4524
if (p_type.class_type->get_global_name() != StringName()) {
4525
return p_type.class_type->get_global_name();
4526
}
4527
return _find_narrowest_native_or_global_class(p_type.class_type->base_type);
4528
} break;
4529
default: {
4530
ERR_FAIL_V(StringName());
4531
} break;
4532
}
4533
}
4534
4535
template <PropertyHint t_hint, Variant::Type t_type>
4536
bool GDScriptParser::export_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4537
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4538
ERR_FAIL_NULL_V(p_class, false);
4539
4540
VariableNode *variable = static_cast<VariableNode *>(p_target);
4541
if (variable->is_static) {
4542
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4543
return false;
4544
}
4545
if (variable->exported) {
4546
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4547
return false;
4548
}
4549
4550
variable->exported = true;
4551
4552
variable->export_info.type = t_type;
4553
variable->export_info.hint = t_hint;
4554
4555
String hint_string;
4556
for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
4557
String arg_string = String(p_annotation->resolved_arguments[i]);
4558
4559
if (p_annotation->name != SNAME("@export_placeholder")) {
4560
if (arg_string.is_empty()) {
4561
push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
4562
return false;
4563
}
4564
if (arg_string.contains_char(',')) {
4565
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]);
4566
return false;
4567
}
4568
}
4569
4570
// WARNING: Do not merge with the previous `if` because there `!=`, not `==`!
4571
if (p_annotation->name == SNAME("@export_flags")) {
4572
const int64_t max_flags = 32;
4573
Vector<String> t = arg_string.split(":", true, 1);
4574
if (t[0].is_empty()) {
4575
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
4576
return false;
4577
}
4578
if (t.size() == 2) {
4579
if (t[1].is_empty()) {
4580
push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
4581
return false;
4582
}
4583
if (!t[1].is_valid_int()) {
4584
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]);
4585
return false;
4586
}
4587
int64_t value = t[1].to_int();
4588
if (value < 1 || value >= (1LL << max_flags)) {
4589
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]);
4590
return false;
4591
}
4592
} else if (i >= max_flags) {
4593
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]);
4594
return false;
4595
}
4596
} else if (p_annotation->name == SNAME("@export_node_path")) {
4597
String native_class = arg_string;
4598
if (ScriptServer::is_global_class(arg_string)) {
4599
native_class = ScriptServer::get_global_class_native_base(arg_string);
4600
}
4601
if (!ClassDB::class_exists(native_class)) {
4602
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]);
4603
return false;
4604
} else if (!ClassDB::is_parent_class(native_class, SNAME("Node"))) {
4605
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]);
4606
return false;
4607
}
4608
}
4609
4610
if (i > 0) {
4611
hint_string += ",";
4612
}
4613
hint_string += arg_string;
4614
}
4615
variable->export_info.hint_string = hint_string;
4616
4617
// This is called after the analyzer is done finding the type, so this should be set here.
4618
DataType export_type = variable->get_datatype();
4619
4620
// Use initializer type if specified type is `Variant`.
4621
if (export_type.is_variant() && variable->initializer != nullptr && variable->initializer->datatype.is_set()) {
4622
export_type = variable->initializer->get_datatype();
4623
export_type.type_source = DataType::INFERRED;
4624
}
4625
4626
const Variant::Type original_export_type_builtin = export_type.builtin_type;
4627
4628
// Process array and packed array annotations on the element type.
4629
bool is_array = false;
4630
if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type(0)) {
4631
is_array = true;
4632
export_type = export_type.get_container_element_type(0);
4633
} else if (export_type.is_typed_container_type()) {
4634
is_array = true;
4635
export_type = export_type.get_typed_container_type();
4636
export_type.type_source = variable->datatype.type_source;
4637
}
4638
4639
bool is_dict = false;
4640
if (export_type.builtin_type == Variant::DICTIONARY && export_type.has_container_element_types()) {
4641
is_dict = true;
4642
DataType inner_type = export_type.get_container_element_type_or_variant(1);
4643
export_type = export_type.get_container_element_type_or_variant(0);
4644
export_type.set_container_element_type(0, inner_type); // Store earlier extracted value within key to separately parse after.
4645
}
4646
4647
bool use_default_variable_type_check = true;
4648
4649
if (p_annotation->name == SNAME("@export_range")) {
4650
if (export_type.builtin_type == Variant::INT) {
4651
variable->export_info.type = Variant::INT;
4652
}
4653
} else if (p_annotation->name == SNAME("@export_multiline")) {
4654
use_default_variable_type_check = false;
4655
4656
if (export_type.builtin_type != Variant::STRING && export_type.builtin_type != Variant::DICTIONARY) {
4657
Vector<Variant::Type> expected_types = { Variant::STRING, Variant::DICTIONARY };
4658
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4659
return false;
4660
}
4661
4662
if (export_type.builtin_type == Variant::DICTIONARY) {
4663
variable->export_info.type = Variant::DICTIONARY;
4664
}
4665
} else if (p_annotation->name == SNAME("@export")) {
4666
use_default_variable_type_check = false;
4667
4668
if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
4669
push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
4670
return false;
4671
}
4672
4673
if (export_type.has_no_type()) {
4674
push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
4675
return false;
4676
}
4677
4678
switch (export_type.kind) {
4679
case GDScriptParser::DataType::BUILTIN:
4680
variable->export_info.type = export_type.builtin_type;
4681
variable->export_info.hint = PROPERTY_HINT_NONE;
4682
variable->export_info.hint_string = String();
4683
break;
4684
case GDScriptParser::DataType::NATIVE:
4685
case GDScriptParser::DataType::SCRIPT:
4686
case GDScriptParser::DataType::CLASS: {
4687
const StringName class_name = _find_narrowest_native_or_global_class(export_type);
4688
if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
4689
variable->export_info.type = Variant::OBJECT;
4690
variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
4691
variable->export_info.hint_string = class_name;
4692
} else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
4693
variable->export_info.type = Variant::OBJECT;
4694
variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
4695
variable->export_info.hint_string = class_name;
4696
} else {
4697
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4698
return false;
4699
}
4700
} break;
4701
case GDScriptParser::DataType::ENUM: {
4702
if (export_type.is_meta_type) {
4703
variable->export_info.type = Variant::DICTIONARY;
4704
} else {
4705
variable->export_info.type = Variant::INT;
4706
variable->export_info.hint = PROPERTY_HINT_ENUM;
4707
4708
String enum_hint_string;
4709
bool first = true;
4710
for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
4711
if (!first) {
4712
enum_hint_string += ",";
4713
} else {
4714
first = false;
4715
}
4716
enum_hint_string += E.key.operator String().capitalize().xml_escape();
4717
enum_hint_string += ":";
4718
enum_hint_string += String::num_int64(E.value).xml_escape();
4719
}
4720
4721
variable->export_info.hint_string = enum_hint_string;
4722
variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
4723
variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
4724
}
4725
} break;
4726
case GDScriptParser::DataType::VARIANT: {
4727
if (export_type.is_variant()) {
4728
variable->export_info.type = Variant::NIL;
4729
variable->export_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
4730
}
4731
} break;
4732
default:
4733
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4734
return false;
4735
}
4736
4737
if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
4738
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);
4739
return false;
4740
}
4741
4742
if (is_dict) {
4743
String key_prefix = itos(variable->export_info.type);
4744
if (variable->export_info.hint) {
4745
key_prefix += "/" + itos(variable->export_info.hint);
4746
}
4747
key_prefix += ":" + variable->export_info.hint_string;
4748
4749
// Now parse value.
4750
export_type = export_type.get_container_element_type(0);
4751
4752
if (export_type.is_variant() || export_type.has_no_type()) {
4753
export_type.kind = GDScriptParser::DataType::BUILTIN;
4754
}
4755
switch (export_type.kind) {
4756
case GDScriptParser::DataType::BUILTIN:
4757
variable->export_info.type = export_type.builtin_type;
4758
variable->export_info.hint = PROPERTY_HINT_NONE;
4759
variable->export_info.hint_string = String();
4760
break;
4761
case GDScriptParser::DataType::NATIVE:
4762
case GDScriptParser::DataType::SCRIPT:
4763
case GDScriptParser::DataType::CLASS: {
4764
const StringName class_name = _find_narrowest_native_or_global_class(export_type);
4765
if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
4766
variable->export_info.type = Variant::OBJECT;
4767
variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
4768
variable->export_info.hint_string = class_name;
4769
} else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
4770
variable->export_info.type = Variant::OBJECT;
4771
variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
4772
variable->export_info.hint_string = class_name;
4773
} else {
4774
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4775
return false;
4776
}
4777
} break;
4778
case GDScriptParser::DataType::ENUM: {
4779
if (export_type.is_meta_type) {
4780
variable->export_info.type = Variant::DICTIONARY;
4781
} else {
4782
variable->export_info.type = Variant::INT;
4783
variable->export_info.hint = PROPERTY_HINT_ENUM;
4784
4785
String enum_hint_string;
4786
bool first = true;
4787
for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
4788
if (!first) {
4789
enum_hint_string += ",";
4790
} else {
4791
first = false;
4792
}
4793
enum_hint_string += E.key.operator String().capitalize().xml_escape();
4794
enum_hint_string += ":";
4795
enum_hint_string += String::num_int64(E.value).xml_escape();
4796
}
4797
4798
variable->export_info.hint_string = enum_hint_string;
4799
variable->export_info.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
4800
variable->export_info.class_name = String(export_type.native_type).replace("::", ".");
4801
}
4802
} break;
4803
default:
4804
push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", p_annotation);
4805
return false;
4806
}
4807
4808
if (variable->export_info.hint == PROPERTY_HINT_NODE_TYPE && !ClassDB::is_parent_class(p_class->base_type.native_type, SNAME("Node"))) {
4809
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);
4810
return false;
4811
}
4812
4813
String value_prefix = itos(variable->export_info.type);
4814
if (variable->export_info.hint) {
4815
value_prefix += "/" + itos(variable->export_info.hint);
4816
}
4817
value_prefix += ":" + variable->export_info.hint_string;
4818
4819
variable->export_info.type = Variant::DICTIONARY;
4820
variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
4821
variable->export_info.hint_string = key_prefix + ";" + value_prefix;
4822
variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
4823
variable->export_info.class_name = StringName();
4824
}
4825
} else if (p_annotation->name == SNAME("@export_enum")) {
4826
use_default_variable_type_check = false;
4827
4828
Variant::Type enum_type = Variant::INT;
4829
4830
if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
4831
enum_type = Variant::STRING;
4832
}
4833
4834
variable->export_info.type = enum_type;
4835
4836
if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
4837
Vector<Variant::Type> expected_types = { Variant::INT, Variant::STRING };
4838
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4839
return false;
4840
}
4841
}
4842
4843
if (use_default_variable_type_check) {
4844
// Validate variable type with export.
4845
if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
4846
// Allow float/int conversion.
4847
if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
4848
Vector<Variant::Type> expected_types = { t_type };
4849
push_error(_get_annotation_error_string(p_annotation->name, expected_types, variable->get_datatype()), p_annotation);
4850
return false;
4851
}
4852
}
4853
}
4854
4855
if (is_array) {
4856
String hint_prefix = itos(variable->export_info.type);
4857
if (variable->export_info.hint) {
4858
hint_prefix += "/" + itos(variable->export_info.hint);
4859
}
4860
variable->export_info.type = original_export_type_builtin;
4861
variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
4862
variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
4863
variable->export_info.usage = PROPERTY_USAGE_DEFAULT;
4864
variable->export_info.class_name = StringName();
4865
}
4866
4867
return true;
4868
}
4869
4870
// For `@export_storage` and `@export_custom`, there is no need to check the variable type, argument values,
4871
// or handle array exports in a special way, so they are implemented as separate methods.
4872
4873
bool GDScriptParser::export_storage_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4874
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4875
4876
VariableNode *variable = static_cast<VariableNode *>(p_target);
4877
if (variable->is_static) {
4878
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4879
return false;
4880
}
4881
if (variable->exported) {
4882
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4883
return false;
4884
}
4885
4886
variable->exported = true;
4887
4888
// Save the info because the compiler uses export info for overwriting member info.
4889
variable->export_info = variable->get_datatype().to_property_info(variable->identifier->name);
4890
variable->export_info.usage |= PROPERTY_USAGE_STORAGE;
4891
4892
return true;
4893
}
4894
4895
bool GDScriptParser::export_custom_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4896
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4897
ERR_FAIL_COND_V_MSG(p_annotation->resolved_arguments.size() < 2, false, R"(Annotation "@export_custom" requires 2 arguments.)");
4898
4899
VariableNode *variable = static_cast<VariableNode *>(p_target);
4900
if (variable->is_static) {
4901
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4902
return false;
4903
}
4904
if (variable->exported) {
4905
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4906
return false;
4907
}
4908
4909
variable->exported = true;
4910
4911
DataType export_type = variable->get_datatype();
4912
4913
variable->export_info.type = export_type.builtin_type;
4914
variable->export_info.hint = static_cast<PropertyHint>(p_annotation->resolved_arguments[0].operator int64_t());
4915
variable->export_info.hint_string = p_annotation->resolved_arguments[1];
4916
4917
if (p_annotation->resolved_arguments.size() >= 3) {
4918
variable->export_info.usage = p_annotation->resolved_arguments[2].operator int64_t();
4919
}
4920
return true;
4921
}
4922
4923
bool GDScriptParser::export_tool_button_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4924
#ifdef TOOLS_ENABLED
4925
ERR_FAIL_COND_V_MSG(p_target->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
4926
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4927
4928
if (!is_tool()) {
4929
push_error(R"(Tool buttons can only be used in tool scripts (add "@tool" to the top of the script).)", p_annotation);
4930
return false;
4931
}
4932
4933
VariableNode *variable = static_cast<VariableNode *>(p_target);
4934
4935
if (variable->is_static) {
4936
push_error(vformat(R"(Annotation "%s" cannot be applied to a static variable.)", p_annotation->name), p_annotation);
4937
return false;
4938
}
4939
if (variable->exported) {
4940
push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
4941
return false;
4942
}
4943
4944
const DataType variable_type = variable->get_datatype();
4945
if (!variable_type.is_variant() && variable_type.is_hard_type()) {
4946
if (variable_type.kind != DataType::BUILTIN || variable_type.builtin_type != Variant::CALLABLE) {
4947
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);
4948
return false;
4949
}
4950
}
4951
4952
variable->exported = true;
4953
4954
// Build the hint string (format: `<text>[,<icon>]`).
4955
String hint_string = p_annotation->resolved_arguments[0].operator String(); // Button text.
4956
if (p_annotation->resolved_arguments.size() > 1) {
4957
hint_string += "," + p_annotation->resolved_arguments[1].operator String(); // Button icon.
4958
}
4959
4960
variable->export_info.type = Variant::CALLABLE;
4961
variable->export_info.hint = PROPERTY_HINT_TOOL_BUTTON;
4962
variable->export_info.hint_string = hint_string;
4963
variable->export_info.usage = PROPERTY_USAGE_EDITOR;
4964
#endif // TOOLS_ENABLED
4965
4966
return true; // Only available in editor.
4967
}
4968
4969
template <PropertyUsageFlags t_usage>
4970
bool GDScriptParser::export_group_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4971
ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
4972
4973
p_annotation->export_info.name = p_annotation->resolved_arguments[0];
4974
4975
switch (t_usage) {
4976
case PROPERTY_USAGE_CATEGORY: {
4977
p_annotation->export_info.usage = t_usage;
4978
} break;
4979
4980
case PROPERTY_USAGE_GROUP: {
4981
p_annotation->export_info.usage = t_usage;
4982
if (p_annotation->resolved_arguments.size() == 2) {
4983
p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
4984
}
4985
} break;
4986
4987
case PROPERTY_USAGE_SUBGROUP: {
4988
p_annotation->export_info.usage = t_usage;
4989
if (p_annotation->resolved_arguments.size() == 2) {
4990
p_annotation->export_info.hint_string = p_annotation->resolved_arguments[1];
4991
}
4992
} break;
4993
}
4994
4995
return true;
4996
}
4997
4998
bool GDScriptParser::warning_ignore_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
4999
#ifdef DEBUG_ENABLED
5000
if (is_ignoring_warnings) {
5001
return true; // We already ignore all warnings, let's optimize it.
5002
}
5003
5004
bool has_error = false;
5005
for (const Variant &warning_name : p_annotation->resolved_arguments) {
5006
GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
5007
if (warning_code == GDScriptWarning::WARNING_MAX) {
5008
push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
5009
has_error = true;
5010
} else {
5011
int start_line = p_annotation->start_line;
5012
int end_line = p_target->end_line;
5013
5014
switch (p_target->type) {
5015
#define SIMPLE_CASE(m_type, m_class, m_property) \
5016
case m_type: { \
5017
m_class *node = static_cast<m_class *>(p_target); \
5018
if (node->m_property == nullptr) { \
5019
end_line = node->start_line; \
5020
} else { \
5021
end_line = node->m_property->end_line; \
5022
} \
5023
} break;
5024
5025
// Can contain properties (set/get).
5026
SIMPLE_CASE(Node::VARIABLE, VariableNode, initializer)
5027
5028
// Contain bodies.
5029
SIMPLE_CASE(Node::FOR, ForNode, list)
5030
SIMPLE_CASE(Node::IF, IfNode, condition)
5031
SIMPLE_CASE(Node::MATCH, MatchNode, test)
5032
SIMPLE_CASE(Node::WHILE, WhileNode, condition)
5033
#undef SIMPLE_CASE
5034
5035
case Node::CLASS: {
5036
end_line = p_target->start_line;
5037
for (const AnnotationNode *annotation : p_target->annotations) {
5038
start_line = MIN(start_line, annotation->start_line);
5039
end_line = MAX(end_line, annotation->end_line);
5040
}
5041
} break;
5042
5043
case Node::FUNCTION: {
5044
FunctionNode *function = static_cast<FunctionNode *>(p_target);
5045
end_line = function->start_line;
5046
for (int i = 0; i < function->parameters.size(); i++) {
5047
end_line = MAX(end_line, function->parameters[i]->end_line);
5048
if (function->parameters[i]->initializer != nullptr) {
5049
end_line = MAX(end_line, function->parameters[i]->initializer->end_line);
5050
}
5051
}
5052
} break;
5053
5054
case Node::MATCH_BRANCH: {
5055
MatchBranchNode *branch = static_cast<MatchBranchNode *>(p_target);
5056
end_line = branch->start_line;
5057
for (int i = 0; i < branch->patterns.size(); i++) {
5058
end_line = MAX(end_line, branch->patterns[i]->end_line);
5059
}
5060
} break;
5061
5062
default: {
5063
} break;
5064
}
5065
5066
end_line = MAX(start_line, end_line); // Prevent infinite loop.
5067
for (int line = start_line; line <= end_line; line++) {
5068
warning_ignored_lines[warning_code].insert(line);
5069
}
5070
}
5071
}
5072
return !has_error;
5073
#else // !DEBUG_ENABLED
5074
// Only available in debug builds.
5075
return true;
5076
#endif // DEBUG_ENABLED
5077
}
5078
5079
bool GDScriptParser::warning_ignore_region_annotations(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
5080
#ifdef DEBUG_ENABLED
5081
bool has_error = false;
5082
const bool is_start = p_annotation->name == SNAME("@warning_ignore_start");
5083
for (const Variant &warning_name : p_annotation->resolved_arguments) {
5084
GDScriptWarning::Code warning_code = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
5085
if (warning_code == GDScriptWarning::WARNING_MAX) {
5086
push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
5087
has_error = true;
5088
continue;
5089
}
5090
if (is_start) {
5091
if (warning_ignore_start_lines[warning_code] != INT_MAX) {
5092
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);
5093
has_error = true;
5094
continue;
5095
}
5096
warning_ignore_start_lines[warning_code] = p_annotation->start_line;
5097
} else {
5098
if (warning_ignore_start_lines[warning_code] == INT_MAX) {
5099
push_error(vformat(R"(Warning "%s" is not being ignored by "@warning_ignore_start".)", String(warning_name).to_upper()), p_annotation);
5100
has_error = true;
5101
continue;
5102
}
5103
const int start_line = warning_ignore_start_lines[warning_code];
5104
const int end_line = MAX(start_line, p_annotation->start_line); // Prevent infinite loop.
5105
for (int i = start_line; i <= end_line; i++) {
5106
warning_ignored_lines[warning_code].insert(i);
5107
}
5108
warning_ignore_start_lines[warning_code] = INT_MAX;
5109
}
5110
}
5111
return !has_error;
5112
#else // !DEBUG_ENABLED
5113
// Only available in debug builds.
5114
return true;
5115
#endif // DEBUG_ENABLED
5116
}
5117
5118
bool GDScriptParser::rpc_annotation(AnnotationNode *p_annotation, Node *p_target, ClassNode *p_class) {
5119
ERR_FAIL_COND_V_MSG(p_target->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
5120
5121
FunctionNode *function = static_cast<FunctionNode *>(p_target);
5122
if (function->rpc_config.get_type() != Variant::NIL) {
5123
push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
5124
return false;
5125
}
5126
5127
Dictionary rpc_config;
5128
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
5129
if (!p_annotation->resolved_arguments.is_empty()) {
5130
unsigned char locality_args = 0;
5131
unsigned char permission_args = 0;
5132
unsigned char transfer_mode_args = 0;
5133
5134
for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
5135
if (i == 3) {
5136
rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
5137
continue;
5138
}
5139
5140
String arg = p_annotation->resolved_arguments[i].operator String();
5141
if (arg == "call_local") {
5142
locality_args++;
5143
rpc_config["call_local"] = true;
5144
} else if (arg == "call_remote") {
5145
locality_args++;
5146
rpc_config["call_local"] = false;
5147
} else if (arg == "any_peer") {
5148
permission_args++;
5149
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
5150
} else if (arg == "authority") {
5151
permission_args++;
5152
rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
5153
} else if (arg == "reliable") {
5154
transfer_mode_args++;
5155
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
5156
} else if (arg == "unreliable") {
5157
transfer_mode_args++;
5158
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
5159
} else if (arg == "unreliable_ordered") {
5160
transfer_mode_args++;
5161
rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
5162
} else {
5163
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);
5164
}
5165
}
5166
5167
if (locality_args > 1) {
5168
push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
5169
} else if (permission_args > 1) {
5170
push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
5171
} else if (transfer_mode_args > 1) {
5172
push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
5173
}
5174
}
5175
function->rpc_config = rpc_config;
5176
return true;
5177
}
5178
5179
GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
5180
switch (type) {
5181
case CONSTANT:
5182
return constant->get_datatype();
5183
case VARIABLE:
5184
return variable->get_datatype();
5185
case PARAMETER:
5186
return parameter->get_datatype();
5187
case FOR_VARIABLE:
5188
case PATTERN_BIND:
5189
return bind->get_datatype();
5190
case UNDEFINED:
5191
return DataType();
5192
}
5193
return DataType();
5194
}
5195
5196
String GDScriptParser::SuiteNode::Local::get_name() const {
5197
switch (type) {
5198
case SuiteNode::Local::PARAMETER:
5199
return "parameter";
5200
case SuiteNode::Local::CONSTANT:
5201
return "constant";
5202
case SuiteNode::Local::VARIABLE:
5203
return "variable";
5204
case SuiteNode::Local::FOR_VARIABLE:
5205
return "for loop iterator";
5206
case SuiteNode::Local::PATTERN_BIND:
5207
return "pattern bind";
5208
case SuiteNode::Local::UNDEFINED:
5209
return "<undefined>";
5210
default:
5211
return String();
5212
}
5213
}
5214
5215
String GDScriptParser::DataType::to_string() const {
5216
switch (kind) {
5217
case VARIANT:
5218
return "Variant";
5219
case BUILTIN:
5220
if (builtin_type == Variant::NIL) {
5221
return "null";
5222
}
5223
if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
5224
return vformat("Array[%s]", get_container_element_type(0).to_string());
5225
}
5226
if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
5227
return vformat("Dictionary[%s, %s]", get_container_element_type_or_variant(0).to_string(), get_container_element_type_or_variant(1).to_string());
5228
}
5229
return Variant::get_type_name(builtin_type);
5230
case NATIVE:
5231
if (is_meta_type) {
5232
return GDScriptNativeClass::get_class_static();
5233
}
5234
return native_type.operator String();
5235
case CLASS:
5236
if (class_type->identifier != nullptr) {
5237
return class_type->identifier->name.operator String();
5238
}
5239
return class_type->fqcn;
5240
case SCRIPT: {
5241
if (is_meta_type) {
5242
return script_type.is_valid() ? script_type->get_class_name().operator String() : "";
5243
}
5244
String name = script_type.is_valid() ? script_type->get_name() : "";
5245
if (!name.is_empty()) {
5246
return name;
5247
}
5248
name = script_path;
5249
if (!name.is_empty()) {
5250
return name;
5251
}
5252
return native_type.operator String();
5253
}
5254
case ENUM: {
5255
// native_type contains either the native class defining the enum
5256
// or the fully qualified class name of the script defining the enum
5257
return String(native_type).get_file(); // Remove path, keep filename
5258
}
5259
case RESOLVING:
5260
case UNRESOLVED:
5261
return "<unresolved type>";
5262
}
5263
5264
ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
5265
}
5266
5267
PropertyInfo GDScriptParser::DataType::to_property_info(const String &p_name) const {
5268
PropertyInfo result;
5269
result.name = p_name;
5270
result.usage = PROPERTY_USAGE_NONE;
5271
5272
if (!is_hard_type()) {
5273
result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
5274
return result;
5275
}
5276
5277
switch (kind) {
5278
case BUILTIN:
5279
result.type = builtin_type;
5280
if (builtin_type == Variant::ARRAY && has_container_element_type(0)) {
5281
const DataType elem_type = get_container_element_type(0);
5282
switch (elem_type.kind) {
5283
case BUILTIN:
5284
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5285
result.hint_string = Variant::get_type_name(elem_type.builtin_type);
5286
break;
5287
case NATIVE:
5288
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5289
result.hint_string = elem_type.native_type;
5290
break;
5291
case SCRIPT:
5292
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5293
if (elem_type.script_type.is_valid() && elem_type.script_type->get_global_name() != StringName()) {
5294
result.hint_string = elem_type.script_type->get_global_name();
5295
} else {
5296
result.hint_string = elem_type.native_type;
5297
}
5298
break;
5299
case CLASS:
5300
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5301
if (elem_type.class_type != nullptr && elem_type.class_type->get_global_name() != StringName()) {
5302
result.hint_string = elem_type.class_type->get_global_name();
5303
} else {
5304
result.hint_string = elem_type.native_type;
5305
}
5306
break;
5307
case ENUM:
5308
result.hint = PROPERTY_HINT_ARRAY_TYPE;
5309
result.hint_string = String(elem_type.native_type).replace("::", ".");
5310
break;
5311
case VARIANT:
5312
case RESOLVING:
5313
case UNRESOLVED:
5314
break;
5315
}
5316
} else if (builtin_type == Variant::DICTIONARY && has_container_element_types()) {
5317
const DataType key_type = get_container_element_type_or_variant(0);
5318
const DataType value_type = get_container_element_type_or_variant(1);
5319
if ((key_type.kind == VARIANT && value_type.kind == VARIANT) || key_type.kind == RESOLVING ||
5320
key_type.kind == UNRESOLVED || value_type.kind == RESOLVING || value_type.kind == UNRESOLVED) {
5321
break;
5322
}
5323
String key_hint, value_hint;
5324
switch (key_type.kind) {
5325
case BUILTIN:
5326
key_hint = Variant::get_type_name(key_type.builtin_type);
5327
break;
5328
case NATIVE:
5329
key_hint = key_type.native_type;
5330
break;
5331
case SCRIPT:
5332
if (key_type.script_type.is_valid() && key_type.script_type->get_global_name() != StringName()) {
5333
key_hint = key_type.script_type->get_global_name();
5334
} else {
5335
key_hint = key_type.native_type;
5336
}
5337
break;
5338
case CLASS:
5339
if (key_type.class_type != nullptr && key_type.class_type->get_global_name() != StringName()) {
5340
key_hint = key_type.class_type->get_global_name();
5341
} else {
5342
key_hint = key_type.native_type;
5343
}
5344
break;
5345
case ENUM:
5346
key_hint = String(key_type.native_type).replace("::", ".");
5347
break;
5348
default:
5349
key_hint = "Variant";
5350
break;
5351
}
5352
switch (value_type.kind) {
5353
case BUILTIN:
5354
value_hint = Variant::get_type_name(value_type.builtin_type);
5355
break;
5356
case NATIVE:
5357
value_hint = value_type.native_type;
5358
break;
5359
case SCRIPT:
5360
if (value_type.script_type.is_valid() && value_type.script_type->get_global_name() != StringName()) {
5361
value_hint = value_type.script_type->get_global_name();
5362
} else {
5363
value_hint = value_type.native_type;
5364
}
5365
break;
5366
case CLASS:
5367
if (value_type.class_type != nullptr && value_type.class_type->get_global_name() != StringName()) {
5368
value_hint = value_type.class_type->get_global_name();
5369
} else {
5370
value_hint = value_type.native_type;
5371
}
5372
break;
5373
case ENUM:
5374
value_hint = String(value_type.native_type).replace("::", ".");
5375
break;
5376
default:
5377
value_hint = "Variant";
5378
break;
5379
}
5380
result.hint = PROPERTY_HINT_DICTIONARY_TYPE;
5381
result.hint_string = key_hint + ";" + value_hint;
5382
}
5383
break;
5384
case NATIVE:
5385
result.type = Variant::OBJECT;
5386
if (is_meta_type) {
5387
result.class_name = GDScriptNativeClass::get_class_static();
5388
} else {
5389
result.class_name = native_type;
5390
}
5391
break;
5392
case SCRIPT:
5393
result.type = Variant::OBJECT;
5394
if (is_meta_type) {
5395
result.class_name = script_type.is_valid() ? script_type->get_class_name() : Script::get_class_static();
5396
} else if (script_type.is_valid() && script_type->get_global_name() != StringName()) {
5397
result.class_name = script_type->get_global_name();
5398
} else {
5399
result.class_name = native_type;
5400
}
5401
break;
5402
case CLASS:
5403
result.type = Variant::OBJECT;
5404
if (is_meta_type) {
5405
result.class_name = GDScript::get_class_static();
5406
} else if (class_type != nullptr && class_type->get_global_name() != StringName()) {
5407
result.class_name = class_type->get_global_name();
5408
} else {
5409
result.class_name = native_type;
5410
}
5411
break;
5412
case ENUM:
5413
if (is_meta_type) {
5414
result.type = Variant::DICTIONARY;
5415
} else {
5416
result.type = Variant::INT;
5417
result.usage |= PROPERTY_USAGE_CLASS_IS_ENUM;
5418
result.class_name = String(native_type).replace("::", ".");
5419
}
5420
break;
5421
case VARIANT:
5422
case RESOLVING:
5423
case UNRESOLVED:
5424
result.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
5425
break;
5426
}
5427
5428
return result;
5429
}
5430
5431
static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
5432
switch (p_type) {
5433
case Variant::PACKED_BYTE_ARRAY:
5434
case Variant::PACKED_INT32_ARRAY:
5435
case Variant::PACKED_INT64_ARRAY:
5436
return Variant::INT;
5437
case Variant::PACKED_FLOAT32_ARRAY:
5438
case Variant::PACKED_FLOAT64_ARRAY:
5439
return Variant::FLOAT;
5440
case Variant::PACKED_STRING_ARRAY:
5441
return Variant::STRING;
5442
case Variant::PACKED_VECTOR2_ARRAY:
5443
return Variant::VECTOR2;
5444
case Variant::PACKED_VECTOR3_ARRAY:
5445
return Variant::VECTOR3;
5446
case Variant::PACKED_COLOR_ARRAY:
5447
return Variant::COLOR;
5448
case Variant::PACKED_VECTOR4_ARRAY:
5449
return Variant::VECTOR4;
5450
default:
5451
return Variant::NIL;
5452
}
5453
}
5454
5455
bool GDScriptParser::DataType::is_typed_container_type() const {
5456
return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
5457
}
5458
5459
GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
5460
GDScriptParser::DataType type;
5461
type.kind = GDScriptParser::DataType::BUILTIN;
5462
type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
5463
return type;
5464
}
5465
5466
bool GDScriptParser::DataType::can_reference(const GDScriptParser::DataType &p_other) const {
5467
if (p_other.is_meta_type) {
5468
return false;
5469
} else if (builtin_type != p_other.builtin_type) {
5470
return false;
5471
} else if (builtin_type != Variant::OBJECT) {
5472
return true;
5473
}
5474
5475
if (native_type == StringName()) {
5476
return true;
5477
} else if (p_other.native_type == StringName()) {
5478
return false;
5479
} else if (native_type != p_other.native_type && !ClassDB::is_parent_class(p_other.native_type, native_type)) {
5480
return false;
5481
}
5482
5483
Ref<Script> script = script_type;
5484
if (kind == GDScriptParser::DataType::CLASS && script.is_null()) {
5485
Error err = OK;
5486
Ref<GDScript> scr = GDScriptCache::get_shallow_script(script_path, err);
5487
ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", script_path));
5488
script.reference_ptr(scr->find_class(class_type->fqcn));
5489
}
5490
5491
Ref<Script> script_other = p_other.script_type;
5492
if (p_other.kind == GDScriptParser::DataType::CLASS && script_other.is_null()) {
5493
Error err = OK;
5494
Ref<GDScript> scr = GDScriptCache::get_shallow_script(p_other.script_path, err);
5495
ERR_FAIL_COND_V_MSG(err, false, vformat(R"(Error while getting cache for script "%s".)", p_other.script_path));
5496
script_other.reference_ptr(scr->find_class(p_other.class_type->fqcn));
5497
}
5498
5499
if (script.is_null()) {
5500
return true;
5501
} else if (script_other.is_null()) {
5502
return false;
5503
} else if (script != script_other && !script_other->inherits_script(script)) {
5504
return false;
5505
}
5506
5507
return true;
5508
}
5509
5510
void GDScriptParser::complete_extents(Node *p_node) {
5511
while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
5512
ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
5513
nodes_in_progress.pop_back();
5514
}
5515
if (nodes_in_progress.is_empty()) {
5516
ERR_PRINT("Parser bug: Extents tracking stack is empty.");
5517
} else {
5518
nodes_in_progress.pop_back();
5519
}
5520
}
5521
5522
void GDScriptParser::update_extents(Node *p_node) {
5523
p_node->end_line = previous.end_line;
5524
p_node->end_column = previous.end_column;
5525
}
5526
5527
void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
5528
p_node->start_line = p_token.start_line;
5529
p_node->end_line = p_token.end_line;
5530
p_node->start_column = p_token.start_column;
5531
p_node->end_column = p_token.end_column;
5532
}
5533
5534
void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
5535
if (p_from == nullptr) {
5536
return;
5537
}
5538
p_node->start_line = p_from->start_line;
5539
p_node->end_line = p_from->end_line;
5540
p_node->start_column = p_from->start_column;
5541
p_node->end_column = p_from->end_column;
5542
}
5543
5544
/*---------- PRETTY PRINT FOR DEBUG ----------*/
5545
5546
#ifdef DEBUG_ENABLED
5547
5548
void GDScriptParser::TreePrinter::increase_indent() {
5549
indent_level++;
5550
indent = "";
5551
for (int i = 0; i < indent_level * 4; i++) {
5552
if (i % 4 == 0) {
5553
indent += "|";
5554
} else {
5555
indent += " ";
5556
}
5557
}
5558
}
5559
5560
void GDScriptParser::TreePrinter::decrease_indent() {
5561
indent_level--;
5562
indent = "";
5563
for (int i = 0; i < indent_level * 4; i++) {
5564
if (i % 4 == 0) {
5565
indent += "|";
5566
} else {
5567
indent += " ";
5568
}
5569
}
5570
}
5571
5572
void GDScriptParser::TreePrinter::push_line(const String &p_line) {
5573
if (!p_line.is_empty()) {
5574
push_text(p_line);
5575
}
5576
printed += "\n";
5577
pending_indent = true;
5578
}
5579
5580
void GDScriptParser::TreePrinter::push_text(const String &p_text) {
5581
if (pending_indent) {
5582
printed += indent;
5583
pending_indent = false;
5584
}
5585
printed += p_text;
5586
}
5587
5588
void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
5589
push_text(p_annotation->name);
5590
push_text(" (");
5591
for (int i = 0; i < p_annotation->arguments.size(); i++) {
5592
if (i > 0) {
5593
push_text(" , ");
5594
}
5595
print_expression(p_annotation->arguments[i]);
5596
}
5597
push_line(")");
5598
}
5599
5600
void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
5601
push_text("[ ");
5602
for (int i = 0; i < p_array->elements.size(); i++) {
5603
if (i > 0) {
5604
push_text(" , ");
5605
}
5606
print_expression(p_array->elements[i]);
5607
}
5608
push_text(" ]");
5609
}
5610
5611
void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
5612
push_text("Assert ( ");
5613
print_expression(p_assert->condition);
5614
push_line(" )");
5615
}
5616
5617
void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
5618
switch (p_assignment->assignee->type) {
5619
case Node::IDENTIFIER:
5620
print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
5621
break;
5622
case Node::SUBSCRIPT:
5623
print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
5624
break;
5625
default:
5626
break; // Unreachable.
5627
}
5628
5629
push_text(" ");
5630
switch (p_assignment->operation) {
5631
case AssignmentNode::OP_ADDITION:
5632
push_text("+");
5633
break;
5634
case AssignmentNode::OP_SUBTRACTION:
5635
push_text("-");
5636
break;
5637
case AssignmentNode::OP_MULTIPLICATION:
5638
push_text("*");
5639
break;
5640
case AssignmentNode::OP_DIVISION:
5641
push_text("/");
5642
break;
5643
case AssignmentNode::OP_MODULO:
5644
push_text("%");
5645
break;
5646
case AssignmentNode::OP_POWER:
5647
push_text("**");
5648
break;
5649
case AssignmentNode::OP_BIT_SHIFT_LEFT:
5650
push_text("<<");
5651
break;
5652
case AssignmentNode::OP_BIT_SHIFT_RIGHT:
5653
push_text(">>");
5654
break;
5655
case AssignmentNode::OP_BIT_AND:
5656
push_text("&");
5657
break;
5658
case AssignmentNode::OP_BIT_OR:
5659
push_text("|");
5660
break;
5661
case AssignmentNode::OP_BIT_XOR:
5662
push_text("^");
5663
break;
5664
case AssignmentNode::OP_NONE:
5665
break;
5666
}
5667
push_text("= ");
5668
print_expression(p_assignment->assigned_value);
5669
push_line();
5670
}
5671
5672
void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
5673
push_text("Await ");
5674
print_expression(p_await->to_await);
5675
}
5676
5677
void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
5678
// Surround in parenthesis for disambiguation.
5679
push_text("(");
5680
print_expression(p_binary_op->left_operand);
5681
switch (p_binary_op->operation) {
5682
case BinaryOpNode::OP_ADDITION:
5683
push_text(" + ");
5684
break;
5685
case BinaryOpNode::OP_SUBTRACTION:
5686
push_text(" - ");
5687
break;
5688
case BinaryOpNode::OP_MULTIPLICATION:
5689
push_text(" * ");
5690
break;
5691
case BinaryOpNode::OP_DIVISION:
5692
push_text(" / ");
5693
break;
5694
case BinaryOpNode::OP_MODULO:
5695
push_text(" % ");
5696
break;
5697
case BinaryOpNode::OP_POWER:
5698
push_text(" ** ");
5699
break;
5700
case BinaryOpNode::OP_BIT_LEFT_SHIFT:
5701
push_text(" << ");
5702
break;
5703
case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
5704
push_text(" >> ");
5705
break;
5706
case BinaryOpNode::OP_BIT_AND:
5707
push_text(" & ");
5708
break;
5709
case BinaryOpNode::OP_BIT_OR:
5710
push_text(" | ");
5711
break;
5712
case BinaryOpNode::OP_BIT_XOR:
5713
push_text(" ^ ");
5714
break;
5715
case BinaryOpNode::OP_LOGIC_AND:
5716
push_text(" AND ");
5717
break;
5718
case BinaryOpNode::OP_LOGIC_OR:
5719
push_text(" OR ");
5720
break;
5721
case BinaryOpNode::OP_CONTENT_TEST:
5722
push_text(" IN ");
5723
break;
5724
case BinaryOpNode::OP_COMP_EQUAL:
5725
push_text(" == ");
5726
break;
5727
case BinaryOpNode::OP_COMP_NOT_EQUAL:
5728
push_text(" != ");
5729
break;
5730
case BinaryOpNode::OP_COMP_LESS:
5731
push_text(" < ");
5732
break;
5733
case BinaryOpNode::OP_COMP_LESS_EQUAL:
5734
push_text(" <= ");
5735
break;
5736
case BinaryOpNode::OP_COMP_GREATER:
5737
push_text(" > ");
5738
break;
5739
case BinaryOpNode::OP_COMP_GREATER_EQUAL:
5740
push_text(" >= ");
5741
break;
5742
}
5743
print_expression(p_binary_op->right_operand);
5744
// Surround in parenthesis for disambiguation.
5745
push_text(")");
5746
}
5747
5748
void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
5749
if (p_call->is_super) {
5750
push_text("super");
5751
if (p_call->callee != nullptr) {
5752
push_text(".");
5753
print_expression(p_call->callee);
5754
}
5755
} else {
5756
print_expression(p_call->callee);
5757
}
5758
push_text("( ");
5759
for (int i = 0; i < p_call->arguments.size(); i++) {
5760
if (i > 0) {
5761
push_text(" , ");
5762
}
5763
print_expression(p_call->arguments[i]);
5764
}
5765
push_text(" )");
5766
}
5767
5768
void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
5769
print_expression(p_cast->operand);
5770
push_text(" AS ");
5771
print_type(p_cast->cast_type);
5772
}
5773
5774
void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
5775
for (const AnnotationNode *E : p_class->annotations) {
5776
print_annotation(E);
5777
}
5778
push_text("Class ");
5779
if (p_class->identifier == nullptr) {
5780
push_text("<unnamed>");
5781
} else {
5782
print_identifier(p_class->identifier);
5783
}
5784
5785
if (p_class->extends_used) {
5786
bool first = true;
5787
push_text(" Extends ");
5788
if (!p_class->extends_path.is_empty()) {
5789
push_text(vformat(R"("%s")", p_class->extends_path));
5790
first = false;
5791
}
5792
for (int i = 0; i < p_class->extends.size(); i++) {
5793
if (!first) {
5794
push_text(".");
5795
} else {
5796
first = false;
5797
}
5798
push_text(p_class->extends[i]->name);
5799
}
5800
}
5801
5802
push_line(" :");
5803
5804
increase_indent();
5805
5806
for (int i = 0; i < p_class->members.size(); i++) {
5807
const ClassNode::Member &m = p_class->members[i];
5808
5809
switch (m.type) {
5810
case ClassNode::Member::CLASS:
5811
print_class(m.m_class);
5812
break;
5813
case ClassNode::Member::VARIABLE:
5814
print_variable(m.variable);
5815
break;
5816
case ClassNode::Member::CONSTANT:
5817
print_constant(m.constant);
5818
break;
5819
case ClassNode::Member::SIGNAL:
5820
print_signal(m.signal);
5821
break;
5822
case ClassNode::Member::FUNCTION:
5823
print_function(m.function);
5824
break;
5825
case ClassNode::Member::ENUM:
5826
print_enum(m.m_enum);
5827
break;
5828
case ClassNode::Member::ENUM_VALUE:
5829
break; // Nothing. Will be printed by enum.
5830
case ClassNode::Member::GROUP:
5831
break; // Nothing. Groups are only used by inspector.
5832
case ClassNode::Member::UNDEFINED:
5833
push_line("<unknown member>");
5834
break;
5835
}
5836
}
5837
5838
decrease_indent();
5839
}
5840
5841
void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
5842
push_text("Constant ");
5843
print_identifier(p_constant->identifier);
5844
5845
increase_indent();
5846
5847
push_line();
5848
push_text("= ");
5849
if (p_constant->initializer == nullptr) {
5850
push_text("<missing value>");
5851
} else {
5852
print_expression(p_constant->initializer);
5853
}
5854
decrease_indent();
5855
push_line();
5856
}
5857
5858
void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
5859
push_line("{");
5860
increase_indent();
5861
for (int i = 0; i < p_dictionary->elements.size(); i++) {
5862
print_expression(p_dictionary->elements[i].key);
5863
if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
5864
push_text(" : ");
5865
} else {
5866
push_text(" = ");
5867
}
5868
print_expression(p_dictionary->elements[i].value);
5869
push_line(" ,");
5870
}
5871
decrease_indent();
5872
push_text("}");
5873
}
5874
5875
void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
5876
if (p_expression == nullptr) {
5877
push_text("<invalid expression>");
5878
return;
5879
}
5880
switch (p_expression->type) {
5881
case Node::ARRAY:
5882
print_array(static_cast<ArrayNode *>(p_expression));
5883
break;
5884
case Node::ASSIGNMENT:
5885
print_assignment(static_cast<AssignmentNode *>(p_expression));
5886
break;
5887
case Node::AWAIT:
5888
print_await(static_cast<AwaitNode *>(p_expression));
5889
break;
5890
case Node::BINARY_OPERATOR:
5891
print_binary_op(static_cast<BinaryOpNode *>(p_expression));
5892
break;
5893
case Node::CALL:
5894
print_call(static_cast<CallNode *>(p_expression));
5895
break;
5896
case Node::CAST:
5897
print_cast(static_cast<CastNode *>(p_expression));
5898
break;
5899
case Node::DICTIONARY:
5900
print_dictionary(static_cast<DictionaryNode *>(p_expression));
5901
break;
5902
case Node::GET_NODE:
5903
print_get_node(static_cast<GetNodeNode *>(p_expression));
5904
break;
5905
case Node::IDENTIFIER:
5906
print_identifier(static_cast<IdentifierNode *>(p_expression));
5907
break;
5908
case Node::LAMBDA:
5909
print_lambda(static_cast<LambdaNode *>(p_expression));
5910
break;
5911
case Node::LITERAL:
5912
print_literal(static_cast<LiteralNode *>(p_expression));
5913
break;
5914
case Node::PRELOAD:
5915
print_preload(static_cast<PreloadNode *>(p_expression));
5916
break;
5917
case Node::SELF:
5918
print_self(static_cast<SelfNode *>(p_expression));
5919
break;
5920
case Node::SUBSCRIPT:
5921
print_subscript(static_cast<SubscriptNode *>(p_expression));
5922
break;
5923
case Node::TERNARY_OPERATOR:
5924
print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
5925
break;
5926
case Node::TYPE_TEST:
5927
print_type_test(static_cast<TypeTestNode *>(p_expression));
5928
break;
5929
case Node::UNARY_OPERATOR:
5930
print_unary_op(static_cast<UnaryOpNode *>(p_expression));
5931
break;
5932
default:
5933
push_text(vformat("<unknown expression %d>", p_expression->type));
5934
break;
5935
}
5936
}
5937
5938
void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
5939
push_text("Enum ");
5940
if (p_enum->identifier != nullptr) {
5941
print_identifier(p_enum->identifier);
5942
} else {
5943
push_text("<unnamed>");
5944
}
5945
5946
push_line(" {");
5947
increase_indent();
5948
for (int i = 0; i < p_enum->values.size(); i++) {
5949
const EnumNode::Value &item = p_enum->values[i];
5950
print_identifier(item.identifier);
5951
push_text(" = ");
5952
push_text(itos(item.value));
5953
push_line(" ,");
5954
}
5955
decrease_indent();
5956
push_line("}");
5957
}
5958
5959
void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
5960
push_text("For ");
5961
print_identifier(p_for->variable);
5962
push_text(" IN ");
5963
print_expression(p_for->list);
5964
push_line(" :");
5965
5966
increase_indent();
5967
5968
print_suite(p_for->loop);
5969
5970
decrease_indent();
5971
}
5972
5973
void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
5974
for (const AnnotationNode *E : p_function->annotations) {
5975
print_annotation(E);
5976
}
5977
if (p_function->is_static) {
5978
push_text("Static ");
5979
}
5980
push_text(p_context);
5981
push_text(" ");
5982
if (p_function->identifier) {
5983
print_identifier(p_function->identifier);
5984
} else {
5985
push_text("<anonymous>");
5986
}
5987
push_text("( ");
5988
for (int i = 0; i < p_function->parameters.size(); i++) {
5989
if (i > 0) {
5990
push_text(" , ");
5991
}
5992
print_parameter(p_function->parameters[i]);
5993
}
5994
push_line(" ) :");
5995
increase_indent();
5996
print_suite(p_function->body);
5997
decrease_indent();
5998
}
5999
6000
void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
6001
if (p_get_node->use_dollar) {
6002
push_text("$");
6003
}
6004
push_text(p_get_node->full_path);
6005
}
6006
6007
void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
6008
if (p_identifier != nullptr) {
6009
push_text(p_identifier->name);
6010
} else {
6011
push_text("<invalid identifier>");
6012
}
6013
}
6014
6015
void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
6016
if (p_is_elif) {
6017
push_text("Elif ");
6018
} else {
6019
push_text("If ");
6020
}
6021
print_expression(p_if->condition);
6022
push_line(" :");
6023
6024
increase_indent();
6025
print_suite(p_if->true_block);
6026
decrease_indent();
6027
6028
// FIXME: Properly detect "elif" blocks.
6029
if (p_if->false_block != nullptr) {
6030
push_line("Else :");
6031
increase_indent();
6032
print_suite(p_if->false_block);
6033
decrease_indent();
6034
}
6035
}
6036
6037
void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
6038
print_function(p_lambda->function, "Lambda");
6039
push_text("| captures [ ");
6040
for (int i = 0; i < p_lambda->captures.size(); i++) {
6041
if (i > 0) {
6042
push_text(" , ");
6043
}
6044
push_text(p_lambda->captures[i]->name.operator String());
6045
}
6046
push_line(" ]");
6047
}
6048
6049
void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
6050
// Prefix for string types.
6051
switch (p_literal->value.get_type()) {
6052
case Variant::NODE_PATH:
6053
push_text("^\"");
6054
break;
6055
case Variant::STRING:
6056
push_text("\"");
6057
break;
6058
case Variant::STRING_NAME:
6059
push_text("&\"");
6060
break;
6061
default:
6062
break;
6063
}
6064
push_text(p_literal->value);
6065
// Suffix for string types.
6066
switch (p_literal->value.get_type()) {
6067
case Variant::NODE_PATH:
6068
case Variant::STRING:
6069
case Variant::STRING_NAME:
6070
push_text("\"");
6071
break;
6072
default:
6073
break;
6074
}
6075
}
6076
6077
void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
6078
push_text("Match ");
6079
print_expression(p_match->test);
6080
push_line(" :");
6081
6082
increase_indent();
6083
for (int i = 0; i < p_match->branches.size(); i++) {
6084
print_match_branch(p_match->branches[i]);
6085
}
6086
decrease_indent();
6087
}
6088
6089
void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
6090
for (int i = 0; i < p_match_branch->patterns.size(); i++) {
6091
if (i > 0) {
6092
push_text(" , ");
6093
}
6094
print_match_pattern(p_match_branch->patterns[i]);
6095
}
6096
6097
push_line(" :");
6098
6099
increase_indent();
6100
print_suite(p_match_branch->block);
6101
decrease_indent();
6102
}
6103
6104
void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
6105
switch (p_match_pattern->pattern_type) {
6106
case PatternNode::PT_LITERAL:
6107
print_literal(p_match_pattern->literal);
6108
break;
6109
case PatternNode::PT_WILDCARD:
6110
push_text("_");
6111
break;
6112
case PatternNode::PT_REST:
6113
push_text("..");
6114
break;
6115
case PatternNode::PT_BIND:
6116
push_text("Var ");
6117
print_identifier(p_match_pattern->bind);
6118
break;
6119
case PatternNode::PT_EXPRESSION:
6120
print_expression(p_match_pattern->expression);
6121
break;
6122
case PatternNode::PT_ARRAY:
6123
push_text("[ ");
6124
for (int i = 0; i < p_match_pattern->array.size(); i++) {
6125
if (i > 0) {
6126
push_text(" , ");
6127
}
6128
print_match_pattern(p_match_pattern->array[i]);
6129
}
6130
push_text(" ]");
6131
break;
6132
case PatternNode::PT_DICTIONARY:
6133
push_text("{ ");
6134
for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
6135
if (i > 0) {
6136
push_text(" , ");
6137
}
6138
if (p_match_pattern->dictionary[i].key != nullptr) {
6139
// Key can be null for rest pattern.
6140
print_expression(p_match_pattern->dictionary[i].key);
6141
push_text(" : ");
6142
}
6143
print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
6144
}
6145
push_text(" }");
6146
break;
6147
}
6148
}
6149
6150
void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
6151
print_identifier(p_parameter->identifier);
6152
if (p_parameter->datatype_specifier != nullptr) {
6153
push_text(" : ");
6154
print_type(p_parameter->datatype_specifier);
6155
}
6156
if (p_parameter->initializer != nullptr) {
6157
push_text(" = ");
6158
print_expression(p_parameter->initializer);
6159
}
6160
}
6161
6162
void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
6163
push_text(R"(Preload ( ")");
6164
push_text(p_preload->resolved_path);
6165
push_text(R"(" )");
6166
}
6167
6168
void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
6169
push_text("Return");
6170
if (p_return->return_value != nullptr) {
6171
push_text(" ");
6172
print_expression(p_return->return_value);
6173
}
6174
push_line();
6175
}
6176
6177
void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
6178
push_text("Self(");
6179
if (p_self->current_class->identifier != nullptr) {
6180
print_identifier(p_self->current_class->identifier);
6181
} else {
6182
push_text("<main class>");
6183
}
6184
push_text(")");
6185
}
6186
6187
void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
6188
push_text("Signal ");
6189
print_identifier(p_signal->identifier);
6190
push_text("( ");
6191
for (int i = 0; i < p_signal->parameters.size(); i++) {
6192
print_parameter(p_signal->parameters[i]);
6193
}
6194
push_line(" )");
6195
}
6196
6197
void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
6198
print_expression(p_subscript->base);
6199
if (p_subscript->is_attribute) {
6200
push_text(".");
6201
print_identifier(p_subscript->attribute);
6202
} else {
6203
push_text("[ ");
6204
print_expression(p_subscript->index);
6205
push_text(" ]");
6206
}
6207
}
6208
6209
void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
6210
switch (p_statement->type) {
6211
case Node::ASSERT:
6212
print_assert(static_cast<AssertNode *>(p_statement));
6213
break;
6214
case Node::VARIABLE:
6215
print_variable(static_cast<VariableNode *>(p_statement));
6216
break;
6217
case Node::CONSTANT:
6218
print_constant(static_cast<ConstantNode *>(p_statement));
6219
break;
6220
case Node::IF:
6221
print_if(static_cast<IfNode *>(p_statement));
6222
break;
6223
case Node::FOR:
6224
print_for(static_cast<ForNode *>(p_statement));
6225
break;
6226
case Node::WHILE:
6227
print_while(static_cast<WhileNode *>(p_statement));
6228
break;
6229
case Node::MATCH:
6230
print_match(static_cast<MatchNode *>(p_statement));
6231
break;
6232
case Node::RETURN:
6233
print_return(static_cast<ReturnNode *>(p_statement));
6234
break;
6235
case Node::BREAK:
6236
push_line("Break");
6237
break;
6238
case Node::CONTINUE:
6239
push_line("Continue");
6240
break;
6241
case Node::PASS:
6242
push_line("Pass");
6243
break;
6244
case Node::BREAKPOINT:
6245
push_line("Breakpoint");
6246
break;
6247
case Node::ASSIGNMENT:
6248
print_assignment(static_cast<AssignmentNode *>(p_statement));
6249
break;
6250
default:
6251
if (p_statement->is_expression()) {
6252
print_expression(static_cast<ExpressionNode *>(p_statement));
6253
push_line();
6254
} else {
6255
push_line(vformat("<unknown statement %d>", p_statement->type));
6256
}
6257
break;
6258
}
6259
}
6260
6261
void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
6262
for (int i = 0; i < p_suite->statements.size(); i++) {
6263
print_statement(p_suite->statements[i]);
6264
}
6265
}
6266
6267
void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
6268
// Surround in parenthesis for disambiguation.
6269
push_text("(");
6270
print_expression(p_ternary_op->true_expr);
6271
push_text(") IF (");
6272
print_expression(p_ternary_op->condition);
6273
push_text(") ELSE (");
6274
print_expression(p_ternary_op->false_expr);
6275
push_text(")");
6276
}
6277
6278
void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
6279
if (p_type->type_chain.is_empty()) {
6280
push_text("Void");
6281
} else {
6282
for (int i = 0; i < p_type->type_chain.size(); i++) {
6283
if (i > 0) {
6284
push_text(".");
6285
}
6286
print_identifier(p_type->type_chain[i]);
6287
}
6288
}
6289
}
6290
6291
void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
6292
print_expression(p_test->operand);
6293
push_text(" IS ");
6294
print_type(p_test->test_type);
6295
}
6296
6297
void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
6298
// Surround in parenthesis for disambiguation.
6299
push_text("(");
6300
switch (p_unary_op->operation) {
6301
case UnaryOpNode::OP_POSITIVE:
6302
push_text("+");
6303
break;
6304
case UnaryOpNode::OP_NEGATIVE:
6305
push_text("-");
6306
break;
6307
case UnaryOpNode::OP_LOGIC_NOT:
6308
push_text("NOT");
6309
break;
6310
case UnaryOpNode::OP_COMPLEMENT:
6311
push_text("~");
6312
break;
6313
}
6314
print_expression(p_unary_op->operand);
6315
// Surround in parenthesis for disambiguation.
6316
push_text(")");
6317
}
6318
6319
void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
6320
for (const AnnotationNode *E : p_variable->annotations) {
6321
print_annotation(E);
6322
}
6323
6324
if (p_variable->is_static) {
6325
push_text("Static ");
6326
}
6327
push_text("Variable ");
6328
print_identifier(p_variable->identifier);
6329
6330
push_text(" : ");
6331
if (p_variable->datatype_specifier != nullptr) {
6332
print_type(p_variable->datatype_specifier);
6333
} else if (p_variable->infer_datatype) {
6334
push_text("<inferred type>");
6335
} else {
6336
push_text("Variant");
6337
}
6338
6339
increase_indent();
6340
6341
push_line();
6342
push_text("= ");
6343
if (p_variable->initializer == nullptr) {
6344
push_text("<default value>");
6345
} else {
6346
print_expression(p_variable->initializer);
6347
}
6348
push_line();
6349
6350
if (p_variable->property != VariableNode::PROP_NONE) {
6351
if (p_variable->getter != nullptr) {
6352
push_text("Get");
6353
if (p_variable->property == VariableNode::PROP_INLINE) {
6354
push_line(":");
6355
increase_indent();
6356
print_suite(p_variable->getter->body);
6357
decrease_indent();
6358
} else {
6359
push_line(" =");
6360
increase_indent();
6361
print_identifier(p_variable->getter_pointer);
6362
push_line();
6363
decrease_indent();
6364
}
6365
}
6366
if (p_variable->setter != nullptr) {
6367
push_text("Set (");
6368
if (p_variable->property == VariableNode::PROP_INLINE) {
6369
if (p_variable->setter_parameter != nullptr) {
6370
print_identifier(p_variable->setter_parameter);
6371
} else {
6372
push_text("<missing>");
6373
}
6374
push_line("):");
6375
increase_indent();
6376
print_suite(p_variable->setter->body);
6377
decrease_indent();
6378
} else {
6379
push_line(" =");
6380
increase_indent();
6381
print_identifier(p_variable->setter_pointer);
6382
push_line();
6383
decrease_indent();
6384
}
6385
}
6386
}
6387
6388
decrease_indent();
6389
push_line();
6390
}
6391
6392
void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
6393
push_text("While ");
6394
print_expression(p_while->condition);
6395
push_line(" :");
6396
6397
increase_indent();
6398
print_suite(p_while->loop);
6399
decrease_indent();
6400
}
6401
6402
void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
6403
ClassNode *class_tree = p_parser.get_tree();
6404
ERR_FAIL_NULL_MSG(class_tree, "Parse the code before printing the parse tree.");
6405
6406
if (p_parser.is_tool()) {
6407
push_line("@tool");
6408
}
6409
if (!class_tree->icon_path.is_empty()) {
6410
push_text(R"(@icon (")");
6411
push_text(class_tree->icon_path);
6412
push_line("\")");
6413
}
6414
print_class(class_tree);
6415
6416
print_line(String(printed));
6417
}
6418
6419
#endif // DEBUG_ENABLED
6420
6421