shader_preprocessor.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. process_if(p_tokenizer);
  297. } else if (directive == "ifdef") {
  298. process_ifdef(p_tokenizer);
  299. } else if (directive == "ifndef") {
  300. process_ifndef(p_tokenizer);
  301. } else if (directive == "elif") {
  302. process_elif(p_tokenizer);
  303. } else if (directive == "else") {
  304. process_else(p_tokenizer);
  305. } else if (directive == "endif") {
  306. process_endif(p_tokenizer);
  307. } else if (directive == "define") {
  308. process_define(p_tokenizer);
  309. } else if (directive == "undef") {
  310. process_undef(p_tokenizer);
  311. } else if (directive == "include") {
  312. process_include(p_tokenizer);
  313. } else if (directive == "pragma") {
  314. process_pragma(p_tokenizer);
  315. } else {
  316. set_error(RTR("Unknown directive."), p_tokenizer->get_line());
  317. }
  318. }
  319. void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
  320. const int line = p_tokenizer->get_line();
  321. String label = p_tokenizer->get_identifier();
  322. if (label.is_empty()) {
  323. set_error(RTR("Invalid macro name."), line);
  324. return;
  325. }
  326. if (state->defines.has(label)) {
  327. set_error(RTR("Macro redefinition."), line);
  328. return;
  329. }
  330. if (p_tokenizer->peek() == '(') {
  331. // Macro has arguments.
  332. p_tokenizer->get_token();
  333. Vector<String> args;
  334. while (true) {
  335. String name = p_tokenizer->get_identifier();
  336. if (name.is_empty()) {
  337. set_error(RTR("Invalid argument name."), line);
  338. return;
  339. }
  340. args.push_back(name);
  341. p_tokenizer->skip_whitespace();
  342. char32_t next = p_tokenizer->get_token().text;
  343. if (next == ')') {
  344. break;
  345. } else if (next != ',') {
  346. set_error(RTR("Expected a comma in the macro argument list."), line);
  347. return;
  348. }
  349. }
  350. Define *define = memnew(Define);
  351. define->arguments = args;
  352. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  353. state->defines[label] = define;
  354. } else {
  355. // Simple substitution macro.
  356. Define *define = memnew(Define);
  357. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  358. state->defines[label] = define;
  359. }
  360. }
  361. void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
  362. const int line = p_tokenizer->get_line();
  363. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  364. set_error(RTR("Unmatched elif."), line);
  365. return;
  366. }
  367. if (state->previous_region != nullptr) {
  368. state->previous_region->to_line = line - 1;
  369. }
  370. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  371. if (body.is_empty()) {
  372. set_error(RTR("Missing condition."), line);
  373. return;
  374. }
  375. Error error = expand_macros(body, line, body);
  376. if (error != OK) {
  377. return;
  378. }
  379. Expression expression;
  380. Vector<String> names;
  381. error = expression.parse(body, names);
  382. if (error != OK) {
  383. set_error(expression.get_error_text(), line);
  384. return;
  385. }
  386. Variant v = expression.execute(Array(), nullptr, false);
  387. if (v.get_type() == Variant::NIL) {
  388. set_error(RTR("Condition evaluation error."), line);
  389. return;
  390. }
  391. bool skip = false;
  392. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  393. if (state->current_branch->conditions[i]) {
  394. skip = true;
  395. break;
  396. }
  397. }
  398. bool success = !skip && v.booleanize();
  399. start_branch_condition(p_tokenizer, success, true);
  400. if (state->save_regions) {
  401. add_region(line + 1, success, state->previous_region->parent);
  402. }
  403. }
  404. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  405. const int line = p_tokenizer->get_line();
  406. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  407. set_error(RTR("Unmatched else."), line);
  408. return;
  409. }
  410. if (state->previous_region != nullptr) {
  411. state->previous_region->to_line = line - 1;
  412. }
  413. p_tokenizer->advance('\n');
  414. bool skip = false;
  415. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  416. if (state->current_branch->conditions[i]) {
  417. skip = true;
  418. break;
  419. }
  420. }
  421. state->current_branch->else_defined = true;
  422. if (state->save_regions) {
  423. add_region(line + 1, !skip, state->previous_region->parent);
  424. }
  425. if (skip) {
  426. Vector<String> ends;
  427. ends.push_back("endif");
  428. next_directive(p_tokenizer, ends);
  429. }
  430. }
  431. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  432. state->condition_depth--;
  433. if (state->condition_depth < 0) {
  434. set_error(RTR("Unmatched endif."), p_tokenizer->get_line());
  435. return;
  436. }
  437. if (state->previous_region != nullptr) {
  438. state->previous_region->to_line = p_tokenizer->get_line() - 1;
  439. state->previous_region = state->previous_region->parent;
  440. }
  441. p_tokenizer->advance('\n');
  442. state->current_branch = state->current_branch->parent;
  443. state->branches.pop_back();
  444. }
  445. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  446. const int line = p_tokenizer->get_line();
  447. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  448. if (body.is_empty()) {
  449. set_error(RTR("Missing condition."), line);
  450. return;
  451. }
  452. Error error = expand_macros(body, line, body);
  453. if (error != OK) {
  454. return;
  455. }
  456. Expression expression;
  457. Vector<String> names;
  458. error = expression.parse(body, names);
  459. if (error != OK) {
  460. set_error(expression.get_error_text(), line);
  461. return;
  462. }
  463. Variant v = expression.execute(Array(), nullptr, false);
  464. if (v.get_type() == Variant::NIL) {
  465. set_error(RTR("Condition evaluation error."), line);
  466. return;
  467. }
  468. bool success = v.booleanize();
  469. start_branch_condition(p_tokenizer, success);
  470. if (state->save_regions) {
  471. add_region(line + 1, success, state->previous_region);
  472. }
  473. }
  474. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  475. const int line = p_tokenizer->get_line();
  476. String label = p_tokenizer->get_identifier();
  477. if (label.is_empty()) {
  478. set_error(RTR("Invalid macro name."), line);
  479. return;
  480. }
  481. p_tokenizer->skip_whitespace();
  482. if (!is_char_end(p_tokenizer->peek())) {
  483. set_error(RTR("Invalid ifdef."), line);
  484. return;
  485. }
  486. p_tokenizer->advance('\n');
  487. bool success = state->defines.has(label);
  488. start_branch_condition(p_tokenizer, success);
  489. if (state->save_regions) {
  490. add_region(line + 1, success, state->previous_region);
  491. }
  492. }
  493. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  494. const int line = p_tokenizer->get_line();
  495. String label = p_tokenizer->get_identifier();
  496. if (label.is_empty()) {
  497. set_error(RTR("Invalid macro name."), line);
  498. return;
  499. }
  500. p_tokenizer->skip_whitespace();
  501. if (!is_char_end(p_tokenizer->peek())) {
  502. set_error(RTR("Invalid ifndef."), line);
  503. return;
  504. }
  505. p_tokenizer->advance('\n');
  506. bool success = !state->defines.has(label);
  507. start_branch_condition(p_tokenizer, success);
  508. if (state->save_regions) {
  509. add_region(line + 1, success, state->previous_region);
  510. }
  511. }
  512. void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
  513. const int line = p_tokenizer->get_line();
  514. p_tokenizer->advance('"');
  515. String path = tokens_to_string(p_tokenizer->advance('"'));
  516. for (int i = 0; i < path.length(); i++) {
  517. if (path[i] == '\n') {
  518. break; //stop parsing
  519. }
  520. if (path[i] == CURSOR) {
  521. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  522. break;
  523. }
  524. }
  525. path = path.substr(0, path.length() - 1);
  526. p_tokenizer->skip_whitespace();
  527. if (path.is_empty() || !is_char_end(p_tokenizer->peek())) {
  528. set_error(RTR("Invalid path."), line);
  529. return;
  530. }
  531. Ref<Resource> res = ResourceLoader::load(path);
  532. if (res.is_null()) {
  533. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  534. return;
  535. }
  536. Ref<ShaderInclude> shader_inc = res;
  537. if (shader_inc.is_null()) {
  538. set_error(RTR("Shader include resource type is wrong."), line);
  539. return;
  540. }
  541. String included = shader_inc->get_code();
  542. if (!included.is_empty()) {
  543. uint64_t code_hash = included.hash64();
  544. if (state->cyclic_include_hashes.find(code_hash)) {
  545. set_error(RTR("Cyclic include found."), line);
  546. return;
  547. }
  548. }
  549. state->shader_includes.insert(shader_inc);
  550. const String real_path = shader_inc->get_path();
  551. if (state->includes.has(real_path)) {
  552. // Already included, skip.
  553. // This is a valid check because 2 separate include paths could use some
  554. // of the same shared functions from a common shader include.
  555. return;
  556. }
  557. // Mark as included.
  558. state->includes.insert(real_path);
  559. state->include_depth++;
  560. if (state->include_depth > 25) {
  561. set_error(RTR("Shader max include depth exceeded."), line);
  562. return;
  563. }
  564. String old_filename = state->current_filename;
  565. state->current_filename = real_path;
  566. ShaderPreprocessor processor;
  567. int prev_condition_depth = state->condition_depth;
  568. state->condition_depth = 0;
  569. FilePosition fp;
  570. fp.file = state->current_filename;
  571. fp.line = line;
  572. state->include_positions.push_back(fp);
  573. String result;
  574. processor.preprocess(state, included, result);
  575. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  576. add_to_output(result);
  577. add_to_output("\n@@<\n"); // Add token for exit include path
  578. // Reset to last include if there are no errors. We want to use this as context.
  579. if (state->error.is_empty()) {
  580. state->current_filename = old_filename;
  581. state->include_positions.pop_back();
  582. } else {
  583. return;
  584. }
  585. state->include_depth--;
  586. state->condition_depth = prev_condition_depth;
  587. }
  588. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  589. const int line = p_tokenizer->get_line();
  590. bool is_cursor;
  591. const String label = p_tokenizer->get_identifier(&is_cursor);
  592. if (is_cursor) {
  593. state->completion_type = COMPLETION_TYPE_PRAGMA;
  594. }
  595. if (label.is_empty()) {
  596. set_error(RTR("Invalid pragma directive."), line);
  597. return;
  598. }
  599. // Rxplicitly handle pragma values here.
  600. // If more pragma options are created, then refactor into a more defined structure.
  601. if (label == "disable_preprocessor") {
  602. state->disabled = true;
  603. } else {
  604. set_error(RTR("Invalid pragma directive."), line);
  605. return;
  606. }
  607. p_tokenizer->advance('\n');
  608. }
  609. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  610. const int line = p_tokenizer->get_line();
  611. const String label = p_tokenizer->get_identifier();
  612. if (label.is_empty() || !state->defines.has(label)) {
  613. set_error(RTR("Invalid name."), line);
  614. return;
  615. }
  616. p_tokenizer->skip_whitespace();
  617. if (!is_char_end(p_tokenizer->peek())) {
  618. set_error(RTR("Invalid undef."), line);
  619. return;
  620. }
  621. memdelete(state->defines[label]);
  622. state->defines.erase(label);
  623. }
  624. void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
  625. Region region;
  626. region.file = state->current_filename;
  627. region.enabled = p_enabled;
  628. region.from_line = p_line;
  629. region.parent = p_parent_region;
  630. state->previous_region = &state->regions[region.file].push_back(region)->get();
  631. }
  632. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
  633. if (!p_continue) {
  634. state->condition_depth++;
  635. state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
  636. } else {
  637. state->current_branch->conditions.push_back(p_success);
  638. }
  639. if (!p_success) {
  640. Vector<String> ends;
  641. ends.push_back("elif");
  642. ends.push_back("else");
  643. ends.push_back("endif");
  644. next_directive(p_tokenizer, ends);
  645. }
  646. }
  647. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  648. String line = vector_to_string(output, p_start, output.size());
  649. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  650. if (error != OK) {
  651. return;
  652. }
  653. output.resize(p_start);
  654. add_to_output(line);
  655. }
  656. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  657. Vector<Pair<String, Define *>> active_defines;
  658. active_defines.resize(state->defines.size());
  659. int index = 0;
  660. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  661. active_defines.set(index++, Pair<String, Define *>(E->key(), E->get()));
  662. }
  663. return expand_macros(p_string, p_line, active_defines, r_expanded);
  664. }
  665. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, Vector<Pair<String, Define *>> p_defines, String &r_expanded) {
  666. r_expanded = p_string;
  667. // When expanding macros we must only evaluate them once.
  668. // Later we continue expanding but with the already
  669. // evaluated macros removed.
  670. for (int i = 0; i < p_defines.size(); i++) {
  671. Pair<String, Define *> define_pair = p_defines[i];
  672. Error error = expand_macros_once(r_expanded, p_line, define_pair, r_expanded);
  673. if (error != OK) {
  674. return error;
  675. }
  676. // Remove expanded macro and recursively replace remaining.
  677. p_defines.remove_at(i);
  678. return expand_macros(r_expanded, p_line, p_defines, r_expanded);
  679. }
  680. return OK;
  681. }
  682. Error ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, Pair<String, Define *> p_define_pair, String &r_expanded) {
  683. String result = p_line;
  684. const String &key = p_define_pair.first;
  685. const Define *define = p_define_pair.second;
  686. int index_start = 0;
  687. int index = 0;
  688. while (find_match(result, key, index, index_start)) {
  689. String body = define->body;
  690. if (define->arguments.size() > 0) {
  691. // Complex macro with arguments.
  692. int args_start = index + key.length();
  693. int args_end = p_line.find(")", args_start);
  694. if (args_start == -1 || args_end == -1) {
  695. set_error(RTR("Missing macro argument parenthesis."), p_line_number);
  696. return FAILED;
  697. }
  698. String values = result.substr(args_start + 1, args_end - (args_start + 1));
  699. Vector<String> args = values.split(",");
  700. if (args.size() != define->arguments.size()) {
  701. set_error(RTR("Invalid macro argument count."), p_line_number);
  702. return FAILED;
  703. }
  704. // Insert macro arguments into the body.
  705. for (int i = 0; i < args.size(); i++) {
  706. String arg_name = define->arguments[i];
  707. int arg_index_start = 0;
  708. int arg_index = 0;
  709. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  710. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  711. // Manually reset arg_index_start to where the arg value of the define finishes.
  712. // This ensures we don't skip the other args of this macro in the string.
  713. arg_index_start = arg_index + args[i].length() + 1;
  714. }
  715. }
  716. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  717. } else {
  718. result = result.substr(0, index) + body + result.substr(index + key.length(), result.length() - (index + key.length()));
  719. // Manually reset index_start to where the body value of the define finishes.
  720. // This ensures we don't skip another instance of this macro in the string.
  721. index_start = index + body.length() + 1;
  722. break;
  723. }
  724. }
  725. r_expanded = result;
  726. return OK;
  727. }
  728. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  729. // Looks for value in string and then determines if the boundaries
  730. // are non-word characters. This method semi-emulates \b in regex.
  731. r_index = p_string.find(p_value, r_index_start);
  732. while (r_index > -1) {
  733. if (r_index > 0) {
  734. if (is_char_word(p_string[r_index - 1])) {
  735. r_index_start = r_index + 1;
  736. r_index = p_string.find(p_value, r_index_start);
  737. continue;
  738. }
  739. }
  740. if (r_index + p_value.length() < p_string.length()) {
  741. if (is_char_word(p_string[r_index + p_value.length()])) {
  742. r_index_start = r_index + p_value.length() + 1;
  743. r_index = p_string.find(p_value, r_index_start);
  744. continue;
  745. }
  746. }
  747. // Return and shift index start automatically for next call.
  748. r_index_start = r_index + p_value.length() + 1;
  749. return true;
  750. }
  751. return false;
  752. }
  753. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  754. const int line = p_tokenizer->get_line();
  755. int nesting = 0;
  756. while (true) {
  757. p_tokenizer->advance('#');
  758. String id = p_tokenizer->peek_identifier();
  759. if (id.is_empty()) {
  760. break;
  761. }
  762. if (nesting == 0) {
  763. for (int i = 0; i < p_directives.size(); i++) {
  764. if (p_directives[i] == id) {
  765. p_tokenizer->backtrack('#');
  766. return id;
  767. }
  768. }
  769. }
  770. if (id == "ifdef" || id == "ifndef" || id == "if") {
  771. nesting++;
  772. } else if (id == "endif") {
  773. nesting--;
  774. }
  775. }
  776. set_error(RTR("Can't find matching branch directive."), line);
  777. return "";
  778. }
  779. void ShaderPreprocessor::add_to_output(const String &p_str) {
  780. for (int i = 0; i < p_str.length(); i++) {
  781. output.push_back(p_str[i]);
  782. }
  783. }
  784. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  785. if (state->error.is_empty()) {
  786. state->error = p_error;
  787. FilePosition fp;
  788. fp.line = p_line + 1;
  789. state->include_positions.push_back(fp);
  790. }
  791. }
  792. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  793. ShaderPreprocessor::Define *define = memnew(Define);
  794. define->body = p_body;
  795. return define;
  796. }
  797. void ShaderPreprocessor::clear() {
  798. if (state_owner && state != nullptr) {
  799. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  800. memdelete(E->get());
  801. }
  802. memdelete(state);
  803. }
  804. state_owner = false;
  805. state = nullptr;
  806. }
  807. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  808. clear();
  809. output.clear();
  810. state = p_state;
  811. CommentRemover remover(p_code);
  812. String stripped = remover.strip();
  813. String error = remover.get_error();
  814. if (!error.is_empty()) {
  815. set_error(error, remover.get_error_line());
  816. return FAILED;
  817. }
  818. // Track code hashes to prevent cyclic include.
  819. uint64_t code_hash = p_code.hash64();
  820. state->cyclic_include_hashes.push_back(code_hash);
  821. Tokenizer p_tokenizer(stripped);
  822. int last_size = 0;
  823. bool has_symbols_before_directive = false;
  824. while (true) {
  825. const Token &t = p_tokenizer.get_token();
  826. if (t.text == 0) {
  827. break;
  828. }
  829. if (state->disabled) {
  830. // Preprocessor was disabled.
  831. // Read the rest of the file into the output.
  832. output.push_back(t.text);
  833. continue;
  834. } else {
  835. // Add autogenerated tokens.
  836. Vector<Token> generated;
  837. p_tokenizer.get_and_clear_generated(&generated);
  838. for (int i = 0; i < generated.size(); i++) {
  839. output.push_back(generated[i].text);
  840. }
  841. }
  842. if (t.text == '#') {
  843. if (has_symbols_before_directive) {
  844. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  845. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  846. return FAILED;
  847. }
  848. process_directive(&p_tokenizer);
  849. } else {
  850. if (is_char_end(t.text)) {
  851. expand_output_macros(last_size, p_tokenizer.get_line());
  852. last_size = output.size();
  853. has_symbols_before_directive = false;
  854. } else if (!is_char_space(t.text)) {
  855. has_symbols_before_directive = true;
  856. }
  857. output.push_back(t.text);
  858. }
  859. if (!state->error.is_empty()) {
  860. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  861. return FAILED;
  862. }
  863. }
  864. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  865. if (!state->disabled) {
  866. if (state->condition_depth != 0) {
  867. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  868. return FAILED;
  869. }
  870. expand_output_macros(last_size, p_tokenizer.get_line());
  871. }
  872. r_result = vector_to_string(output);
  873. return OK;
  874. }
  875. 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, IncludeCompletionFunction p_include_completion_func) {
  876. State pp_state;
  877. if (!p_filename.is_empty()) {
  878. pp_state.current_filename = p_filename;
  879. pp_state.save_regions = r_regions != nullptr;
  880. }
  881. Error err = preprocess(&pp_state, p_code, r_result);
  882. if (err != OK) {
  883. if (r_error_text) {
  884. *r_error_text = pp_state.error;
  885. }
  886. if (r_error_position) {
  887. *r_error_position = pp_state.include_positions;
  888. }
  889. }
  890. if (r_regions) {
  891. *r_regions = pp_state.regions[p_filename];
  892. }
  893. if (r_includes) {
  894. *r_includes = pp_state.shader_includes;
  895. }
  896. if (r_completion_options) {
  897. switch (pp_state.completion_type) {
  898. case COMPLETION_TYPE_DIRECTIVE: {
  899. List<String> options;
  900. get_keyword_list(&options, true);
  901. for (const String &E : options) {
  902. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  903. r_completion_options->push_back(option);
  904. }
  905. } break;
  906. case COMPLETION_TYPE_PRAGMA: {
  907. List<String> options;
  908. ShaderPreprocessor::get_pragma_list(&options);
  909. for (const String &E : options) {
  910. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  911. r_completion_options->push_back(option);
  912. }
  913. } break;
  914. case COMPLETION_TYPE_INCLUDE_PATH: {
  915. if (p_include_completion_func && r_completion_options) {
  916. p_include_completion_func(r_completion_options);
  917. }
  918. } break;
  919. default: {
  920. }
  921. }
  922. }
  923. return err;
  924. }
  925. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords) {
  926. r_keywords->push_back("define");
  927. r_keywords->push_back("elif");
  928. if (p_include_shader_keywords) {
  929. r_keywords->push_back("else");
  930. }
  931. r_keywords->push_back("endif");
  932. if (p_include_shader_keywords) {
  933. r_keywords->push_back("if");
  934. }
  935. r_keywords->push_back("ifdef");
  936. r_keywords->push_back("ifndef");
  937. r_keywords->push_back("include");
  938. r_keywords->push_back("pragma");
  939. r_keywords->push_back("undef");
  940. }
  941. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  942. r_pragmas->push_back("disable_preprocessor");
  943. }
  944. ShaderPreprocessor::ShaderPreprocessor() {
  945. }
  946. ShaderPreprocessor::~ShaderPreprocessor() {
  947. clear();
  948. }