Debian Codegraph @

servers/rendering/shader_preprocessor.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* shader_preprocessor.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 "shader_preprocessor.h"
32 #include "core/math/expression.h"
33
34 const char32_t CURSOR = 0xFFFF;
35
36 // Tokenizer
37
38 void ShaderPreprocessor::Tokenizer::add_generated(const ShaderPreprocessor::Token &p_t) {
39 generated.push_back(p_t);
40 }
41
42 char32_t ShaderPreprocessor::Tokenizer::next() {
43 if (index < size) {
44 return code[index++];
45 }
46 return 0;
47 }
48
49 int ShaderPreprocessor::Tokenizer::get_line() const {
50 return line;
51 }
52
53 int ShaderPreprocessor::Tokenizer::get_index() const {
54 return index;
55 }
56
57 void ShaderPreprocessor::Tokenizer::get_and_clear_generated(LocalVector<char32_t> *r_out) {
58 for (uint32_t i = 0; i < generated.size(); i++) {
59 r_out->push_back(generated[i].text);
60 }
61 generated.clear();
62 }
63
64 void ShaderPreprocessor::Tokenizer::backtrack(char32_t p_what) {
65 while (index >= 0) {
66 char32_t c = code[index];
67 if (c == p_what) {
68 break;
69 }
70 index--;
71 }
72 }
73
74 char32_t ShaderPreprocessor::Tokenizer::peek() {
75 if (index < size) {
76 return code[index];
77 }
78 return 0;
79 }
80
81 int ShaderPreprocessor::Tokenizer::consume_line_continuations(int p_offset) {
82 int skips = 0;
83
84 for (int i = index + p_offset; i < size; i++) {
85 char32_t c = code[i];
86 if (c == '\\') {
87 if (i + 1 < size && code[i + 1] == '\n') {
88 // This line ends with "\" and "\n" continuation.
89 add_generated(Token('\n', line));
90 line++;
91 skips++;
92
93 i = i + 2;
94 index = i;
95 } else {
96 break;
97 }
98 } else if (!is_whitespace(c)) {
99 break;
100 }
101 }
102 return skips;
103 }
104
105 LocalVector<ShaderPreprocessor::Token> ShaderPreprocessor::Tokenizer::advance(char32_t p_what) {
106 LocalVector<ShaderPreprocessor::Token> tokens;
107
108 while (index < size) {
109 char32_t c = code[index++];
110 if (c == '\\' && consume_line_continuations(-1) > 0) {
111 continue;
112 }
113
114 if (c == '\n') {
115 add_generated(ShaderPreprocessor::Token('\n', line));
116 line++;
117 }
118
119 tokens.push_back(ShaderPreprocessor::Token(c, line));
120
121 if (c == p_what || c == 0) {
122 return tokens;
123 }
124 }
125 return LocalVector<ShaderPreprocessor::Token>();
126 }
127
128 void ShaderPreprocessor::Tokenizer::skip_whitespace() {
129 while (is_char_space(peek())) {
130 next();
131 }
132 }
133
134 bool ShaderPreprocessor::Tokenizer::consume_empty_line() {
135 // Read until newline and return true if the content was all whitespace/empty.
136 return tokens_to_string(advance('\n')).strip_edges().is_empty();
137 }
138
139 String ShaderPreprocessor::Tokenizer::get_identifier(bool *r_is_cursor, bool p_started) {
140 if (r_is_cursor != nullptr) {
141 *r_is_cursor = false;
142 }
143
144 LocalVector<char32_t> text;
145
146 while (true) {
147 char32_t c = peek();
148 if (c == '\\' && consume_line_continuations(0) > 0) {
149 continue;
150 }
151
152 if (is_char_end(c) || c == '(' || c == ')' || c == ',' || c == ';') {
153 break;
154 }
155
156 if (is_whitespace(c) && p_started) {
157 break;
158 }
159 if (!is_whitespace(c)) {
160 p_started = true;
161 }
162
163 char32_t n = next();
164 if (n == CURSOR) {
165 if (r_is_cursor != nullptr) {
166 *r_is_cursor = true;
167 }
168 } else {
169 if (p_started) {
170 text.push_back(n);
171 }
172 }
173 }
174
175 String id = vector_to_string(text);
176 if (!id.is_valid_ascii_identifier()) {
177 return "";
178 }
179
180 return id;
181 }
182
183 String ShaderPreprocessor::Tokenizer::peek_identifier() {
184 const int original = index;
185 const int original_line = line;
186 String id = get_identifier();
187 index = original;
188 line = original_line;
189 return id;
190 }
191
192 ShaderPreprocessor::Token ShaderPreprocessor::Tokenizer::get_token() {
193 while (index < size) {
194 const char32_t c = code[index++];
195 const Token t = ShaderPreprocessor::Token(c, line);
196
197 switch (c) {
198 case ' ':
199 case '\t':
200 skip_whitespace();
201 return ShaderPreprocessor::Token(' ', line);
202 case '\n':
203 line++;
204 return t;
205 default:
206 return t;
207 }
208 }
209 return ShaderPreprocessor::Token(char32_t(0), line);
210 }
211
212 ShaderPreprocessor::Tokenizer::Tokenizer(const String &p_code) {
213 code = p_code;
214 line = 0;
215 index = 0;
216 size = code.size();
217 }
218
219 // ShaderPreprocessor::CommentRemover
220
221 String ShaderPreprocessor::CommentRemover::get_error() const {
222 if (comments_open != 0) {
223 return "Block comment mismatch";
224 }
225 return "";
226 }
227
228 int ShaderPreprocessor::CommentRemover::get_error_line() const {
229 if (comments_open != 0) {
230 return comment_line_open;
231 }
232 return -1;
233 }
234
235 char32_t ShaderPreprocessor::CommentRemover::peek() const {
236 if (index < code.size()) {
237 return code[index];
238 }
239 return 0;
240 }
241
242 bool ShaderPreprocessor::CommentRemover::advance(char32_t p_what) {
243 while (index < code.size()) {
244 char32_t c = code[index++];
245
246 if (c == '\n') {
247 line++;
248 stripped.push_back('\n');
249 }
250
251 if (c == p_what) {
252 return true;
253 }
254 }
255 return false;
256 }
257
258 String ShaderPreprocessor::CommentRemover::strip() {
259 stripped.clear();
260 index = 0;
261 line = 0;
262 comment_line_open = 0;
263 comments_open = 0;
264 strings_open = 0;
265
266 while (index < code.size()) {
267 char32_t c = code[index++];
268
269 if (c == CURSOR) {
270 // Cursor. Maintain.
271 stripped.push_back(c);
272 } else if (c == '"') {
273 if (strings_open <= 0) {
274 strings_open++;
275 } else {
276 strings_open--;
277 }
278 stripped.push_back(c);
279 } else if (c == '/' && strings_open == 0) {
280 char32_t p = peek();
281 if (p == '/') { // Single line comment.
282 advance('\n');
283 } else if (p == '*') { // Start of a block comment.
284 index++;
285 comment_line_open = line;
286 comments_open++;
287 while (advance('*')) {
288 if (peek() == '/') { // End of a block comment.
289 comments_open--;
290 index++;
291 break;
292 }
293 }
294 } else {
295 stripped.push_back(c);
296 }
297 } else if (c == '*' && strings_open == 0) {
298 if (peek() == '/') { // Unmatched end of a block comment.
299 comment_line_open = line;
300 comments_open--;
301 } else {
302 stripped.push_back(c);
303 }
304 } else if (c == '\n') {
305 line++;
306 stripped.push_back(c);
307 } else {
308 stripped.push_back(c);
309 }
310 }
311 return vector_to_string(stripped);
312 }
313
314 ShaderPreprocessor::CommentRemover::CommentRemover(const String &p_code) {
315 code = p_code;
316 index = 0;
317 line = 0;
318 comment_line_open = 0;
319 comments_open = 0;
320 strings_open = 0;
321 }
322
323 // ShaderPreprocessor::Token
324
325 ShaderPreprocessor::Token::Token() {
326 text = 0;
327 line = -1;
328 }
329
330 ShaderPreprocessor::Token::Token(char32_t p_text, int p_line) {
331 text = p_text;
332 line = p_line;
333 }
334
335 // ShaderPreprocessor
336
337 bool ShaderPreprocessor::is_char_word(char32_t p_char) {
338 if ((p_char >= '0' && p_char <= '9') ||
339 (p_char >= 'a' && p_char <= 'z') ||
340 (p_char >= 'A' && p_char <= 'Z') ||
341 p_char == '_') {
342 return true;
343 }
344
345 return false;
346 }
347
348 bool ShaderPreprocessor::is_char_space(char32_t p_char) {
349 return p_char == ' ' || p_char == '\t';
350 }
351
352 bool ShaderPreprocessor::is_char_end(char32_t p_char) {
353 return p_char == '\n' || p_char == 0;
354 }
355
356 String ShaderPreprocessor::vector_to_string(const LocalVector<char32_t> &p_v, int p_start, int p_end) {
357 const int stop = (p_end == -1) ? p_v.size() : p_end;
358 const int count = stop - p_start;
359
360 String result;
361 result.resize_uninitialized(count + 1);
362 for (int i = 0; i < count; i++) {
363 result[i] = p_v[p_start + i];
364 }
365 result[count] = 0; // Ensure string is null terminated for length() to work.
366 return result;
367 }
368
369 String ShaderPreprocessor::tokens_to_string(const LocalVector<Token> &p_tokens) {
370 LocalVector<char32_t> result;
371 for (const Token &token : p_tokens) {
372 result.push_back(token.text);
373 }
374 return vector_to_string(result);
375 }
376
377 void ShaderPreprocessor::process_directive(Tokenizer *p_tokenizer) {
378 bool is_cursor;
379 String directive = p_tokenizer->get_identifier(&is_cursor, true);
380 if (is_cursor) {
381 state->completion_type = COMPLETION_TYPE_DIRECTIVE;
382 }
383
384 if (directive == "if") {
385 process_if(p_tokenizer);
386 } else if (directive == "ifdef") {
387 process_ifdef(p_tokenizer);
388 } else if (directive == "ifndef") {
389 process_ifndef(p_tokenizer);
390 } else if (directive == "elif") {
391 process_elif(p_tokenizer);
392 } else if (directive == "else") {
393 process_else(p_tokenizer);
394 } else if (directive == "endif") {
395 process_endif(p_tokenizer);
396 } else if (directive == "error") {
397 process_error(p_tokenizer);
398 } else if (directive == "define") {
399 process_define(p_tokenizer);
400 } else if (directive == "undef") {
401 process_undef(p_tokenizer);
402 } else if (directive == "include") {
403 process_include(p_tokenizer);
404 } else if (directive == "pragma") {
405 process_pragma(p_tokenizer);
406 } else {
407 set_error(RTR("Unknown directive."), p_tokenizer->get_line());
408 }
409 }
410
411 void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
412 const int line = p_tokenizer->get_line();
413
414 String label = p_tokenizer->get_identifier();
415 if (label.is_empty()) {
416 set_error(RTR("Invalid macro name."), line);
417 return;
418 }
419
420 if (state->defines.has(label)) {
421 set_error(RTR("Macro redefinition."), line);
422 return;
423 }
424
425 Vector<String> args;
426 if (p_tokenizer->peek() == '(') {
427 // Macro has arguments.
428 p_tokenizer->get_token();
429
430 while (true) {
431 String name = p_tokenizer->get_identifier();
432 if (name.is_empty()) {
433 set_error(RTR("Invalid argument name."), line);
434 return;
435 }
436 args.push_back(name);
437
438 p_tokenizer->skip_whitespace();
439 char32_t next = p_tokenizer->get_token().text;
440 if (next == ')') {
441 break;
442 } else if (next != ',') {
443 set_error(RTR("Expected a comma in the macro argument list."), line);
444 return;
445 }
446 }
447 }
448
449 String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
450 if (body.begins_with("##")) {
451 set_error(RTR("'##' must not appear at beginning of macro expansion."), line);
452 return;
453 }
454 if (body.ends_with("##")) {
455 set_error(RTR("'##' must not appear at end of macro expansion."), line);
456 return;
457 }
458
459 Define *define = memnew(Define);
460 if (!args.is_empty()) {
461 define->arguments = args;
462 }
463 define->body = body;
464 state->defines[label] = define;
465 }
466
467 void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
468 const int line = p_tokenizer->get_line();
469
470 if (state->current_branch == nullptr || state->current_branch->else_defined) {
471 set_error(vformat(RTR("Unmatched '%s' directive."), "elif"), line);
472 return;
473 }
474 if (state->previous_region != nullptr) {
475 state->previous_region->to_line = line - 1;
476 }
477
478 String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
479 if (body.is_empty()) {
480 set_error(RTR("Missing condition."), line);
481 return;
482 }
483
484 Error error = expand_condition(body, line, body);
485 if (error != OK) {
486 return;
487 }
488
489 error = expand_macros(body, line, body);
490 if (error != OK) {
491 return;
492 }
493
494 Expression expression;
495 Vector<String> names;
496 error = expression.parse(body, names);
497 if (error != OK) {
498 set_error(expression.get_error_text(), line);
499 return;
500 }
501
502 Variant v = expression.execute(Array(), nullptr, false);
503 if (v.get_type() == Variant::NIL) {
504 set_error(RTR("Condition evaluation error."), line);
505 return;
506 }
507
508 bool skip = false;
509 for (int i = 0; i < state->current_branch->conditions.size(); i++) {
510 if (state->current_branch->conditions[i]) {
511 skip = true;
512 break;
513 }
514 }
515
516 bool success = !skip && v.booleanize();
517 start_branch_condition(p_tokenizer, success, true);
518
519 if (state->save_regions) {
520 add_region(line + 1, success, state->previous_region->parent);
521 }
522 }
523
524 void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
525 const int line = p_tokenizer->get_line();
526
527 if (state->current_branch == nullptr || state->current_branch->else_defined) {
528 set_error(vformat(RTR("Unmatched '%s' directive."), "else"), line);
529 return;
530 }
531 if (state->previous_region != nullptr) {
532 state->previous_region->to_line = line - 1;
533 }
534
535 if (!p_tokenizer->consume_empty_line()) {
536 set_error(vformat(RTR("Invalid '%s' directive."), "else"), line);
537 }
538
539 bool skip = false;
540 for (int i = 0; i < state->current_branch->conditions.size(); i++) {
541 if (state->current_branch->conditions[i]) {
542 skip = true;
543 break;
544 }
545 }
546 state->current_branch->else_defined = true;
547
548 if (state->save_regions) {
549 add_region(line + 1, !skip, state->previous_region->parent);
550 }
551
552 if (skip) {
553 Vector<String> ends;
554 ends.push_back("endif");
555 // Legacy return value.
556 _ALLOW_DISCARD_ next_directive(p_tokenizer, ends);
557 }
558 }
559
560 void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
561 const int line = p_tokenizer->get_line();
562
563 state->condition_depth--;
564 if (state->condition_depth < 0) {
565 set_error(vformat(RTR("Unmatched '%s' directive."), "endif"), line);
566 return;
567 }
568 if (state->previous_region != nullptr) {
569 state->previous_region->to_line = line - 1;
570 state->previous_region = state->previous_region->parent;
571 }
572
573 if (!p_tokenizer->consume_empty_line()) {
574 set_error(vformat(RTR("Invalid '%s' directive."), "endif"), line);
575 }
576
577 state->current_branch = state->current_branch->parent;
578 state->branches.pop_back();
579 }
580
581 void ShaderPreprocessor::process_error(Tokenizer *p_tokenizer) {
582 const int line = p_tokenizer->get_line();
583
584 const String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
585 if (body.is_empty()) {
586 set_error(" ", line);
587 } else {
588 set_error(body, line);
589 }
590
591 if (!p_tokenizer->consume_empty_line()) {
592 set_error(vformat(RTR("Invalid '%s' directive."), "error"), line);
593 }
594 }
595
596 void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
597 const int line = p_tokenizer->get_line();
598
599 String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
600 if (body.is_empty()) {
601 set_error(RTR("Missing condition."), line);
602 return;
603 }
604
605 Error error = expand_condition(body, line, body);
606 if (error != OK) {
607 return;
608 }
609
610 error = expand_macros(body, line, body);
611 if (error != OK) {
612 return;
613 }
614
615 Expression expression;
616 Vector<String> names;
617 error = expression.parse(body, names);
618 if (error != OK) {
619 set_error(expression.get_error_text(), line);
620 return;
621 }
622
623 Variant v = expression.execute(Array(), nullptr, false);
624 if (v.get_type() == Variant::NIL) {
625 set_error(RTR("Condition evaluation error."), line);
626 return;
627 }
628
629 bool success = v.booleanize();
630 start_branch_condition(p_tokenizer, success);
631
632 if (state->save_regions) {
633 add_region(line + 1, success, state->previous_region);
634 }
635 }
636
637 void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
638 const int line = p_tokenizer->get_line();
639 bool is_cursor = false;
640
641 String label = p_tokenizer->get_identifier(&is_cursor);
642 if (label.is_empty()) {
643 set_error(RTR("Invalid macro name."), line);
644 return;
645 }
646
647 if (is_cursor) {
648 state->completion_show_defines = true;
649 }
650
651 if (!p_tokenizer->consume_empty_line()) {
652 set_error(vformat(RTR("Invalid '%s' directive."), "ifdef"), line);
653 return;
654 }
655
656 bool success = state->defines.has(label);
657 start_branch_condition(p_tokenizer, success);
658
659 if (state->save_regions) {
660 add_region(line + 1, success, state->previous_region);
661 }
662 }
663
664 void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
665 const int line = p_tokenizer->get_line();
666
667 String label = p_tokenizer->get_identifier();
668 if (label.is_empty()) {
669 set_error(RTR("Invalid macro name."), line);
670 return;
671 }
672
673 if (!p_tokenizer->consume_empty_line()) {
674 set_error(vformat(RTR("Invalid '%s' directive."), "ifndef"), line);
675 return;
676 }
677
678 bool success = !state->defines.has(label);
679 start_branch_condition(p_tokenizer, success);
680
681 if (state->save_regions) {
682 add_region(line + 1, success, state->previous_region);
683 }
684 }
685
686 void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
687 const int line = p_tokenizer->get_line();
688
689 p_tokenizer->advance('"');
690 String path = tokens_to_string(p_tokenizer->advance('"'));
691 for (int i = 0; i < path.length(); i++) {
692 if (path[i] == '\n') {
693 break; //stop parsing
694 }
695 if (path[i] == CURSOR) {
696 state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
697 break;
698 }
699 }
700 path = path.substr(0, path.length() - 1);
701
702 if (path.is_empty() || !p_tokenizer->consume_empty_line()) {
703 set_error(RTR("Invalid path."), line);
704 return;
705 }
706
707 path = path.simplify_path();
708 if (path.is_relative_path()) {
709 path = state->current_filename.get_base_dir().path_join(path);
710 }
711
712 if (!ResourceLoader::exists(path)) {
713 set_error(RTR("Shader include file does not exist:") + " " + path, line);
714 return;
715 }
716
717 Ref<Resource> res = ResourceLoader::load(path);
718 if (res.is_null()) {
719 set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
720 return;
721 }
722
723 Ref<ShaderInclude> shader_inc = res;
724 if (shader_inc.is_null()) {
725 set_error(RTR("Shader include resource type is wrong."), line);
726 return;
727 }
728
729 String included = shader_inc->get_code();
730 if (!included.is_empty()) {
731 uint64_t code_hash = included.hash64();
732 if (state->cyclic_include_hashes.find(code_hash)) {
733 set_error(RTR("Cyclic include found") + ": " + path, line);
734 return;
735 }
736 }
737
738 state->shader_includes.insert(shader_inc);
739
740 const String real_path = shader_inc->get_path();
741 if (state->includes.has(real_path)) {
742 // Already included, skip.
743 // This is a valid check because 2 separate include paths could use some
744 // of the same shared functions from a common shader include.
745 return;
746 }
747
748 // Mark as included.
749 state->includes.insert(real_path);
750
751 state->include_depth++;
752 if (state->include_depth > 25) {
753 set_error(RTR("Shader max include depth exceeded."), line);
754 return;
755 }
756
757 String old_filename = state->current_filename;
758 state->current_filename = real_path;
759 ShaderPreprocessor processor;
760
761 int prev_condition_depth = state->condition_depth;
762 state->condition_depth = 0;
763
764 FilePosition fp;
765 fp.file = state->current_filename;
766 fp.line = line + 1;
767 state->include_positions.push_back(fp);
768
769 String result;
770 processor.preprocess(state, included, result);
771 add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
772 add_to_output(result);
773 add_to_output("\n@@<" + real_path + "\n"); // Add token for exit include path.
774
775 // Reset to last include if there are no errors. We want to use this as context.
776 if (state->error.is_empty()) {
777 state->current_filename = old_filename;
778 state->include_positions.pop_back();
779 } else {
780 return;
781 }
782
783 state->include_depth--;
784 state->condition_depth = prev_condition_depth;
785 }
786
787 void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
788 const int line = p_tokenizer->get_line();
789
790 bool is_cursor;
791 const String label = p_tokenizer->get_identifier(&is_cursor);
792 if (is_cursor) {
793 state->completion_type = COMPLETION_TYPE_PRAGMA;
794 }
795
796 if (label.is_empty()) {
797 set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
798 return;
799 }
800
801 // Explicitly handle pragma values here.
802 // If more pragma options are created, then refactor into a more defined structure.
803 if (label == "disable_preprocessor") {
804 state->disabled = true;
805 } else {
806 set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
807 return;
808 }
809
810 if (!p_tokenizer->consume_empty_line()) {
811 set_error(vformat(RTR("Invalid '%s' directive."), "pragma"), line);
812 return;
813 }
814 }
815
816 void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
817 const int line = p_tokenizer->get_line();
818 const String label = p_tokenizer->get_identifier();
819 if (label.is_empty() || !p_tokenizer->consume_empty_line()) {
820 set_error(vformat(RTR("Invalid '%s' directive."), "undef"), line);
821 return;
822 }
823
824 if (state->defines.has(label)) {
825 if (state->defines[label]->is_builtin) {
826 set_error(vformat(RTR("Cannot use '%s' on built-in define."), "undef"), line);
827 return;
828 }
829
830 memdelete(state->defines[label]);
831 state->defines.erase(label);
832 }
833 }
834
835 void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
836 Region region;
837 region.file = state->current_filename;
838 region.enabled = p_enabled;
839 region.from_line = p_line;
840 region.parent = p_parent_region;
841 state->previous_region = &state->regions[region.file].push_back(region)->get();
842 }
843
844 void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
845 if (!p_continue) {
846 state->condition_depth++;
847 state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
848 } else {
849 state->current_branch->conditions.push_back(p_success);
850 }
851 if (!p_success) {
852 Vector<String> ends;
853 ends.push_back("elif");
854 ends.push_back("else");
855 ends.push_back("endif");
856 // Legacy return value.
857 _ALLOW_DISCARD_ next_directive(p_tokenizer, ends);
858 }
859 }
860
861 void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
862 String line = vector_to_string(output, p_start, output.size());
863
864 Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
865 if (error != OK) {
866 return;
867 }
868
869 output.resize(p_start);
870
871 add_to_output(line);
872 }
873
874 Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
875 // Checks bracket count to be even + check the cursor position.
876 {
877 int bracket_start_count = 0;
878 int bracket_end_count = 0;
879
880 for (int i = 0; i < p_string.size(); i++) {
881 switch (p_string[i]) {
882 case CURSOR:
883 state->completion_type = COMPLETION_TYPE_CONDITION;
884 state->completion_show_defines = true;
885 break;
886 case '(':
887 bracket_start_count++;
888 break;
889 case ')':
890 bracket_end_count++;
891 break;
892 }
893 }
894 if (bracket_start_count > bracket_end_count) {
895 _set_expected_error(")", p_line);
896 return FAILED;
897 }
898 if (bracket_end_count > bracket_start_count) {
899 _set_expected_error("(", p_line);
900 return FAILED;
901 }
902 }
903
904 String result = p_string;
905
906 int index = 0;
907 int index_start = 0;
908 int index_end = 0;
909
910 while (find_match(result, "defined", index, index_start)) {
911 bool open_bracket = false;
912 bool found_word = false;
913 bool word_completed = false;
914
915 LocalVector<char32_t> text;
916 int post_bracket_index = -1;
917 int size = result.size();
918
919 for (int i = (index_start - 1); i < size; i++) {
920 char32_t c = result[i];
921 if (c == 0) {
922 if (found_word) {
923 word_completed = true;
924 }
925 break;
926 }
927 char32_t cs[] = { c, '\0' };
928 String s = String(cs);
929 bool is_space = is_char_space(c);
930
931 if (word_completed) {
932 if (c == ')') {
933 continue;
934 }
935 if (c == '|' || c == '&') {
936 if (open_bracket) {
937 _set_unexpected_token_error(s, p_line);
938 return FAILED;
939 }
940 break;
941 } else if (!is_space) {
942 _set_unexpected_token_error(s, p_line);
943 return FAILED;
944 }
945 } else if (is_space) {
946 if (found_word && !open_bracket) {
947 index_end = i;
948 word_completed = true;
949 }
950 } else if (c == '(') {
951 if (open_bracket) {
952 _set_unexpected_token_error(s, p_line);
953 return FAILED;
954 }
955 open_bracket = true;
956 } else if (c == ')') {
957 if (open_bracket) {
958 if (!found_word) {
959 _set_unexpected_token_error(s, p_line);
960 return FAILED;
961 }
962 open_bracket = false;
963 post_bracket_index = i + 1;
964 } else {
965 index_end = i;
966 }
967 word_completed = true;
968 } else if (is_char_word(c)) {
969 text.push_back(c);
970 found_word = true;
971 } else {
972 _set_unexpected_token_error(s, p_line);
973 return FAILED;
974 }
975 }
976
977 if (word_completed) {
978 if (open_bracket) {
979 _set_expected_error(")", p_line);
980 return FAILED;
981 }
982 if (post_bracket_index != -1) {
983 index_end = post_bracket_index;
984 }
985
986 String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
987 String temp = result;
988
989 result = result.substr(0, index) + body;
990 index_start = result.length();
991 if (index_end > 0) {
992 result += temp.substr(index_end);
993 }
994 } else {
995 set_error(RTR("Invalid macro name."), p_line);
996 return FAILED;
997 }
998 }
999 r_expanded = result;
1000 return OK;
1001 }
1002
1003 Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
1004 String iterative = p_string;
1005 int pass_count = 0;
1006 bool expanded = true;
1007
1008 while (expanded) {
1009 expanded = false;
1010
1011 // As long as we find something to expand, keep going.
1012 for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
1013 if (expand_macros_once(iterative, p_line, E, iterative)) {
1014 expanded = true;
1015 }
1016 }
1017
1018 pass_count++;
1019 if (pass_count > 50) {
1020 set_error(RTR("Macro expansion limit exceeded."), p_line);
1021 break;
1022 }
1023 }
1024
1025 r_expanded = iterative;
1026
1027 if (!state->error.is_empty()) {
1028 return FAILED;
1029 }
1030 return OK;
1031 }
1032
1033 bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
1034 String result = p_line;
1035
1036 const String &key = p_define_pair->key();
1037 const Define *define = p_define_pair->value();
1038
1039 int index_start = 0;
1040 int index = 0;
1041 if (find_match(result, key, index, index_start)) {
1042 String body = define->body;
1043 if (define->arguments.size() > 0) {
1044 // Complex macro with arguments.
1045
1046 int args_start = -1;
1047 int args_end = -1;
1048 int brackets_open = 0;
1049 Vector<String> args;
1050 for (int i = index_start - 1; i < p_line.length(); i++) {
1051 bool add_argument = false;
1052 bool reached_end = false;
1053 char32_t c = p_line[i];
1054
1055 if (c == '(') {
1056 brackets_open++;
1057 if (brackets_open == 1) {
1058 args_start = i + 1;
1059 args_end = -1;
1060 }
1061 } else if (c == ')') {
1062 brackets_open--;
1063 if (brackets_open == 0) {
1064 args_end = i;
1065 add_argument = true;
1066 reached_end = true;
1067 }
1068 } else if (c == ',') {
1069 if (brackets_open == 1) {
1070 args_end = i;
1071 add_argument = true;
1072 }
1073 }
1074
1075 if (add_argument) {
1076 if (args_start == -1 || args_end == -1) {
1077 set_error(RTR("Invalid macro argument list."), p_line_number);
1078 return false;
1079 }
1080
1081 String arg = p_line.substr(args_start, args_end - args_start).strip_edges();
1082 if (arg.is_empty()) {
1083 set_error(RTR("Invalid macro argument."), p_line_number);
1084 return false;
1085 }
1086 args.append(arg);
1087
1088 args_start = args_end + 1;
1089 }
1090
1091 if (reached_end) {
1092 break;
1093 }
1094 }
1095
1096 if (args.size() != define->arguments.size()) {
1097 set_error(RTR("Invalid macro argument count."), p_line_number);
1098 return false;
1099 }
1100
1101 // Insert macro arguments into the body.
1102 for (int i = 0; i < args.size(); i++) {
1103 String arg_name = define->arguments[i];
1104 int arg_index_start = 0;
1105 int arg_index = 0;
1106 while (find_match(body, arg_name, arg_index, arg_index_start)) {
1107 body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length());
1108 // Manually reset arg_index_start to where the arg value of the define finishes.
1109 // This ensures we don't skip the other args of this macro in the string.
1110 arg_index_start = arg_index + args[i].length() + 1;
1111 }
1112 }
1113
1114 concatenate_macro_body(body);
1115
1116 result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1);
1117 } else {
1118 concatenate_macro_body(body);
1119
1120 result = result.substr(0, index) + " " + body + " " + result.substr(index + key.length());
1121 }
1122
1123 r_expanded = result;
1124 return true;
1125 }
1126
1127 return false;
1128 }
1129
1130 bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
1131 // Looks for value in string and then determines if the boundaries
1132 // are non-word characters. This method semi-emulates \b in regex.
1133 r_index = p_string.find(p_value, r_index_start);
1134 while (r_index > -1) {
1135 if (r_index > 0) {
1136 if (is_char_word(p_string[r_index - 1])) {
1137 r_index_start = r_index + 1;
1138 r_index = p_string.find(p_value, r_index_start);
1139 continue;
1140 }
1141 }
1142
1143 if (r_index + p_value.length() < p_string.length()) {
1144 if (is_char_word(p_string[r_index + p_value.length()])) {
1145 r_index_start = r_index + p_value.length() + 1;
1146 r_index = p_string.find(p_value, r_index_start);
1147 continue;
1148 }
1149 }
1150
1151 // Return and shift index start automatically for next call.
1152 r_index_start = r_index + p_value.length() + 1;
1153 return true;
1154 }
1155
1156 return false;
1157 }
1158
1159 void ShaderPreprocessor::concatenate_macro_body(String &r_body) {
1160 int index_start = r_body.find("##");
1161 while (index_start > -1) {
1162 int index_end = index_start + 2; // First character after ##.
1163 // The macro was checked during creation so this should never happen.
1164 ERR_FAIL_INDEX(index_end, r_body.size());
1165
1166 // If there more than two # in a row, then it's not a concatenation.
1167 bool is_concat = true;
1168 while (index_end <= r_body.length() && r_body[index_end] == '#') {
1169 index_end++;
1170 is_concat = false;
1171 }
1172 if (!is_concat) {
1173 index_start = r_body.find("##", index_end);
1174 continue;
1175 }
1176
1177 // Skip whitespace after ##.
1178 while (index_end < r_body.length() && is_char_space(r_body[index_end])) {
1179 index_end++;
1180 }
1181
1182 // Skip whitespace before ##.
1183 while (index_start >= 1 && is_char_space(r_body[index_start - 1])) {
1184 index_start--;
1185 }
1186
1187 r_body = r_body.substr(0, index_start) + r_body.substr(index_end);
1188
1189 index_start = r_body.find("##", index_start);
1190 }
1191 }
1192
1193 String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
1194 const int line = p_tokenizer->get_line();
1195 int nesting = 0;
1196
1197 while (true) {
1198 p_tokenizer->advance('#');
1199
1200 String id = p_tokenizer->peek_identifier();
1201 if (id.is_empty()) {
1202 break;
1203 }
1204
1205 if (nesting == 0) {
1206 for (int i = 0; i < p_directives.size(); i++) {
1207 if (p_directives[i] == id) {
1208 p_tokenizer->backtrack('#');
1209 return id;
1210 }
1211 }
1212 }
1213
1214 if (id == "ifdef" || id == "ifndef" || id == "if") {
1215 nesting++;
1216 } else if (id == "endif") {
1217 nesting--;
1218 }
1219 }
1220
1221 set_error(RTR("Can't find matching branch directive."), line);
1222 return "";
1223 }
1224
1225 void ShaderPreprocessor::add_to_output(const String &p_str) {
1226 for (int i = 0; i < p_str.length(); i++) {
1227 output.push_back(p_str[i]);
1228 }
1229 }
1230
1231 void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
1232 if (state->error.is_empty()) {
1233 state->error = p_error;
1234 FilePosition fp;
1235 fp.file = state->current_filename;
1236 fp.line = p_line + 1;
1237 state->include_positions.push_back(fp);
1238 }
1239 }
1240
1241 ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
1242 ShaderPreprocessor::Define *define = memnew(Define);
1243 define->body = p_body;
1244 return define;
1245 }
1246
1247 void ShaderPreprocessor::insert_builtin_define(String p_name, String p_value, State &p_state) {
1248 Define *define = memnew(Define);
1249 define->is_builtin = true;
1250 define->body = p_value;
1251 p_state.defines[p_name] = define;
1252 }
1253
1254 void ShaderPreprocessor::clear_state() {
1255 if (state != nullptr) {
1256 for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
1257 memdelete(E->get());
1258 }
1259 state->defines.clear();
1260 }
1261 state = nullptr;
1262 }
1263
1264 Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
1265 output.clear();
1266
1267 state = p_state;
1268
1269 CommentRemover remover(p_code);
1270 String stripped = remover.strip();
1271 String error = remover.get_error();
1272 if (!error.is_empty()) {
1273 set_error(error, remover.get_error_line());
1274 return FAILED;
1275 }
1276
1277 // Track code hashes to prevent cyclic include.
1278 uint64_t code_hash = p_code.hash64();
1279 state->cyclic_include_hashes.push_back(code_hash);
1280
1281 Tokenizer p_tokenizer(stripped);
1282 int last_size = 0;
1283 bool has_symbols_before_directive = false;
1284
1285 while (true) {
1286 const Token &t = p_tokenizer.get_token();
1287
1288 if (t.text == 0) {
1289 break;
1290 }
1291
1292 // Add autogenerated tokens if there are any.
1293 p_tokenizer.get_and_clear_generated(&output);
1294
1295 if (state->disabled) {
1296 // Preprocessor was disabled.
1297 // Read the rest of the file into the output.
1298 output.push_back(t.text);
1299 continue;
1300 }
1301
1302 if (t.text == '#') {
1303 if (has_symbols_before_directive) {
1304 set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
1305 state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
1306 return FAILED;
1307 }
1308 process_directive(&p_tokenizer);
1309 } else {
1310 if (is_char_end(t.text)) {
1311 expand_output_macros(last_size, p_tokenizer.get_line());
1312 last_size = output.size();
1313 has_symbols_before_directive = false;
1314 } else if (!is_char_space(t.text)) {
1315 has_symbols_before_directive = true;
1316 }
1317 output.push_back(t.text);
1318 }
1319
1320 if (!state->error.is_empty()) {
1321 state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
1322 return FAILED;
1323 }
1324 }
1325 state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
1326
1327 if (!state->disabled) {
1328 if (state->condition_depth != 0) {
1329 set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
1330 return FAILED;
1331 }
1332
1333 expand_output_macros(last_size, p_tokenizer.get_line());
1334 }
1335
1336 r_result = vector_to_string(output);
1337
1338 return OK;
1339 }
1340
1341 Error ShaderPreprocessor::preprocess(const String &p_code, const String &p_filename, String &r_result, String *r_error_text, List<FilePosition> *r_error_position, List<Region> *r_regions, HashSet<Ref<ShaderInclude>> *r_includes, List<ScriptLanguage::CodeCompletionOption> *r_completion_options, List<ScriptLanguage::CodeCompletionOption> *r_completion_defines, IncludeCompletionFunction p_include_completion_func) {
1342 State pp_state;
1343 if (!p_filename.is_empty()) {
1344 pp_state.current_filename = p_filename;
1345 pp_state.save_regions = r_regions != nullptr;
1346 }
1347
1348 // Built-in defines.
1349 {
1350 const String rendering_method = OS::get_singleton()->get_current_rendering_method();
1351
1352 if (rendering_method == "forward_plus") {
1353 insert_builtin_define("CURRENT_RENDERER", _MKSTR(2), pp_state);
1354 } else if (rendering_method == "mobile") {
1355 insert_builtin_define("CURRENT_RENDERER", _MKSTR(1), pp_state);
1356 } else { // gl_compatibility
1357 insert_builtin_define("CURRENT_RENDERER", _MKSTR(0), pp_state);
1358 }
1359
1360 insert_builtin_define("RENDERER_COMPATIBILITY", _MKSTR(0), pp_state);
1361 insert_builtin_define("RENDERER_MOBILE", _MKSTR(1), pp_state);
1362 insert_builtin_define("RENDERER_FORWARD_PLUS", _MKSTR(2), pp_state);
1363 }
1364
1365 Error err = preprocess(&pp_state, p_code, r_result);
1366 if (err != OK) {
1367 if (r_error_text) {
1368 *r_error_text = pp_state.error;
1369 }
1370 if (r_error_position) {
1371 *r_error_position = pp_state.include_positions;
1372 }
1373 }
1374 if (r_regions) {
1375 *r_regions = pp_state.regions[p_filename];
1376 }
1377 if (r_includes) {
1378 *r_includes = pp_state.shader_includes;
1379 }
1380
1381 if (r_completion_defines) {
1382 for (const KeyValue<String, Define *> &E : state->defines) {
1383 ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
1384 r_completion_defines->push_back(option);
1385 }
1386 }
1387
1388 if (r_completion_options) {
1389 switch (pp_state.completion_type) {
1390 case COMPLETION_TYPE_DIRECTIVE: {
1391 List<String> options;
1392 get_keyword_list(&options, true, true);
1393
1394 for (const String &E : options) {
1395 ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
1396 r_completion_options->push_back(option);
1397 }
1398
1399 } break;
1400 case COMPLETION_TYPE_PRAGMA: {
1401 List<String> options;
1402 ShaderPreprocessor::get_pragma_list(&options);
1403
1404 for (const String &E : options) {
1405 ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
1406 r_completion_options->push_back(option);
1407 }
1408
1409 } break;
1410 case COMPLETION_TYPE_CONDITION: {
1411 ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
1412 r_completion_options->push_back(option);
1413
1414 } break;
1415 case COMPLETION_TYPE_INCLUDE_PATH: {
1416 if (p_include_completion_func && r_completion_options) {
1417 p_include_completion_func(r_completion_options);
1418 }
1419
1420 } break;
1421 default: {
1422 }
1423 }
1424 }
1425
1426 if (state->completion_show_defines) {
1427 for (const KeyValue<String, Define *> &E : state->defines) {
1428 ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
1429 r_completion_options->push_back(option);
1430 }
1431 }
1432
1433 clear_state();
1434
1435 return err;
1436 }
1437
1438 void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
1439 r_keywords->push_back("define");
1440 if (!p_ignore_context_keywords) {
1441 r_keywords->push_back("defined");
1442 }
1443 r_keywords->push_back("elif");
1444 if (p_include_shader_keywords) {
1445 r_keywords->push_back("else");
1446 }
1447 r_keywords->push_back("endif");
1448 r_keywords->push_back("error");
1449 if (p_include_shader_keywords) {
1450 r_keywords->push_back("if");
1451 }
1452 r_keywords->push_back("ifdef");
1453 r_keywords->push_back("ifndef");
1454 r_keywords->push_back("include");
1455 r_keywords->push_back("pragma");
1456 r_keywords->push_back("undef");
1457 }
1458
1459 void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
1460 r_pragmas->push_back("disable_preprocessor");
1461 }
1462
1463 ShaderPreprocessor::ShaderPreprocessor() {
1464 }
1465
1466 ShaderPreprocessor::~ShaderPreprocessor() {
1467 }