shader_preprocessor.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. /*************************************************************************/
  2. /* shader_preprocessor.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "shader_preprocessor.h"
  31. #include "core/math/expression.h"
  32. const char32_t CURSOR = 0xFFFF;
  33. // Tokenizer
  34. void ShaderPreprocessor::Tokenizer::add_generated(const ShaderPreprocessor::Token &p_t) {
  35. generated.push_back(p_t);
  36. }
  37. char32_t ShaderPreprocessor::Tokenizer::next() {
  38. if (index < size) {
  39. return code[index++];
  40. }
  41. return 0;
  42. }
  43. int ShaderPreprocessor::Tokenizer::get_line() const {
  44. return line;
  45. }
  46. int ShaderPreprocessor::Tokenizer::get_index() const {
  47. return index;
  48. }
  49. void ShaderPreprocessor::Tokenizer::get_and_clear_generated(Vector<ShaderPreprocessor::Token> *r_out) {
  50. for (int i = 0; i < generated.size(); i++) {
  51. r_out->push_back(generated[i]);
  52. }
  53. generated.clear();
  54. }
  55. void ShaderPreprocessor::Tokenizer::backtrack(char32_t p_what) {
  56. while (index >= 0) {
  57. char32_t c = code[index];
  58. if (c == p_what) {
  59. break;
  60. }
  61. index--;
  62. }
  63. }
  64. char32_t ShaderPreprocessor::Tokenizer::peek() {
  65. if (index < size) {
  66. return code[index];
  67. }
  68. return 0;
  69. }
  70. LocalVector<ShaderPreprocessor::Token> ShaderPreprocessor::Tokenizer::advance(char32_t p_what) {
  71. LocalVector<ShaderPreprocessor::Token> tokens;
  72. while (index < size) {
  73. char32_t c = code[index++];
  74. tokens.push_back(ShaderPreprocessor::Token(c, line));
  75. if (c == '\n') {
  76. add_generated(ShaderPreprocessor::Token('\n', line));
  77. line++;
  78. }
  79. if (c == p_what || c == 0) {
  80. return tokens;
  81. }
  82. }
  83. return LocalVector<ShaderPreprocessor::Token>();
  84. }
  85. void ShaderPreprocessor::Tokenizer::skip_whitespace() {
  86. while (is_char_space(peek())) {
  87. next();
  88. }
  89. }
  90. String ShaderPreprocessor::Tokenizer::get_identifier(bool *r_is_cursor, bool p_started) {
  91. if (r_is_cursor != nullptr) {
  92. *r_is_cursor = false;
  93. }
  94. LocalVector<char32_t> text;
  95. while (true) {
  96. char32_t c = peek();
  97. if (is_char_end(c) || c == '(' || c == ')' || c == ',' || c == ';') {
  98. break;
  99. }
  100. if (is_whitespace(c) && p_started) {
  101. break;
  102. }
  103. if (!is_whitespace(c)) {
  104. p_started = true;
  105. }
  106. char32_t n = next();
  107. if (n == CURSOR) {
  108. if (r_is_cursor != nullptr) {
  109. *r_is_cursor = true;
  110. }
  111. } else {
  112. if (p_started) {
  113. text.push_back(n);
  114. }
  115. }
  116. }
  117. String id = vector_to_string(text);
  118. if (!id.is_valid_identifier()) {
  119. return "";
  120. }
  121. return id;
  122. }
  123. String ShaderPreprocessor::Tokenizer::peek_identifier() {
  124. const int original = index;
  125. String id = get_identifier();
  126. index = original;
  127. return id;
  128. }
  129. ShaderPreprocessor::Token ShaderPreprocessor::Tokenizer::get_token() {
  130. while (index < size) {
  131. const char32_t c = code[index++];
  132. const Token t = ShaderPreprocessor::Token(c, line);
  133. switch (c) {
  134. case ' ':
  135. case '\t':
  136. skip_whitespace();
  137. return ShaderPreprocessor::Token(' ', line);
  138. case '\n':
  139. line++;
  140. return t;
  141. default:
  142. return t;
  143. }
  144. }
  145. return ShaderPreprocessor::Token(char32_t(0), line);
  146. }
  147. ShaderPreprocessor::Tokenizer::Tokenizer(const String &p_code) {
  148. code = p_code;
  149. line = 0;
  150. index = 0;
  151. size = code.size();
  152. }
  153. // ShaderPreprocessor::CommentRemover
  154. String ShaderPreprocessor::CommentRemover::get_error() const {
  155. if (comments_open != 0) {
  156. return "Block comment mismatch";
  157. }
  158. return "";
  159. }
  160. int ShaderPreprocessor::CommentRemover::get_error_line() const {
  161. if (comments_open != 0) {
  162. return comment_line_open;
  163. }
  164. return -1;
  165. }
  166. char32_t ShaderPreprocessor::CommentRemover::peek() const {
  167. if (index < code.size()) {
  168. return code[index];
  169. }
  170. return 0;
  171. }
  172. bool ShaderPreprocessor::CommentRemover::advance(char32_t p_what) {
  173. while (index < code.size()) {
  174. char32_t c = code[index++];
  175. if (c == '\n') {
  176. line++;
  177. stripped.push_back('\n');
  178. }
  179. if (c == p_what) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. }
  185. String ShaderPreprocessor::CommentRemover::strip() {
  186. stripped.clear();
  187. index = 0;
  188. line = 0;
  189. comment_line_open = 0;
  190. comments_open = 0;
  191. strings_open = 0;
  192. while (index < code.size()) {
  193. char32_t c = code[index++];
  194. if (c == CURSOR) {
  195. // Cursor. Maintain.
  196. stripped.push_back(c);
  197. } else if (c == '"') {
  198. if (strings_open <= 0) {
  199. strings_open++;
  200. } else {
  201. strings_open--;
  202. }
  203. stripped.push_back(c);
  204. } else if (c == '/' && strings_open == 0) {
  205. char32_t p = peek();
  206. if (p == '/') { // Single line comment.
  207. advance('\n');
  208. } else if (p == '*') { // Start of a block comment.
  209. index++;
  210. comment_line_open = line;
  211. comments_open++;
  212. while (advance('*')) {
  213. if (peek() == '/') { // End of a block comment.
  214. comments_open--;
  215. index++;
  216. break;
  217. }
  218. }
  219. } else {
  220. stripped.push_back(c);
  221. }
  222. } else if (c == '*' && strings_open == 0) {
  223. if (peek() == '/') { // Unmatched end of a block comment.
  224. comment_line_open = line;
  225. comments_open--;
  226. } else {
  227. stripped.push_back(c);
  228. }
  229. } else if (c == '\n') {
  230. line++;
  231. stripped.push_back(c);
  232. } else {
  233. stripped.push_back(c);
  234. }
  235. }
  236. return vector_to_string(stripped);
  237. }
  238. ShaderPreprocessor::CommentRemover::CommentRemover(const String &p_code) {
  239. code = p_code;
  240. index = 0;
  241. line = 0;
  242. comment_line_open = 0;
  243. comments_open = 0;
  244. strings_open = 0;
  245. }
  246. // ShaderPreprocessor::Token
  247. ShaderPreprocessor::Token::Token() {
  248. text = 0;
  249. line = -1;
  250. }
  251. ShaderPreprocessor::Token::Token(char32_t p_text, int p_line) {
  252. text = p_text;
  253. line = p_line;
  254. }
  255. // ShaderPreprocessor
  256. bool ShaderPreprocessor::is_char_word(char32_t p_char) {
  257. if ((p_char >= '0' && p_char <= '9') ||
  258. (p_char >= 'a' && p_char <= 'z') ||
  259. (p_char >= 'A' && p_char <= 'Z') ||
  260. p_char == '_') {
  261. return true;
  262. }
  263. return false;
  264. }
  265. bool ShaderPreprocessor::is_char_space(char32_t p_char) {
  266. return p_char == ' ' || p_char == '\t';
  267. }
  268. bool ShaderPreprocessor::is_char_end(char32_t p_char) {
  269. return p_char == '\n' || p_char == 0;
  270. }
  271. String ShaderPreprocessor::vector_to_string(const LocalVector<char32_t> &p_v, int p_start, int p_end) {
  272. const int stop = (p_end == -1) ? p_v.size() : p_end;
  273. const int count = stop - p_start;
  274. String result;
  275. result.resize(count + 1);
  276. for (int i = 0; i < count; i++) {
  277. result[i] = p_v[p_start + i];
  278. }
  279. result[count] = 0; // Ensure string is null terminated for length() to work.
  280. return result;
  281. }
  282. String ShaderPreprocessor::tokens_to_string(const LocalVector<Token> &p_tokens) {
  283. LocalVector<char32_t> result;
  284. for (uint32_t i = 0; i < p_tokens.size(); i++) {
  285. result.push_back(p_tokens[i].text);
  286. }
  287. return vector_to_string(result);
  288. }
  289. void ShaderPreprocessor::process_directive(Tokenizer *p_tokenizer) {
  290. bool is_cursor;
  291. String directive = p_tokenizer->get_identifier(&is_cursor, true);
  292. if (is_cursor) {
  293. state->completion_type = COMPLETION_TYPE_DIRECTIVE;
  294. }
  295. if (directive == "if") {
  296. if (check_directive_before_type(p_tokenizer, directive)) {
  297. process_if(p_tokenizer);
  298. }
  299. } else if (directive == "ifdef") {
  300. if (check_directive_before_type(p_tokenizer, directive)) {
  301. process_ifdef(p_tokenizer);
  302. }
  303. } else if (directive == "ifndef") {
  304. if (check_directive_before_type(p_tokenizer, directive)) {
  305. process_ifndef(p_tokenizer);
  306. }
  307. } else if (directive == "else") {
  308. if (check_directive_before_type(p_tokenizer, directive)) {
  309. process_else(p_tokenizer);
  310. }
  311. } else if (directive == "endif") {
  312. if (check_directive_before_type(p_tokenizer, directive)) {
  313. process_endif(p_tokenizer);
  314. }
  315. } else if (directive == "define") {
  316. if (check_directive_before_type(p_tokenizer, directive)) {
  317. process_define(p_tokenizer);
  318. }
  319. } else if (directive == "undef") {
  320. if (check_directive_before_type(p_tokenizer, directive)) {
  321. process_undef(p_tokenizer);
  322. }
  323. } else if (directive == "include") {
  324. if (check_directive_before_type(p_tokenizer, directive)) {
  325. process_include(p_tokenizer);
  326. }
  327. } else if (directive == "pragma") {
  328. if (check_directive_before_type(p_tokenizer, directive)) {
  329. process_pragma(p_tokenizer);
  330. }
  331. } else {
  332. set_error(RTR("Unknown directive."), p_tokenizer->get_line());
  333. }
  334. }
  335. void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
  336. const int line = p_tokenizer->get_line();
  337. String label = p_tokenizer->get_identifier();
  338. if (label.is_empty()) {
  339. set_error(RTR("Invalid macro name."), line);
  340. return;
  341. }
  342. if (state->defines.has(label)) {
  343. set_error(RTR("Macro redefinition."), line);
  344. return;
  345. }
  346. if (p_tokenizer->peek() == '(') {
  347. // Macro has arguments.
  348. p_tokenizer->get_token();
  349. Vector<String> args;
  350. while (true) {
  351. String name = p_tokenizer->get_identifier();
  352. if (name.is_empty()) {
  353. set_error(RTR("Invalid argument name."), line);
  354. return;
  355. }
  356. args.push_back(name);
  357. p_tokenizer->skip_whitespace();
  358. char32_t next = p_tokenizer->get_token().text;
  359. if (next == ')') {
  360. break;
  361. } else if (next != ',') {
  362. set_error(RTR("Expected a comma in the macro argument list."), line);
  363. return;
  364. }
  365. }
  366. Define *define = memnew(Define);
  367. define->arguments = args;
  368. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  369. state->defines[label] = define;
  370. } else {
  371. // Simple substitution macro.
  372. Define *define = memnew(Define);
  373. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  374. state->defines[label] = define;
  375. }
  376. }
  377. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  378. if (state->skip_stack_else.is_empty()) {
  379. set_error(RTR("Unmatched else."), p_tokenizer->get_line());
  380. return;
  381. }
  382. p_tokenizer->advance('\n');
  383. bool skip = state->skip_stack_else[state->skip_stack_else.size() - 1];
  384. state->skip_stack_else.remove_at(state->skip_stack_else.size() - 1);
  385. Vector<SkippedCondition *> vec = state->skipped_conditions[state->current_include];
  386. int index = vec.size() - 1;
  387. if (index >= 0) {
  388. SkippedCondition *cond = vec[index];
  389. if (cond->end_line == -1) {
  390. cond->end_line = p_tokenizer->get_line();
  391. }
  392. }
  393. if (skip) {
  394. Vector<String> ends;
  395. ends.push_back("endif");
  396. next_directive(p_tokenizer, ends);
  397. }
  398. }
  399. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  400. state->condition_depth--;
  401. if (state->condition_depth < 0) {
  402. set_error(RTR("Unmatched endif."), p_tokenizer->get_line());
  403. return;
  404. }
  405. Vector<SkippedCondition *> vec = state->skipped_conditions[state->current_include];
  406. int index = vec.size() - 1;
  407. if (index >= 0) {
  408. SkippedCondition *cond = vec[index];
  409. if (cond->end_line == -1) {
  410. cond->end_line = p_tokenizer->get_line();
  411. }
  412. }
  413. p_tokenizer->advance('\n');
  414. }
  415. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  416. int line = p_tokenizer->get_line();
  417. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  418. if (body.is_empty()) {
  419. set_error(RTR("Missing condition."), line);
  420. return;
  421. }
  422. Error error = expand_macros(body, line, body);
  423. if (error != OK) {
  424. return;
  425. }
  426. Expression expression;
  427. Vector<String> names;
  428. error = expression.parse(body, names);
  429. if (error != OK) {
  430. set_error(expression.get_error_text(), line);
  431. return;
  432. }
  433. Variant v = expression.execute(Array(), nullptr, false);
  434. if (v.get_type() == Variant::NIL) {
  435. set_error(RTR("Condition evaluation error."), line);
  436. return;
  437. }
  438. bool success = v.booleanize();
  439. start_branch_condition(p_tokenizer, success);
  440. }
  441. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  442. const int line = p_tokenizer->get_line();
  443. String label = p_tokenizer->get_identifier();
  444. if (label.is_empty()) {
  445. set_error(RTR("Invalid macro name."), line);
  446. return;
  447. }
  448. p_tokenizer->skip_whitespace();
  449. if (!is_char_end(p_tokenizer->peek())) {
  450. set_error(RTR("Invalid ifdef."), line);
  451. return;
  452. }
  453. p_tokenizer->advance('\n');
  454. bool success = state->defines.has(label);
  455. start_branch_condition(p_tokenizer, success);
  456. }
  457. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  458. const int line = p_tokenizer->get_line();
  459. String label = p_tokenizer->get_identifier();
  460. if (label.is_empty()) {
  461. set_error(RTR("Invalid macro name."), line);
  462. return;
  463. }
  464. p_tokenizer->skip_whitespace();
  465. if (!is_char_end(p_tokenizer->peek())) {
  466. set_error(RTR("Invalid ifndef."), line);
  467. return;
  468. }
  469. p_tokenizer->advance('\n');
  470. bool success = !state->defines.has(label);
  471. start_branch_condition(p_tokenizer, success);
  472. }
  473. void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
  474. const int line = p_tokenizer->get_line();
  475. p_tokenizer->advance('"');
  476. String path = tokens_to_string(p_tokenizer->advance('"'));
  477. for (int i = 0; i < path.length(); i++) {
  478. if (path[i] == '\n') {
  479. break; //stop parsing
  480. }
  481. if (path[i] == CURSOR) {
  482. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  483. break;
  484. }
  485. }
  486. path = path.substr(0, path.length() - 1);
  487. p_tokenizer->skip_whitespace();
  488. if (path.is_empty() || !is_char_end(p_tokenizer->peek())) {
  489. set_error(RTR("Invalid path."), line);
  490. return;
  491. }
  492. Ref<Resource> res = ResourceLoader::load(path);
  493. if (res.is_null()) {
  494. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  495. return;
  496. }
  497. Ref<ShaderInclude> shader_inc = res;
  498. if (shader_inc.is_null()) {
  499. set_error(RTR("Shader include resource type is wrong."), line);
  500. return;
  501. }
  502. String included = shader_inc->get_code();
  503. if (!included.is_empty()) {
  504. uint64_t code_hash = included.hash64();
  505. if (state->cyclic_include_hashes.find(code_hash)) {
  506. set_error(RTR("Cyclic include found."), line);
  507. return;
  508. }
  509. }
  510. state->shader_includes.insert(shader_inc);
  511. const String real_path = shader_inc->get_path();
  512. if (state->includes.has(real_path)) {
  513. // Already included, skip.
  514. // This is a valid check because 2 separate include paths could use some
  515. // of the same shared functions from a common shader include.
  516. return;
  517. }
  518. // Mark as included.
  519. state->includes.insert(real_path);
  520. state->include_depth++;
  521. if (state->include_depth > 25) {
  522. set_error(RTR("Shader max include depth exceeded."), line);
  523. return;
  524. }
  525. String old_include = state->current_include;
  526. state->current_include = real_path;
  527. ShaderPreprocessor processor;
  528. int prev_condition_depth = state->condition_depth;
  529. state->condition_depth = 0;
  530. FilePosition fp;
  531. fp.file = state->current_include;
  532. fp.line = line;
  533. state->include_positions.push_back(fp);
  534. String result;
  535. processor.preprocess(state, included, result);
  536. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  537. add_to_output(result);
  538. add_to_output("\n@@<\n"); // Add token for exit include path
  539. // Reset to last include if there are no errors. We want to use this as context.
  540. if (state->error.is_empty()) {
  541. state->current_include = old_include;
  542. state->include_positions.pop_back();
  543. } else {
  544. return;
  545. }
  546. state->include_depth--;
  547. state->condition_depth = prev_condition_depth;
  548. }
  549. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  550. const int line = p_tokenizer->get_line();
  551. bool is_cursor;
  552. const String label = p_tokenizer->get_identifier(&is_cursor);
  553. if (is_cursor) {
  554. state->completion_type = COMPLETION_TYPE_PRAGMA;
  555. }
  556. if (label.is_empty()) {
  557. set_error(RTR("Invalid pragma directive."), line);
  558. return;
  559. }
  560. // Rxplicitly handle pragma values here.
  561. // If more pragma options are created, then refactor into a more defined structure.
  562. if (label == "disable_preprocessor") {
  563. state->disabled = true;
  564. } else {
  565. set_error(RTR("Invalid pragma directive."), line);
  566. return;
  567. }
  568. p_tokenizer->advance('\n');
  569. }
  570. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  571. const int line = p_tokenizer->get_line();
  572. const String label = p_tokenizer->get_identifier();
  573. if (label.is_empty() || !state->defines.has(label)) {
  574. set_error(RTR("Invalid name."), line);
  575. return;
  576. }
  577. p_tokenizer->skip_whitespace();
  578. if (!is_char_end(p_tokenizer->peek())) {
  579. set_error(RTR("Invalid undef."), line);
  580. return;
  581. }
  582. memdelete(state->defines[label]);
  583. state->defines.erase(label);
  584. }
  585. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success) {
  586. state->condition_depth++;
  587. if (p_success) {
  588. state->skip_stack_else.push_back(true);
  589. } else {
  590. SkippedCondition *cond = memnew(SkippedCondition());
  591. cond->start_line = p_tokenizer->get_line();
  592. state->skipped_conditions[state->current_include].push_back(cond);
  593. Vector<String> ends;
  594. ends.push_back("else");
  595. ends.push_back("endif");
  596. if (next_directive(p_tokenizer, ends) == "else") {
  597. state->skip_stack_else.push_back(false);
  598. } else {
  599. state->skip_stack_else.push_back(true);
  600. }
  601. }
  602. }
  603. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  604. String line = vector_to_string(output, p_start, output.size());
  605. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  606. if (error != OK) {
  607. return;
  608. }
  609. output.resize(p_start);
  610. add_to_output(line);
  611. }
  612. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  613. Vector<Pair<String, Define *>> active_defines;
  614. active_defines.resize(state->defines.size());
  615. int index = 0;
  616. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  617. active_defines.set(index++, Pair<String, Define *>(E->key(), E->get()));
  618. }
  619. return expand_macros(p_string, p_line, active_defines, r_expanded);
  620. }
  621. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, Vector<Pair<String, Define *>> p_defines, String &r_expanded) {
  622. r_expanded = p_string;
  623. // When expanding macros we must only evaluate them once.
  624. // Later we continue expanding but with the already
  625. // evaluated macros removed.
  626. for (int i = 0; i < p_defines.size(); i++) {
  627. Pair<String, Define *> define_pair = p_defines[i];
  628. Error error = expand_macros_once(r_expanded, p_line, define_pair, r_expanded);
  629. if (error != OK) {
  630. return error;
  631. }
  632. // Remove expanded macro and recursively replace remaining.
  633. p_defines.remove_at(i);
  634. return expand_macros(r_expanded, p_line, p_defines, r_expanded);
  635. }
  636. return OK;
  637. }
  638. Error ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, Pair<String, Define *> p_define_pair, String &r_expanded) {
  639. String result = p_line;
  640. const String &key = p_define_pair.first;
  641. const Define *define = p_define_pair.second;
  642. int index_start = 0;
  643. int index = 0;
  644. while (find_match(result, key, index, index_start)) {
  645. String body = define->body;
  646. if (define->arguments.size() > 0) {
  647. // Complex macro with arguments.
  648. int args_start = index + key.length();
  649. int args_end = p_line.find(")", args_start);
  650. if (args_start == -1 || args_end == -1) {
  651. set_error(RTR("Missing macro argument parenthesis."), p_line_number);
  652. return FAILED;
  653. }
  654. String values = result.substr(args_start + 1, args_end - (args_start + 1));
  655. Vector<String> args = values.split(",");
  656. if (args.size() != define->arguments.size()) {
  657. set_error(RTR("Invalid macro argument count."), p_line_number);
  658. return FAILED;
  659. }
  660. // Insert macro arguments into the body.
  661. for (int i = 0; i < args.size(); i++) {
  662. String arg_name = define->arguments[i];
  663. int arg_index_start = 0;
  664. int arg_index = 0;
  665. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  666. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  667. // Manually reset arg_index_start to where the arg value of the define finishes.
  668. // This ensures we don't skip the other args of this macro in the string.
  669. arg_index_start = arg_index + args[i].length() + 1;
  670. }
  671. }
  672. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  673. } else {
  674. result = result.substr(0, index) + body + result.substr(index + key.length(), result.length() - (index + key.length()));
  675. // Manually reset index_start to where the body value of the define finishes.
  676. // This ensures we don't skip another instance of this macro in the string.
  677. index_start = index + body.length() + 1;
  678. break;
  679. }
  680. }
  681. r_expanded = result;
  682. return OK;
  683. }
  684. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  685. // Looks for value in string and then determines if the boundaries
  686. // are non-word characters. This method semi-emulates \b in regex.
  687. r_index = p_string.find(p_value, r_index_start);
  688. while (r_index > -1) {
  689. if (r_index > 0) {
  690. if (is_char_word(p_string[r_index - 1])) {
  691. r_index_start = r_index + 1;
  692. r_index = p_string.find(p_value, r_index_start);
  693. continue;
  694. }
  695. }
  696. if (r_index + p_value.length() < p_string.length()) {
  697. if (is_char_word(p_string[r_index + p_value.length()])) {
  698. r_index_start = r_index + p_value.length() + 1;
  699. r_index = p_string.find(p_value, r_index_start);
  700. continue;
  701. }
  702. }
  703. // Return and shift index start automatically for next call.
  704. r_index_start = r_index + p_value.length() + 1;
  705. return true;
  706. }
  707. return false;
  708. }
  709. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  710. const int line = p_tokenizer->get_line();
  711. int nesting = 0;
  712. while (true) {
  713. p_tokenizer->advance('#');
  714. String id = p_tokenizer->peek_identifier();
  715. if (id.is_empty()) {
  716. break;
  717. }
  718. if (nesting == 0) {
  719. for (int i = 0; i < p_directives.size(); i++) {
  720. if (p_directives[i] == id) {
  721. p_tokenizer->backtrack('#');
  722. return id;
  723. }
  724. }
  725. }
  726. if (id == "ifdef" || id == "ifndef" || id == "if") {
  727. nesting++;
  728. } else if (id == "endif") {
  729. nesting--;
  730. }
  731. }
  732. set_error(RTR("Can't find matching branch directive."), line);
  733. return "";
  734. }
  735. void ShaderPreprocessor::add_to_output(const String &p_str) {
  736. for (int i = 0; i < p_str.length(); i++) {
  737. output.push_back(p_str[i]);
  738. }
  739. }
  740. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  741. if (state->error.is_empty()) {
  742. state->error = p_error;
  743. FilePosition fp;
  744. fp.line = p_line + 1;
  745. state->include_positions.push_back(fp);
  746. }
  747. }
  748. bool ShaderPreprocessor::check_directive_before_type(Tokenizer *p_tokenizer, const String &p_directive) {
  749. if (p_tokenizer->get_index() < state->shader_type_pos) {
  750. set_error(vformat(RTR("`#%s` may not be defined before `shader_type`."), p_directive), p_tokenizer->get_line());
  751. return false;
  752. }
  753. return true;
  754. }
  755. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  756. ShaderPreprocessor::Define *define = memnew(Define);
  757. define->body = p_body;
  758. return define;
  759. }
  760. void ShaderPreprocessor::clear() {
  761. if (state_owner && state != nullptr) {
  762. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  763. memdelete(E->get());
  764. }
  765. for (const RBMap<String, Vector<SkippedCondition *>>::Element *E = state->skipped_conditions.front(); E; E = E->next()) {
  766. for (SkippedCondition *condition : E->get()) {
  767. memdelete(condition);
  768. }
  769. }
  770. memdelete(state);
  771. }
  772. state_owner = false;
  773. state = nullptr;
  774. }
  775. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  776. clear();
  777. output.clear();
  778. state = p_state;
  779. CommentRemover remover(p_code);
  780. String stripped = remover.strip();
  781. String error = remover.get_error();
  782. if (!error.is_empty()) {
  783. set_error(error, remover.get_error_line());
  784. return FAILED;
  785. }
  786. // Track code hashes to prevent cyclic include.
  787. uint64_t code_hash = p_code.hash64();
  788. state->cyclic_include_hashes.push_back(code_hash);
  789. Tokenizer p_tokenizer(stripped);
  790. int last_size = 0;
  791. bool has_symbols_before_directive = false;
  792. while (true) {
  793. const Token &t = p_tokenizer.get_token();
  794. if (t.text == 0) {
  795. break;
  796. }
  797. if (state->disabled) {
  798. // Preprocessor was disabled.
  799. // Read the rest of the file into the output.
  800. output.push_back(t.text);
  801. continue;
  802. } else {
  803. // Add autogenerated tokens.
  804. Vector<Token> generated;
  805. p_tokenizer.get_and_clear_generated(&generated);
  806. for (int i = 0; i < generated.size(); i++) {
  807. output.push_back(generated[i].text);
  808. }
  809. }
  810. if (t.text == '#') {
  811. if (has_symbols_before_directive) {
  812. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  813. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  814. return FAILED;
  815. }
  816. process_directive(&p_tokenizer);
  817. } else {
  818. if (is_char_end(t.text)) {
  819. expand_output_macros(last_size, p_tokenizer.get_line());
  820. last_size = output.size();
  821. has_symbols_before_directive = false;
  822. } else if (!is_char_space(t.text)) {
  823. has_symbols_before_directive = true;
  824. }
  825. output.push_back(t.text);
  826. }
  827. if (!state->error.is_empty()) {
  828. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  829. return FAILED;
  830. }
  831. }
  832. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  833. if (!state->disabled) {
  834. if (state->condition_depth != 0) {
  835. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  836. return FAILED;
  837. }
  838. expand_output_macros(last_size, p_tokenizer.get_line());
  839. }
  840. r_result = vector_to_string(output);
  841. return OK;
  842. }
  843. Error ShaderPreprocessor::preprocess(const String &p_code, String &r_result, String *r_error_text, List<FilePosition> *r_error_position, HashSet<Ref<ShaderInclude>> *r_includes, List<ScriptLanguage::CodeCompletionOption> *r_completion_options, IncludeCompletionFunction p_include_completion_func) {
  844. State pp_state;
  845. Error err = preprocess(&pp_state, p_code, r_result);
  846. if (err != OK) {
  847. if (r_error_text) {
  848. *r_error_text = pp_state.error;
  849. }
  850. if (r_error_position) {
  851. *r_error_position = pp_state.include_positions;
  852. }
  853. }
  854. if (r_includes) {
  855. *r_includes = pp_state.shader_includes;
  856. }
  857. if (r_completion_options) {
  858. switch (pp_state.completion_type) {
  859. case COMPLETION_TYPE_DIRECTIVE: {
  860. List<String> options;
  861. get_keyword_list(&options, true);
  862. for (const String &E : options) {
  863. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  864. r_completion_options->push_back(option);
  865. }
  866. } break;
  867. case COMPLETION_TYPE_PRAGMA: {
  868. List<String> options;
  869. ShaderPreprocessor::get_pragma_list(&options);
  870. for (const String &E : options) {
  871. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  872. r_completion_options->push_back(option);
  873. }
  874. } break;
  875. case COMPLETION_TYPE_INCLUDE_PATH: {
  876. if (p_include_completion_func && r_completion_options) {
  877. p_include_completion_func(r_completion_options);
  878. }
  879. } break;
  880. default: {
  881. }
  882. }
  883. }
  884. return err;
  885. }
  886. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords) {
  887. r_keywords->push_back("define");
  888. if (p_include_shader_keywords) {
  889. r_keywords->push_back("else");
  890. }
  891. r_keywords->push_back("endif");
  892. if (p_include_shader_keywords) {
  893. r_keywords->push_back("if");
  894. }
  895. r_keywords->push_back("ifdef");
  896. r_keywords->push_back("ifndef");
  897. r_keywords->push_back("include");
  898. r_keywords->push_back("pragma");
  899. r_keywords->push_back("undef");
  900. }
  901. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  902. r_pragmas->push_back("disable_preprocessor");
  903. }
  904. ShaderPreprocessor::ShaderPreprocessor() {
  905. }
  906. ShaderPreprocessor::~ShaderPreprocessor() {
  907. clear();
  908. }