shader_preprocessor.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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. #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(LocalVector<char32_t> *r_out) {
  50. for (uint32_t i = 0; i < generated.size(); i++) {
  51. r_out->push_back(generated[i].text);
  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. int ShaderPreprocessor::Tokenizer::consume_line_continuations(int p_offset) {
  71. int skips = 0;
  72. for (int i = index + p_offset; i < size; i++) {
  73. char32_t c = code[i];
  74. if (c == '\\') {
  75. if (i + 1 < size && code[i + 1] == '\n') {
  76. // This line ends with "\" and "\n" continuation.
  77. add_generated(Token('\n', line));
  78. line++;
  79. skips++;
  80. i = i + 2;
  81. index = i;
  82. } else {
  83. break;
  84. }
  85. } else if (!is_whitespace(c)) {
  86. break;
  87. }
  88. }
  89. return skips;
  90. }
  91. LocalVector<ShaderPreprocessor::Token> ShaderPreprocessor::Tokenizer::advance(char32_t p_what) {
  92. LocalVector<ShaderPreprocessor::Token> tokens;
  93. while (index < size) {
  94. char32_t c = code[index++];
  95. if (c == '\\' && consume_line_continuations(-1) > 0) {
  96. continue;
  97. }
  98. if (c == '\n') {
  99. add_generated(ShaderPreprocessor::Token('\n', line));
  100. line++;
  101. }
  102. tokens.push_back(ShaderPreprocessor::Token(c, line));
  103. if (c == p_what || c == 0) {
  104. return tokens;
  105. }
  106. }
  107. return LocalVector<ShaderPreprocessor::Token>();
  108. }
  109. void ShaderPreprocessor::Tokenizer::skip_whitespace() {
  110. while (is_char_space(peek())) {
  111. next();
  112. }
  113. }
  114. bool ShaderPreprocessor::Tokenizer::consume_empty_line() {
  115. // Read until newline and return true if the content was all whitespace/empty.
  116. return tokens_to_string(advance('\n')).strip_edges().size() == 0;
  117. }
  118. String ShaderPreprocessor::Tokenizer::get_identifier(bool *r_is_cursor, bool p_started) {
  119. if (r_is_cursor != nullptr) {
  120. *r_is_cursor = false;
  121. }
  122. LocalVector<char32_t> text;
  123. while (true) {
  124. char32_t c = peek();
  125. if (c == '\\' && consume_line_continuations(0) > 0) {
  126. continue;
  127. }
  128. if (is_char_end(c) || c == '(' || c == ')' || c == ',' || c == ';') {
  129. break;
  130. }
  131. if (is_whitespace(c) && p_started) {
  132. break;
  133. }
  134. if (!is_whitespace(c)) {
  135. p_started = true;
  136. }
  137. char32_t n = next();
  138. if (n == CURSOR) {
  139. if (r_is_cursor != nullptr) {
  140. *r_is_cursor = true;
  141. }
  142. } else {
  143. if (p_started) {
  144. text.push_back(n);
  145. }
  146. }
  147. }
  148. String id = vector_to_string(text);
  149. if (!id.is_valid_identifier()) {
  150. return "";
  151. }
  152. return id;
  153. }
  154. String ShaderPreprocessor::Tokenizer::peek_identifier() {
  155. const int original = index;
  156. const int original_line = line;
  157. String id = get_identifier();
  158. index = original;
  159. line = original_line;
  160. return id;
  161. }
  162. ShaderPreprocessor::Token ShaderPreprocessor::Tokenizer::get_token() {
  163. while (index < size) {
  164. const char32_t c = code[index++];
  165. const Token t = ShaderPreprocessor::Token(c, line);
  166. switch (c) {
  167. case ' ':
  168. case '\t':
  169. skip_whitespace();
  170. return ShaderPreprocessor::Token(' ', line);
  171. case '\n':
  172. line++;
  173. return t;
  174. default:
  175. return t;
  176. }
  177. }
  178. return ShaderPreprocessor::Token(char32_t(0), line);
  179. }
  180. ShaderPreprocessor::Tokenizer::Tokenizer(const String &p_code) {
  181. code = p_code;
  182. line = 0;
  183. index = 0;
  184. size = code.size();
  185. }
  186. // ShaderPreprocessor::CommentRemover
  187. String ShaderPreprocessor::CommentRemover::get_error() const {
  188. if (comments_open != 0) {
  189. return "Block comment mismatch";
  190. }
  191. return "";
  192. }
  193. int ShaderPreprocessor::CommentRemover::get_error_line() const {
  194. if (comments_open != 0) {
  195. return comment_line_open;
  196. }
  197. return -1;
  198. }
  199. char32_t ShaderPreprocessor::CommentRemover::peek() const {
  200. if (index < code.size()) {
  201. return code[index];
  202. }
  203. return 0;
  204. }
  205. bool ShaderPreprocessor::CommentRemover::advance(char32_t p_what) {
  206. while (index < code.size()) {
  207. char32_t c = code[index++];
  208. if (c == '\n') {
  209. line++;
  210. stripped.push_back('\n');
  211. }
  212. if (c == p_what) {
  213. return true;
  214. }
  215. }
  216. return false;
  217. }
  218. String ShaderPreprocessor::CommentRemover::strip() {
  219. stripped.clear();
  220. index = 0;
  221. line = 0;
  222. comment_line_open = 0;
  223. comments_open = 0;
  224. strings_open = 0;
  225. while (index < code.size()) {
  226. char32_t c = code[index++];
  227. if (c == CURSOR) {
  228. // Cursor. Maintain.
  229. stripped.push_back(c);
  230. } else if (c == '"') {
  231. if (strings_open <= 0) {
  232. strings_open++;
  233. } else {
  234. strings_open--;
  235. }
  236. stripped.push_back(c);
  237. } else if (c == '/' && strings_open == 0) {
  238. char32_t p = peek();
  239. if (p == '/') { // Single line comment.
  240. advance('\n');
  241. } else if (p == '*') { // Start of a block comment.
  242. index++;
  243. comment_line_open = line;
  244. comments_open++;
  245. while (advance('*')) {
  246. if (peek() == '/') { // End of a block comment.
  247. comments_open--;
  248. index++;
  249. break;
  250. }
  251. }
  252. } else {
  253. stripped.push_back(c);
  254. }
  255. } else if (c == '*' && strings_open == 0) {
  256. if (peek() == '/') { // Unmatched end of a block comment.
  257. comment_line_open = line;
  258. comments_open--;
  259. } else {
  260. stripped.push_back(c);
  261. }
  262. } else if (c == '\n') {
  263. line++;
  264. stripped.push_back(c);
  265. } else {
  266. stripped.push_back(c);
  267. }
  268. }
  269. return vector_to_string(stripped);
  270. }
  271. ShaderPreprocessor::CommentRemover::CommentRemover(const String &p_code) {
  272. code = p_code;
  273. index = 0;
  274. line = 0;
  275. comment_line_open = 0;
  276. comments_open = 0;
  277. strings_open = 0;
  278. }
  279. // ShaderPreprocessor::Token
  280. ShaderPreprocessor::Token::Token() {
  281. text = 0;
  282. line = -1;
  283. }
  284. ShaderPreprocessor::Token::Token(char32_t p_text, int p_line) {
  285. text = p_text;
  286. line = p_line;
  287. }
  288. // ShaderPreprocessor
  289. bool ShaderPreprocessor::is_char_word(char32_t p_char) {
  290. if ((p_char >= '0' && p_char <= '9') ||
  291. (p_char >= 'a' && p_char <= 'z') ||
  292. (p_char >= 'A' && p_char <= 'Z') ||
  293. p_char == '_') {
  294. return true;
  295. }
  296. return false;
  297. }
  298. bool ShaderPreprocessor::is_char_space(char32_t p_char) {
  299. return p_char == ' ' || p_char == '\t';
  300. }
  301. bool ShaderPreprocessor::is_char_end(char32_t p_char) {
  302. return p_char == '\n' || p_char == 0;
  303. }
  304. String ShaderPreprocessor::vector_to_string(const LocalVector<char32_t> &p_v, int p_start, int p_end) {
  305. const int stop = (p_end == -1) ? p_v.size() : p_end;
  306. const int count = stop - p_start;
  307. String result;
  308. result.resize(count + 1);
  309. for (int i = 0; i < count; i++) {
  310. result[i] = p_v[p_start + i];
  311. }
  312. result[count] = 0; // Ensure string is null terminated for length() to work.
  313. return result;
  314. }
  315. String ShaderPreprocessor::tokens_to_string(const LocalVector<Token> &p_tokens) {
  316. LocalVector<char32_t> result;
  317. for (const Token &token : p_tokens) {
  318. result.push_back(token.text);
  319. }
  320. return vector_to_string(result);
  321. }
  322. void ShaderPreprocessor::process_directive(Tokenizer *p_tokenizer) {
  323. bool is_cursor;
  324. String directive = p_tokenizer->get_identifier(&is_cursor, true);
  325. if (is_cursor) {
  326. state->completion_type = COMPLETION_TYPE_DIRECTIVE;
  327. }
  328. if (directive == "if") {
  329. process_if(p_tokenizer);
  330. } else if (directive == "ifdef") {
  331. process_ifdef(p_tokenizer);
  332. } else if (directive == "ifndef") {
  333. process_ifndef(p_tokenizer);
  334. } else if (directive == "elif") {
  335. process_elif(p_tokenizer);
  336. } else if (directive == "else") {
  337. process_else(p_tokenizer);
  338. } else if (directive == "endif") {
  339. process_endif(p_tokenizer);
  340. } else if (directive == "define") {
  341. process_define(p_tokenizer);
  342. } else if (directive == "undef") {
  343. process_undef(p_tokenizer);
  344. } else if (directive == "include") {
  345. process_include(p_tokenizer);
  346. } else if (directive == "pragma") {
  347. process_pragma(p_tokenizer);
  348. } else {
  349. set_error(RTR("Unknown directive."), p_tokenizer->get_line());
  350. }
  351. }
  352. void ShaderPreprocessor::process_define(Tokenizer *p_tokenizer) {
  353. const int line = p_tokenizer->get_line();
  354. String label = p_tokenizer->get_identifier();
  355. if (label.is_empty()) {
  356. set_error(RTR("Invalid macro name."), line);
  357. return;
  358. }
  359. if (state->defines.has(label)) {
  360. set_error(RTR("Macro redefinition."), line);
  361. return;
  362. }
  363. if (p_tokenizer->peek() == '(') {
  364. // Macro has arguments.
  365. p_tokenizer->get_token();
  366. Vector<String> args;
  367. while (true) {
  368. String name = p_tokenizer->get_identifier();
  369. if (name.is_empty()) {
  370. set_error(RTR("Invalid argument name."), line);
  371. return;
  372. }
  373. args.push_back(name);
  374. p_tokenizer->skip_whitespace();
  375. char32_t next = p_tokenizer->get_token().text;
  376. if (next == ')') {
  377. break;
  378. } else if (next != ',') {
  379. set_error(RTR("Expected a comma in the macro argument list."), line);
  380. return;
  381. }
  382. }
  383. Define *define = memnew(Define);
  384. define->arguments = args;
  385. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  386. state->defines[label] = define;
  387. } else {
  388. // Simple substitution macro.
  389. Define *define = memnew(Define);
  390. define->body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  391. state->defines[label] = define;
  392. }
  393. }
  394. void ShaderPreprocessor::process_elif(Tokenizer *p_tokenizer) {
  395. const int line = p_tokenizer->get_line();
  396. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  397. set_error(RTR("Unmatched elif."), line);
  398. return;
  399. }
  400. if (state->previous_region != nullptr) {
  401. state->previous_region->to_line = line - 1;
  402. }
  403. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  404. if (body.is_empty()) {
  405. set_error(RTR("Missing condition."), line);
  406. return;
  407. }
  408. Error error = expand_condition(body, line, body);
  409. if (error != OK) {
  410. return;
  411. }
  412. error = expand_macros(body, line, body);
  413. if (error != OK) {
  414. return;
  415. }
  416. Expression expression;
  417. Vector<String> names;
  418. error = expression.parse(body, names);
  419. if (error != OK) {
  420. set_error(expression.get_error_text(), line);
  421. return;
  422. }
  423. Variant v = expression.execute(Array(), nullptr, false);
  424. if (v.get_type() == Variant::NIL) {
  425. set_error(RTR("Condition evaluation error."), line);
  426. return;
  427. }
  428. bool skip = false;
  429. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  430. if (state->current_branch->conditions[i]) {
  431. skip = true;
  432. break;
  433. }
  434. }
  435. bool success = !skip && v.booleanize();
  436. start_branch_condition(p_tokenizer, success, true);
  437. if (state->save_regions) {
  438. add_region(line + 1, success, state->previous_region->parent);
  439. }
  440. }
  441. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  442. const int line = p_tokenizer->get_line();
  443. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  444. set_error(RTR("Unmatched else."), line);
  445. return;
  446. }
  447. if (state->previous_region != nullptr) {
  448. state->previous_region->to_line = line - 1;
  449. }
  450. if (!p_tokenizer->consume_empty_line()) {
  451. set_error(RTR("Invalid else."), p_tokenizer->get_line());
  452. }
  453. bool skip = false;
  454. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  455. if (state->current_branch->conditions[i]) {
  456. skip = true;
  457. break;
  458. }
  459. }
  460. state->current_branch->else_defined = true;
  461. if (state->save_regions) {
  462. add_region(line + 1, !skip, state->previous_region->parent);
  463. }
  464. if (skip) {
  465. Vector<String> ends;
  466. ends.push_back("endif");
  467. next_directive(p_tokenizer, ends);
  468. }
  469. }
  470. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  471. const int line = p_tokenizer->get_line();
  472. state->condition_depth--;
  473. if (state->condition_depth < 0) {
  474. set_error(RTR("Unmatched endif."), line);
  475. return;
  476. }
  477. if (state->previous_region != nullptr) {
  478. state->previous_region->to_line = line - 1;
  479. state->previous_region = state->previous_region->parent;
  480. }
  481. if (!p_tokenizer->consume_empty_line()) {
  482. set_error(RTR("Invalid endif."), line);
  483. }
  484. state->current_branch = state->current_branch->parent;
  485. state->branches.pop_back();
  486. }
  487. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  488. const int line = p_tokenizer->get_line();
  489. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  490. if (body.is_empty()) {
  491. set_error(RTR("Missing condition."), line);
  492. return;
  493. }
  494. Error error = expand_condition(body, line, body);
  495. if (error != OK) {
  496. return;
  497. }
  498. error = expand_macros(body, line, body);
  499. if (error != OK) {
  500. return;
  501. }
  502. Expression expression;
  503. Vector<String> names;
  504. error = expression.parse(body, names);
  505. if (error != OK) {
  506. set_error(expression.get_error_text(), line);
  507. return;
  508. }
  509. Variant v = expression.execute(Array(), nullptr, false);
  510. if (v.get_type() == Variant::NIL) {
  511. set_error(RTR("Condition evaluation error."), line);
  512. return;
  513. }
  514. bool success = v.booleanize();
  515. start_branch_condition(p_tokenizer, success);
  516. if (state->save_regions) {
  517. add_region(line + 1, success, state->previous_region);
  518. }
  519. }
  520. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  521. const int line = p_tokenizer->get_line();
  522. String label = p_tokenizer->get_identifier();
  523. if (label.is_empty()) {
  524. set_error(RTR("Invalid macro name."), line);
  525. return;
  526. }
  527. if (!p_tokenizer->consume_empty_line()) {
  528. set_error(RTR("Invalid ifdef."), line);
  529. return;
  530. }
  531. bool success = state->defines.has(label);
  532. start_branch_condition(p_tokenizer, success);
  533. if (state->save_regions) {
  534. add_region(line + 1, success, state->previous_region);
  535. }
  536. }
  537. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  538. const int line = p_tokenizer->get_line();
  539. String label = p_tokenizer->get_identifier();
  540. if (label.is_empty()) {
  541. set_error(RTR("Invalid macro name."), line);
  542. return;
  543. }
  544. if (!p_tokenizer->consume_empty_line()) {
  545. set_error(RTR("Invalid ifndef."), line);
  546. return;
  547. }
  548. bool success = !state->defines.has(label);
  549. start_branch_condition(p_tokenizer, success);
  550. if (state->save_regions) {
  551. add_region(line + 1, success, state->previous_region);
  552. }
  553. }
  554. void ShaderPreprocessor::process_include(Tokenizer *p_tokenizer) {
  555. const int line = p_tokenizer->get_line();
  556. p_tokenizer->advance('"');
  557. String path = tokens_to_string(p_tokenizer->advance('"'));
  558. for (int i = 0; i < path.length(); i++) {
  559. if (path[i] == '\n') {
  560. break; //stop parsing
  561. }
  562. if (path[i] == CURSOR) {
  563. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  564. break;
  565. }
  566. }
  567. path = path.substr(0, path.length() - 1);
  568. if (path.is_empty() || !p_tokenizer->consume_empty_line()) {
  569. set_error(RTR("Invalid path."), line);
  570. return;
  571. }
  572. path = path.simplify_path();
  573. if (path.is_relative_path()) {
  574. path = state->current_filename.get_base_dir().path_join(path);
  575. }
  576. if (!ResourceLoader::exists(path)) {
  577. set_error(RTR("Shader include file does not exist: ") + path, line);
  578. return;
  579. }
  580. Ref<Resource> res = ResourceLoader::load(path);
  581. if (res.is_null()) {
  582. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  583. return;
  584. }
  585. Ref<ShaderInclude> shader_inc = res;
  586. if (shader_inc.is_null()) {
  587. set_error(RTR("Shader include resource type is wrong."), line);
  588. return;
  589. }
  590. String included = shader_inc->get_code();
  591. if (!included.is_empty()) {
  592. uint64_t code_hash = included.hash64();
  593. if (state->cyclic_include_hashes.find(code_hash)) {
  594. set_error(RTR("Cyclic include found."), line);
  595. return;
  596. }
  597. }
  598. state->shader_includes.insert(shader_inc);
  599. const String real_path = shader_inc->get_path();
  600. if (state->includes.has(real_path)) {
  601. // Already included, skip.
  602. // This is a valid check because 2 separate include paths could use some
  603. // of the same shared functions from a common shader include.
  604. return;
  605. }
  606. // Mark as included.
  607. state->includes.insert(real_path);
  608. state->include_depth++;
  609. if (state->include_depth > 25) {
  610. set_error(RTR("Shader max include depth exceeded."), line);
  611. return;
  612. }
  613. String old_filename = state->current_filename;
  614. state->current_filename = real_path;
  615. ShaderPreprocessor processor;
  616. int prev_condition_depth = state->condition_depth;
  617. state->condition_depth = 0;
  618. FilePosition fp;
  619. fp.file = state->current_filename;
  620. fp.line = line;
  621. state->include_positions.push_back(fp);
  622. String result;
  623. processor.preprocess(state, included, result);
  624. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  625. add_to_output(result);
  626. add_to_output("\n@@<\n"); // Add token for exit include path
  627. // Reset to last include if there are no errors. We want to use this as context.
  628. if (state->error.is_empty()) {
  629. state->current_filename = old_filename;
  630. state->include_positions.pop_back();
  631. } else {
  632. return;
  633. }
  634. state->include_depth--;
  635. state->condition_depth = prev_condition_depth;
  636. }
  637. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  638. const int line = p_tokenizer->get_line();
  639. bool is_cursor;
  640. const String label = p_tokenizer->get_identifier(&is_cursor);
  641. if (is_cursor) {
  642. state->completion_type = COMPLETION_TYPE_PRAGMA;
  643. }
  644. if (label.is_empty()) {
  645. set_error(RTR("Invalid pragma directive."), line);
  646. return;
  647. }
  648. // Rxplicitly handle pragma values here.
  649. // If more pragma options are created, then refactor into a more defined structure.
  650. if (label == "disable_preprocessor") {
  651. state->disabled = true;
  652. } else {
  653. set_error(RTR("Invalid pragma directive."), line);
  654. return;
  655. }
  656. if (!p_tokenizer->consume_empty_line()) {
  657. set_error(RTR("Invalid pragma directive."), line);
  658. return;
  659. }
  660. }
  661. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  662. const int line = p_tokenizer->get_line();
  663. const String label = p_tokenizer->get_identifier();
  664. if (label.is_empty() || !p_tokenizer->consume_empty_line()) {
  665. set_error(RTR("Invalid undef."), line);
  666. return;
  667. }
  668. if (state->defines.has(label)) {
  669. memdelete(state->defines[label]);
  670. state->defines.erase(label);
  671. }
  672. }
  673. void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
  674. Region region;
  675. region.file = state->current_filename;
  676. region.enabled = p_enabled;
  677. region.from_line = p_line;
  678. region.parent = p_parent_region;
  679. state->previous_region = &state->regions[region.file].push_back(region)->get();
  680. }
  681. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
  682. if (!p_continue) {
  683. state->condition_depth++;
  684. state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
  685. } else {
  686. state->current_branch->conditions.push_back(p_success);
  687. }
  688. if (!p_success) {
  689. Vector<String> ends;
  690. ends.push_back("elif");
  691. ends.push_back("else");
  692. ends.push_back("endif");
  693. next_directive(p_tokenizer, ends);
  694. }
  695. }
  696. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  697. String line = vector_to_string(output, p_start, output.size());
  698. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  699. if (error != OK) {
  700. return;
  701. }
  702. output.resize(p_start);
  703. add_to_output(line);
  704. }
  705. Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
  706. // Checks bracket count to be even + check the cursor position.
  707. {
  708. int bracket_start_count = 0;
  709. int bracket_end_count = 0;
  710. for (int i = 0; i < p_string.size(); i++) {
  711. switch (p_string[i]) {
  712. case CURSOR:
  713. state->completion_type = COMPLETION_TYPE_CONDITION;
  714. break;
  715. case '(':
  716. bracket_start_count++;
  717. break;
  718. case ')':
  719. bracket_end_count++;
  720. break;
  721. }
  722. }
  723. if (bracket_start_count > bracket_end_count) {
  724. _set_expected_error(")", p_line);
  725. return FAILED;
  726. }
  727. if (bracket_end_count > bracket_start_count) {
  728. _set_expected_error("(", p_line);
  729. return FAILED;
  730. }
  731. }
  732. String result = p_string;
  733. int index = 0;
  734. int index_start = 0;
  735. int index_end = 0;
  736. while (find_match(result, "defined", index, index_start)) {
  737. bool open_bracket = false;
  738. bool found_word = false;
  739. bool word_completed = false;
  740. LocalVector<char32_t> text;
  741. int post_bracket_index = -1;
  742. int size = result.size();
  743. for (int i = (index_start - 1); i < size; i++) {
  744. char32_t c = result[i];
  745. if (c == 0) {
  746. if (found_word) {
  747. word_completed = true;
  748. }
  749. break;
  750. }
  751. char32_t cs[] = { c, '\0' };
  752. String s = String(cs);
  753. bool is_space = is_char_space(c);
  754. if (word_completed) {
  755. if (c == ')') {
  756. continue;
  757. }
  758. if (c == '|' || c == '&') {
  759. if (open_bracket) {
  760. _set_unexpected_token_error(s, p_line);
  761. return FAILED;
  762. }
  763. break;
  764. } else if (!is_space) {
  765. _set_unexpected_token_error(s, p_line);
  766. return FAILED;
  767. }
  768. } else if (is_space) {
  769. if (found_word && !open_bracket) {
  770. index_end = i;
  771. word_completed = true;
  772. }
  773. } else if (c == '(') {
  774. if (open_bracket) {
  775. _set_unexpected_token_error(s, p_line);
  776. return FAILED;
  777. }
  778. open_bracket = true;
  779. } else if (c == ')') {
  780. if (open_bracket) {
  781. if (!found_word) {
  782. _set_unexpected_token_error(s, p_line);
  783. return FAILED;
  784. }
  785. open_bracket = false;
  786. post_bracket_index = i + 1;
  787. } else {
  788. index_end = i;
  789. }
  790. word_completed = true;
  791. } else if (is_char_word(c)) {
  792. text.push_back(c);
  793. found_word = true;
  794. } else {
  795. _set_unexpected_token_error(s, p_line);
  796. return FAILED;
  797. }
  798. }
  799. if (word_completed) {
  800. if (open_bracket) {
  801. _set_expected_error(")", p_line);
  802. return FAILED;
  803. }
  804. if (post_bracket_index != -1) {
  805. index_end = post_bracket_index;
  806. }
  807. String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
  808. String temp = result;
  809. result = result.substr(0, index) + body;
  810. index_start = result.length();
  811. if (index_end > 0) {
  812. result += temp.substr(index_end);
  813. }
  814. } else {
  815. set_error(RTR("Invalid macro name."), p_line);
  816. return FAILED;
  817. }
  818. }
  819. r_expanded = result;
  820. return OK;
  821. }
  822. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  823. String iterative = p_string;
  824. int pass_count = 0;
  825. bool expanded = true;
  826. while (expanded) {
  827. expanded = false;
  828. // As long as we find something to expand, keep going.
  829. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  830. if (expand_macros_once(iterative, p_line, E, iterative)) {
  831. expanded = true;
  832. }
  833. }
  834. pass_count++;
  835. if (pass_count > 50) {
  836. set_error(RTR("Macro expansion limit exceeded."), p_line);
  837. break;
  838. }
  839. }
  840. r_expanded = iterative;
  841. if (!state->error.is_empty()) {
  842. return FAILED;
  843. }
  844. return OK;
  845. }
  846. bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
  847. String result = p_line;
  848. const String &key = p_define_pair->key();
  849. const Define *define = p_define_pair->value();
  850. int index_start = 0;
  851. int index = 0;
  852. if (find_match(result, key, index, index_start)) {
  853. String body = define->body;
  854. if (define->arguments.size() > 0) {
  855. // Complex macro with arguments.
  856. int args_start = -1;
  857. int args_end = -1;
  858. int brackets_open = 0;
  859. Vector<String> args;
  860. for (int i = index_start - 1; i < p_line.length(); i++) {
  861. bool add_argument = false;
  862. bool reached_end = false;
  863. char32_t c = p_line[i];
  864. if (c == '(') {
  865. brackets_open++;
  866. if (brackets_open == 1) {
  867. args_start = i + 1;
  868. args_end = -1;
  869. }
  870. } else if (c == ')') {
  871. brackets_open--;
  872. if (brackets_open == 0) {
  873. args_end = i;
  874. add_argument = true;
  875. reached_end = true;
  876. }
  877. } else if (c == ',') {
  878. if (brackets_open == 1) {
  879. args_end = i;
  880. add_argument = true;
  881. }
  882. }
  883. if (add_argument) {
  884. if (args_start == -1 || args_end == -1) {
  885. set_error(RTR("Invalid macro argument list."), p_line_number);
  886. return false;
  887. }
  888. String arg = p_line.substr(args_start, args_end - args_start).strip_edges();
  889. if (arg.is_empty()) {
  890. set_error(RTR("Invalid macro argument."), p_line_number);
  891. return false;
  892. }
  893. args.append(arg);
  894. args_start = args_end + 1;
  895. }
  896. if (reached_end) {
  897. break;
  898. }
  899. }
  900. if (args.size() != define->arguments.size()) {
  901. set_error(RTR("Invalid macro argument count."), p_line_number);
  902. return false;
  903. }
  904. // Insert macro arguments into the body.
  905. for (int i = 0; i < args.size(); i++) {
  906. String arg_name = define->arguments[i];
  907. int arg_index_start = 0;
  908. int arg_index = 0;
  909. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  910. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  911. // Manually reset arg_index_start to where the arg value of the define finishes.
  912. // This ensures we don't skip the other args of this macro in the string.
  913. arg_index_start = arg_index + args[i].length() + 1;
  914. }
  915. }
  916. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  917. } else {
  918. result = result.substr(0, index) + body + result.substr(index + key.length(), result.length() - (index + key.length()));
  919. }
  920. r_expanded = result;
  921. return true;
  922. }
  923. return false;
  924. }
  925. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  926. // Looks for value in string and then determines if the boundaries
  927. // are non-word characters. This method semi-emulates \b in regex.
  928. r_index = p_string.find(p_value, r_index_start);
  929. while (r_index > -1) {
  930. if (r_index > 0) {
  931. if (is_char_word(p_string[r_index - 1])) {
  932. r_index_start = r_index + 1;
  933. r_index = p_string.find(p_value, r_index_start);
  934. continue;
  935. }
  936. }
  937. if (r_index + p_value.length() < p_string.length()) {
  938. if (is_char_word(p_string[r_index + p_value.length()])) {
  939. r_index_start = r_index + p_value.length() + 1;
  940. r_index = p_string.find(p_value, r_index_start);
  941. continue;
  942. }
  943. }
  944. // Return and shift index start automatically for next call.
  945. r_index_start = r_index + p_value.length() + 1;
  946. return true;
  947. }
  948. return false;
  949. }
  950. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  951. const int line = p_tokenizer->get_line();
  952. int nesting = 0;
  953. while (true) {
  954. p_tokenizer->advance('#');
  955. String id = p_tokenizer->peek_identifier();
  956. if (id.is_empty()) {
  957. break;
  958. }
  959. if (nesting == 0) {
  960. for (int i = 0; i < p_directives.size(); i++) {
  961. if (p_directives[i] == id) {
  962. p_tokenizer->backtrack('#');
  963. return id;
  964. }
  965. }
  966. }
  967. if (id == "ifdef" || id == "ifndef" || id == "if") {
  968. nesting++;
  969. } else if (id == "endif") {
  970. nesting--;
  971. }
  972. }
  973. set_error(RTR("Can't find matching branch directive."), line);
  974. return "";
  975. }
  976. void ShaderPreprocessor::add_to_output(const String &p_str) {
  977. for (int i = 0; i < p_str.length(); i++) {
  978. output.push_back(p_str[i]);
  979. }
  980. }
  981. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  982. if (state->error.is_empty()) {
  983. state->error = p_error;
  984. FilePosition fp;
  985. fp.line = p_line + 1;
  986. state->include_positions.push_back(fp);
  987. }
  988. }
  989. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  990. ShaderPreprocessor::Define *define = memnew(Define);
  991. define->body = p_body;
  992. return define;
  993. }
  994. void ShaderPreprocessor::clear_state() {
  995. if (state != nullptr) {
  996. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  997. memdelete(E->get());
  998. }
  999. state->defines.clear();
  1000. }
  1001. state = nullptr;
  1002. }
  1003. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  1004. output.clear();
  1005. state = p_state;
  1006. CommentRemover remover(p_code);
  1007. String stripped = remover.strip();
  1008. String error = remover.get_error();
  1009. if (!error.is_empty()) {
  1010. set_error(error, remover.get_error_line());
  1011. return FAILED;
  1012. }
  1013. // Track code hashes to prevent cyclic include.
  1014. uint64_t code_hash = p_code.hash64();
  1015. state->cyclic_include_hashes.push_back(code_hash);
  1016. Tokenizer p_tokenizer(stripped);
  1017. int last_size = 0;
  1018. bool has_symbols_before_directive = false;
  1019. while (true) {
  1020. const Token &t = p_tokenizer.get_token();
  1021. if (t.text == 0) {
  1022. break;
  1023. }
  1024. // Add autogenerated tokens if there are any.
  1025. p_tokenizer.get_and_clear_generated(&output);
  1026. if (state->disabled) {
  1027. // Preprocessor was disabled.
  1028. // Read the rest of the file into the output.
  1029. output.push_back(t.text);
  1030. continue;
  1031. }
  1032. if (t.text == '#') {
  1033. if (has_symbols_before_directive) {
  1034. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  1035. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1036. return FAILED;
  1037. }
  1038. process_directive(&p_tokenizer);
  1039. } else {
  1040. if (is_char_end(t.text)) {
  1041. expand_output_macros(last_size, p_tokenizer.get_line());
  1042. last_size = output.size();
  1043. has_symbols_before_directive = false;
  1044. } else if (!is_char_space(t.text)) {
  1045. has_symbols_before_directive = true;
  1046. }
  1047. output.push_back(t.text);
  1048. }
  1049. if (!state->error.is_empty()) {
  1050. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1051. return FAILED;
  1052. }
  1053. }
  1054. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  1055. if (!state->disabled) {
  1056. if (state->condition_depth != 0) {
  1057. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  1058. return FAILED;
  1059. }
  1060. expand_output_macros(last_size, p_tokenizer.get_line());
  1061. }
  1062. r_result = vector_to_string(output);
  1063. return OK;
  1064. }
  1065. 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) {
  1066. State pp_state;
  1067. if (!p_filename.is_empty()) {
  1068. pp_state.current_filename = p_filename;
  1069. pp_state.save_regions = r_regions != nullptr;
  1070. }
  1071. Error err = preprocess(&pp_state, p_code, r_result);
  1072. if (err != OK) {
  1073. if (r_error_text) {
  1074. *r_error_text = pp_state.error;
  1075. }
  1076. if (r_error_position) {
  1077. *r_error_position = pp_state.include_positions;
  1078. }
  1079. }
  1080. if (r_regions) {
  1081. *r_regions = pp_state.regions[p_filename];
  1082. }
  1083. if (r_includes) {
  1084. *r_includes = pp_state.shader_includes;
  1085. }
  1086. if (r_completion_defines) {
  1087. for (const KeyValue<String, Define *> &E : state->defines) {
  1088. ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
  1089. r_completion_defines->push_back(option);
  1090. }
  1091. }
  1092. if (r_completion_options) {
  1093. switch (pp_state.completion_type) {
  1094. case COMPLETION_TYPE_DIRECTIVE: {
  1095. List<String> options;
  1096. get_keyword_list(&options, true, true);
  1097. for (const String &E : options) {
  1098. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1099. r_completion_options->push_back(option);
  1100. }
  1101. } break;
  1102. case COMPLETION_TYPE_PRAGMA: {
  1103. List<String> options;
  1104. ShaderPreprocessor::get_pragma_list(&options);
  1105. for (const String &E : options) {
  1106. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1107. r_completion_options->push_back(option);
  1108. }
  1109. } break;
  1110. case COMPLETION_TYPE_CONDITION: {
  1111. ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1112. r_completion_options->push_back(option);
  1113. } break;
  1114. case COMPLETION_TYPE_INCLUDE_PATH: {
  1115. if (p_include_completion_func && r_completion_options) {
  1116. p_include_completion_func(r_completion_options);
  1117. }
  1118. } break;
  1119. default: {
  1120. }
  1121. }
  1122. }
  1123. clear_state();
  1124. return err;
  1125. }
  1126. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
  1127. r_keywords->push_back("define");
  1128. if (!p_ignore_context_keywords) {
  1129. r_keywords->push_back("defined");
  1130. }
  1131. r_keywords->push_back("elif");
  1132. if (p_include_shader_keywords) {
  1133. r_keywords->push_back("else");
  1134. }
  1135. r_keywords->push_back("endif");
  1136. if (p_include_shader_keywords) {
  1137. r_keywords->push_back("if");
  1138. }
  1139. r_keywords->push_back("ifdef");
  1140. r_keywords->push_back("ifndef");
  1141. r_keywords->push_back("include");
  1142. r_keywords->push_back("pragma");
  1143. r_keywords->push_back("undef");
  1144. }
  1145. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  1146. r_pragmas->push_back("disable_preprocessor");
  1147. }
  1148. ShaderPreprocessor::ShaderPreprocessor() {
  1149. }
  1150. ShaderPreprocessor::~ShaderPreprocessor() {
  1151. }