shader_preprocessor.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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(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 (const Token &token : p_tokens) {
  285. result.push_back(token.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_condition(body, line, body);
  376. if (error != OK) {
  377. return;
  378. }
  379. error = expand_macros(body, line, body);
  380. if (error != OK) {
  381. return;
  382. }
  383. Expression expression;
  384. Vector<String> names;
  385. error = expression.parse(body, names);
  386. if (error != OK) {
  387. set_error(expression.get_error_text(), line);
  388. return;
  389. }
  390. Variant v = expression.execute(Array(), nullptr, false);
  391. if (v.get_type() == Variant::NIL) {
  392. set_error(RTR("Condition evaluation error."), line);
  393. return;
  394. }
  395. bool skip = false;
  396. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  397. if (state->current_branch->conditions[i]) {
  398. skip = true;
  399. break;
  400. }
  401. }
  402. bool success = !skip && v.booleanize();
  403. start_branch_condition(p_tokenizer, success, true);
  404. if (state->save_regions) {
  405. add_region(line + 1, success, state->previous_region->parent);
  406. }
  407. }
  408. void ShaderPreprocessor::process_else(Tokenizer *p_tokenizer) {
  409. const int line = p_tokenizer->get_line();
  410. if (state->current_branch == nullptr || state->current_branch->else_defined) {
  411. set_error(RTR("Unmatched else."), line);
  412. return;
  413. }
  414. if (state->previous_region != nullptr) {
  415. state->previous_region->to_line = line - 1;
  416. }
  417. p_tokenizer->advance('\n');
  418. bool skip = false;
  419. for (int i = 0; i < state->current_branch->conditions.size(); i++) {
  420. if (state->current_branch->conditions[i]) {
  421. skip = true;
  422. break;
  423. }
  424. }
  425. state->current_branch->else_defined = true;
  426. if (state->save_regions) {
  427. add_region(line + 1, !skip, state->previous_region->parent);
  428. }
  429. if (skip) {
  430. Vector<String> ends;
  431. ends.push_back("endif");
  432. next_directive(p_tokenizer, ends);
  433. }
  434. }
  435. void ShaderPreprocessor::process_endif(Tokenizer *p_tokenizer) {
  436. state->condition_depth--;
  437. if (state->condition_depth < 0) {
  438. set_error(RTR("Unmatched endif."), p_tokenizer->get_line());
  439. return;
  440. }
  441. if (state->previous_region != nullptr) {
  442. state->previous_region->to_line = p_tokenizer->get_line() - 1;
  443. state->previous_region = state->previous_region->parent;
  444. }
  445. p_tokenizer->advance('\n');
  446. state->current_branch = state->current_branch->parent;
  447. state->branches.pop_back();
  448. }
  449. void ShaderPreprocessor::process_if(Tokenizer *p_tokenizer) {
  450. const int line = p_tokenizer->get_line();
  451. String body = tokens_to_string(p_tokenizer->advance('\n')).strip_edges();
  452. if (body.is_empty()) {
  453. set_error(RTR("Missing condition."), line);
  454. return;
  455. }
  456. Error error = expand_condition(body, line, body);
  457. if (error != OK) {
  458. return;
  459. }
  460. error = expand_macros(body, line, body);
  461. if (error != OK) {
  462. return;
  463. }
  464. Expression expression;
  465. Vector<String> names;
  466. error = expression.parse(body, names);
  467. if (error != OK) {
  468. set_error(expression.get_error_text(), line);
  469. return;
  470. }
  471. Variant v = expression.execute(Array(), nullptr, false);
  472. if (v.get_type() == Variant::NIL) {
  473. set_error(RTR("Condition evaluation error."), line);
  474. return;
  475. }
  476. bool success = v.booleanize();
  477. start_branch_condition(p_tokenizer, success);
  478. if (state->save_regions) {
  479. add_region(line + 1, success, state->previous_region);
  480. }
  481. }
  482. void ShaderPreprocessor::process_ifdef(Tokenizer *p_tokenizer) {
  483. const int line = p_tokenizer->get_line();
  484. String label = p_tokenizer->get_identifier();
  485. if (label.is_empty()) {
  486. set_error(RTR("Invalid macro name."), line);
  487. return;
  488. }
  489. p_tokenizer->skip_whitespace();
  490. if (!is_char_end(p_tokenizer->peek())) {
  491. set_error(RTR("Invalid ifdef."), line);
  492. return;
  493. }
  494. p_tokenizer->advance('\n');
  495. bool success = state->defines.has(label);
  496. start_branch_condition(p_tokenizer, success);
  497. if (state->save_regions) {
  498. add_region(line + 1, success, state->previous_region);
  499. }
  500. }
  501. void ShaderPreprocessor::process_ifndef(Tokenizer *p_tokenizer) {
  502. const int line = p_tokenizer->get_line();
  503. String label = p_tokenizer->get_identifier();
  504. if (label.is_empty()) {
  505. set_error(RTR("Invalid macro name."), line);
  506. return;
  507. }
  508. p_tokenizer->skip_whitespace();
  509. if (!is_char_end(p_tokenizer->peek())) {
  510. set_error(RTR("Invalid ifndef."), line);
  511. return;
  512. }
  513. p_tokenizer->advance('\n');
  514. bool success = !state->defines.has(label);
  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_include(Tokenizer *p_tokenizer) {
  521. const int line = p_tokenizer->get_line();
  522. p_tokenizer->advance('"');
  523. String path = tokens_to_string(p_tokenizer->advance('"'));
  524. for (int i = 0; i < path.length(); i++) {
  525. if (path[i] == '\n') {
  526. break; //stop parsing
  527. }
  528. if (path[i] == CURSOR) {
  529. state->completion_type = COMPLETION_TYPE_INCLUDE_PATH;
  530. break;
  531. }
  532. }
  533. path = path.substr(0, path.length() - 1);
  534. p_tokenizer->skip_whitespace();
  535. if (path.is_empty() || !is_char_end(p_tokenizer->peek())) {
  536. set_error(RTR("Invalid path."), line);
  537. return;
  538. }
  539. Ref<Resource> res = ResourceLoader::load(path);
  540. if (res.is_null()) {
  541. set_error(RTR("Shader include load failed. Does the shader include exist? Is there a cyclic dependency?"), line);
  542. return;
  543. }
  544. Ref<ShaderInclude> shader_inc = res;
  545. if (shader_inc.is_null()) {
  546. set_error(RTR("Shader include resource type is wrong."), line);
  547. return;
  548. }
  549. String included = shader_inc->get_code();
  550. if (!included.is_empty()) {
  551. uint64_t code_hash = included.hash64();
  552. if (state->cyclic_include_hashes.find(code_hash)) {
  553. set_error(RTR("Cyclic include found."), line);
  554. return;
  555. }
  556. }
  557. state->shader_includes.insert(shader_inc);
  558. const String real_path = shader_inc->get_path();
  559. if (state->includes.has(real_path)) {
  560. // Already included, skip.
  561. // This is a valid check because 2 separate include paths could use some
  562. // of the same shared functions from a common shader include.
  563. return;
  564. }
  565. // Mark as included.
  566. state->includes.insert(real_path);
  567. state->include_depth++;
  568. if (state->include_depth > 25) {
  569. set_error(RTR("Shader max include depth exceeded."), line);
  570. return;
  571. }
  572. String old_filename = state->current_filename;
  573. state->current_filename = real_path;
  574. ShaderPreprocessor processor;
  575. int prev_condition_depth = state->condition_depth;
  576. state->condition_depth = 0;
  577. FilePosition fp;
  578. fp.file = state->current_filename;
  579. fp.line = line;
  580. state->include_positions.push_back(fp);
  581. String result;
  582. processor.preprocess(state, included, result);
  583. add_to_output("@@>" + real_path + "\n"); // Add token for enter include path
  584. add_to_output(result);
  585. add_to_output("\n@@<\n"); // Add token for exit include path
  586. // Reset to last include if there are no errors. We want to use this as context.
  587. if (state->error.is_empty()) {
  588. state->current_filename = old_filename;
  589. state->include_positions.pop_back();
  590. } else {
  591. return;
  592. }
  593. state->include_depth--;
  594. state->condition_depth = prev_condition_depth;
  595. }
  596. void ShaderPreprocessor::process_pragma(Tokenizer *p_tokenizer) {
  597. const int line = p_tokenizer->get_line();
  598. bool is_cursor;
  599. const String label = p_tokenizer->get_identifier(&is_cursor);
  600. if (is_cursor) {
  601. state->completion_type = COMPLETION_TYPE_PRAGMA;
  602. }
  603. if (label.is_empty()) {
  604. set_error(RTR("Invalid pragma directive."), line);
  605. return;
  606. }
  607. // Rxplicitly handle pragma values here.
  608. // If more pragma options are created, then refactor into a more defined structure.
  609. if (label == "disable_preprocessor") {
  610. state->disabled = true;
  611. } else {
  612. set_error(RTR("Invalid pragma directive."), line);
  613. return;
  614. }
  615. p_tokenizer->advance('\n');
  616. }
  617. void ShaderPreprocessor::process_undef(Tokenizer *p_tokenizer) {
  618. const int line = p_tokenizer->get_line();
  619. const String label = p_tokenizer->get_identifier();
  620. if (label.is_empty() || !state->defines.has(label)) {
  621. set_error(RTR("Invalid name."), line);
  622. return;
  623. }
  624. p_tokenizer->skip_whitespace();
  625. if (!is_char_end(p_tokenizer->peek())) {
  626. set_error(RTR("Invalid undef."), line);
  627. return;
  628. }
  629. memdelete(state->defines[label]);
  630. state->defines.erase(label);
  631. }
  632. void ShaderPreprocessor::add_region(int p_line, bool p_enabled, Region *p_parent_region) {
  633. Region region;
  634. region.file = state->current_filename;
  635. region.enabled = p_enabled;
  636. region.from_line = p_line;
  637. region.parent = p_parent_region;
  638. state->previous_region = &state->regions[region.file].push_back(region)->get();
  639. }
  640. void ShaderPreprocessor::start_branch_condition(Tokenizer *p_tokenizer, bool p_success, bool p_continue) {
  641. if (!p_continue) {
  642. state->condition_depth++;
  643. state->current_branch = &state->branches.push_back(Branch(p_success, state->current_branch))->get();
  644. } else {
  645. state->current_branch->conditions.push_back(p_success);
  646. }
  647. if (!p_success) {
  648. Vector<String> ends;
  649. ends.push_back("elif");
  650. ends.push_back("else");
  651. ends.push_back("endif");
  652. next_directive(p_tokenizer, ends);
  653. }
  654. }
  655. void ShaderPreprocessor::expand_output_macros(int p_start, int p_line_number) {
  656. String line = vector_to_string(output, p_start, output.size());
  657. Error error = expand_macros(line, p_line_number - 1, line); // We are already on next line, so -1.
  658. if (error != OK) {
  659. return;
  660. }
  661. output.resize(p_start);
  662. add_to_output(line);
  663. }
  664. Error ShaderPreprocessor::expand_condition(const String &p_string, int p_line, String &r_expanded) {
  665. // Checks bracket count to be even + check the cursor position.
  666. {
  667. int bracket_start_count = 0;
  668. int bracket_end_count = 0;
  669. for (int i = 0; i < p_string.size(); i++) {
  670. switch (p_string[i]) {
  671. case CURSOR:
  672. state->completion_type = COMPLETION_TYPE_CONDITION;
  673. break;
  674. case '(':
  675. bracket_start_count++;
  676. break;
  677. case ')':
  678. bracket_end_count++;
  679. break;
  680. }
  681. }
  682. if (bracket_start_count > bracket_end_count) {
  683. _set_expected_error(")", p_line);
  684. return FAILED;
  685. }
  686. if (bracket_end_count > bracket_start_count) {
  687. _set_expected_error("(", p_line);
  688. return FAILED;
  689. }
  690. }
  691. String result = p_string;
  692. int index = 0;
  693. int index_start = 0;
  694. int index_end = 0;
  695. while (find_match(result, "defined", index, index_start)) {
  696. bool open_bracket = false;
  697. bool found_word = false;
  698. bool word_completed = false;
  699. LocalVector<char32_t> text;
  700. int post_bracket_index = -1;
  701. int size = result.size();
  702. for (int i = (index_start - 1); i < size; i++) {
  703. char32_t c = result[i];
  704. if (c == 0) {
  705. if (found_word) {
  706. word_completed = true;
  707. }
  708. break;
  709. }
  710. char32_t cs[] = { c, '\0' };
  711. String s = String(cs);
  712. bool is_space = is_char_space(c);
  713. if (word_completed) {
  714. if (c == ')') {
  715. continue;
  716. }
  717. if (c == '|' || c == '&') {
  718. if (open_bracket) {
  719. _set_unexpected_token_error(s, p_line);
  720. return FAILED;
  721. }
  722. break;
  723. } else if (!is_space) {
  724. _set_unexpected_token_error(s, p_line);
  725. return FAILED;
  726. }
  727. } else if (is_space) {
  728. if (found_word && !open_bracket) {
  729. index_end = i;
  730. word_completed = true;
  731. }
  732. } else if (c == '(') {
  733. if (open_bracket) {
  734. _set_unexpected_token_error(s, p_line);
  735. return FAILED;
  736. }
  737. open_bracket = true;
  738. } else if (c == ')') {
  739. if (open_bracket) {
  740. if (!found_word) {
  741. _set_unexpected_token_error(s, p_line);
  742. return FAILED;
  743. }
  744. open_bracket = false;
  745. post_bracket_index = i + 1;
  746. } else {
  747. index_end = i;
  748. }
  749. word_completed = true;
  750. } else if (is_char_word(c)) {
  751. text.push_back(c);
  752. found_word = true;
  753. } else {
  754. _set_unexpected_token_error(s, p_line);
  755. return FAILED;
  756. }
  757. }
  758. if (word_completed) {
  759. if (open_bracket) {
  760. _set_expected_error(")", p_line);
  761. return FAILED;
  762. }
  763. if (post_bracket_index != -1) {
  764. index_end = post_bracket_index;
  765. }
  766. String body = state->defines.has(vector_to_string(text)) ? "true" : "false";
  767. String temp = result;
  768. result = result.substr(0, index) + body;
  769. index_start = result.length();
  770. if (index_end > 0) {
  771. result += temp.substr(index_end);
  772. }
  773. } else {
  774. set_error(RTR("Invalid macro name."), p_line);
  775. return FAILED;
  776. }
  777. }
  778. r_expanded = result;
  779. return OK;
  780. }
  781. Error ShaderPreprocessor::expand_macros(const String &p_string, int p_line, String &r_expanded) {
  782. String iterative = p_string;
  783. int pass_count = 0;
  784. bool expanded = true;
  785. while (expanded) {
  786. expanded = false;
  787. // As long as we find something to expand, keep going.
  788. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  789. if (expand_macros_once(iterative, p_line, E, iterative)) {
  790. expanded = true;
  791. }
  792. }
  793. pass_count++;
  794. if (pass_count > 50) {
  795. set_error(RTR("Macro expansion limit exceeded."), p_line);
  796. break;
  797. }
  798. }
  799. r_expanded = iterative;
  800. if (!state->error.is_empty()) {
  801. return FAILED;
  802. }
  803. return OK;
  804. }
  805. bool ShaderPreprocessor::expand_macros_once(const String &p_line, int p_line_number, const RBMap<String, Define *>::Element *p_define_pair, String &r_expanded) {
  806. String result = p_line;
  807. const String &key = p_define_pair->key();
  808. const Define *define = p_define_pair->value();
  809. int index_start = 0;
  810. int index = 0;
  811. if (find_match(result, key, index, index_start)) {
  812. String body = define->body;
  813. if (define->arguments.size() > 0) {
  814. // Complex macro with arguments.
  815. int args_start = index + key.length();
  816. int args_end = p_line.find(")", args_start);
  817. if (args_start == -1 || args_end == -1) {
  818. set_error(RTR("Missing macro argument parenthesis."), p_line_number);
  819. return false;
  820. }
  821. String values = result.substr(args_start + 1, args_end - (args_start + 1));
  822. Vector<String> args = values.split(",");
  823. if (args.size() != define->arguments.size()) {
  824. set_error(RTR("Invalid macro argument count."), p_line_number);
  825. return false;
  826. }
  827. // Insert macro arguments into the body.
  828. for (int i = 0; i < args.size(); i++) {
  829. String arg_name = define->arguments[i];
  830. int arg_index_start = 0;
  831. int arg_index = 0;
  832. while (find_match(body, arg_name, arg_index, arg_index_start)) {
  833. body = body.substr(0, arg_index) + args[i] + body.substr(arg_index + arg_name.length(), body.length() - (arg_index + arg_name.length()));
  834. // Manually reset arg_index_start to where the arg value of the define finishes.
  835. // This ensures we don't skip the other args of this macro in the string.
  836. arg_index_start = arg_index + args[i].length() + 1;
  837. }
  838. }
  839. result = result.substr(0, index) + " " + body + " " + result.substr(args_end + 1, result.length());
  840. } else {
  841. result = result.substr(0, index) + body + result.substr(index + key.length(), result.length() - (index + key.length()));
  842. // Manually reset index_start to where the body value of the define finishes.
  843. // This ensures we don't skip another instance of this macro in the string.
  844. index_start = index + body.length() + 1;
  845. }
  846. r_expanded = result;
  847. return true;
  848. }
  849. return false;
  850. }
  851. bool ShaderPreprocessor::find_match(const String &p_string, const String &p_value, int &r_index, int &r_index_start) {
  852. // Looks for value in string and then determines if the boundaries
  853. // are non-word characters. This method semi-emulates \b in regex.
  854. r_index = p_string.find(p_value, r_index_start);
  855. while (r_index > -1) {
  856. if (r_index > 0) {
  857. if (is_char_word(p_string[r_index - 1])) {
  858. r_index_start = r_index + 1;
  859. r_index = p_string.find(p_value, r_index_start);
  860. continue;
  861. }
  862. }
  863. if (r_index + p_value.length() < p_string.length()) {
  864. if (is_char_word(p_string[r_index + p_value.length()])) {
  865. r_index_start = r_index + p_value.length() + 1;
  866. r_index = p_string.find(p_value, r_index_start);
  867. continue;
  868. }
  869. }
  870. // Return and shift index start automatically for next call.
  871. r_index_start = r_index + p_value.length() + 1;
  872. return true;
  873. }
  874. return false;
  875. }
  876. String ShaderPreprocessor::next_directive(Tokenizer *p_tokenizer, const Vector<String> &p_directives) {
  877. const int line = p_tokenizer->get_line();
  878. int nesting = 0;
  879. while (true) {
  880. p_tokenizer->advance('#');
  881. String id = p_tokenizer->peek_identifier();
  882. if (id.is_empty()) {
  883. break;
  884. }
  885. if (nesting == 0) {
  886. for (int i = 0; i < p_directives.size(); i++) {
  887. if (p_directives[i] == id) {
  888. p_tokenizer->backtrack('#');
  889. return id;
  890. }
  891. }
  892. }
  893. if (id == "ifdef" || id == "ifndef" || id == "if") {
  894. nesting++;
  895. } else if (id == "endif") {
  896. nesting--;
  897. }
  898. }
  899. set_error(RTR("Can't find matching branch directive."), line);
  900. return "";
  901. }
  902. void ShaderPreprocessor::add_to_output(const String &p_str) {
  903. for (int i = 0; i < p_str.length(); i++) {
  904. output.push_back(p_str[i]);
  905. }
  906. }
  907. void ShaderPreprocessor::set_error(const String &p_error, int p_line) {
  908. if (state->error.is_empty()) {
  909. state->error = p_error;
  910. FilePosition fp;
  911. fp.line = p_line + 1;
  912. state->include_positions.push_back(fp);
  913. }
  914. }
  915. ShaderPreprocessor::Define *ShaderPreprocessor::create_define(const String &p_body) {
  916. ShaderPreprocessor::Define *define = memnew(Define);
  917. define->body = p_body;
  918. return define;
  919. }
  920. void ShaderPreprocessor::clear_state() {
  921. if (state != nullptr) {
  922. for (const RBMap<String, Define *>::Element *E = state->defines.front(); E; E = E->next()) {
  923. memdelete(E->get());
  924. }
  925. state->defines.clear();
  926. }
  927. state = nullptr;
  928. }
  929. Error ShaderPreprocessor::preprocess(State *p_state, const String &p_code, String &r_result) {
  930. output.clear();
  931. state = p_state;
  932. CommentRemover remover(p_code);
  933. String stripped = remover.strip();
  934. String error = remover.get_error();
  935. if (!error.is_empty()) {
  936. set_error(error, remover.get_error_line());
  937. return FAILED;
  938. }
  939. // Track code hashes to prevent cyclic include.
  940. uint64_t code_hash = p_code.hash64();
  941. state->cyclic_include_hashes.push_back(code_hash);
  942. Tokenizer p_tokenizer(stripped);
  943. int last_size = 0;
  944. bool has_symbols_before_directive = false;
  945. while (true) {
  946. const Token &t = p_tokenizer.get_token();
  947. if (t.text == 0) {
  948. break;
  949. }
  950. if (state->disabled) {
  951. // Preprocessor was disabled.
  952. // Read the rest of the file into the output.
  953. output.push_back(t.text);
  954. continue;
  955. } else {
  956. // Add autogenerated tokens.
  957. Vector<Token> generated;
  958. p_tokenizer.get_and_clear_generated(&generated);
  959. for (int i = 0; i < generated.size(); i++) {
  960. output.push_back(generated[i].text);
  961. }
  962. }
  963. if (t.text == '#') {
  964. if (has_symbols_before_directive) {
  965. set_error(RTR("Invalid symbols placed before directive."), p_tokenizer.get_line());
  966. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  967. return FAILED;
  968. }
  969. process_directive(&p_tokenizer);
  970. } else {
  971. if (is_char_end(t.text)) {
  972. expand_output_macros(last_size, p_tokenizer.get_line());
  973. last_size = output.size();
  974. has_symbols_before_directive = false;
  975. } else if (!is_char_space(t.text)) {
  976. has_symbols_before_directive = true;
  977. }
  978. output.push_back(t.text);
  979. }
  980. if (!state->error.is_empty()) {
  981. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  982. return FAILED;
  983. }
  984. }
  985. state->cyclic_include_hashes.erase(code_hash); // Remove this hash.
  986. if (!state->disabled) {
  987. if (state->condition_depth != 0) {
  988. set_error(RTR("Unmatched conditional statement."), p_tokenizer.line);
  989. return FAILED;
  990. }
  991. expand_output_macros(last_size, p_tokenizer.get_line());
  992. }
  993. r_result = vector_to_string(output);
  994. return OK;
  995. }
  996. 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) {
  997. State pp_state;
  998. if (!p_filename.is_empty()) {
  999. pp_state.current_filename = p_filename;
  1000. pp_state.save_regions = r_regions != nullptr;
  1001. }
  1002. Error err = preprocess(&pp_state, p_code, r_result);
  1003. if (err != OK) {
  1004. if (r_error_text) {
  1005. *r_error_text = pp_state.error;
  1006. }
  1007. if (r_error_position) {
  1008. *r_error_position = pp_state.include_positions;
  1009. }
  1010. }
  1011. if (r_regions) {
  1012. *r_regions = pp_state.regions[p_filename];
  1013. }
  1014. if (r_includes) {
  1015. *r_includes = pp_state.shader_includes;
  1016. }
  1017. if (r_completion_defines) {
  1018. for (const KeyValue<String, Define *> &E : state->defines) {
  1019. ScriptLanguage::CodeCompletionOption option(E.key, ScriptLanguage::CODE_COMPLETION_KIND_CONSTANT);
  1020. r_completion_defines->push_back(option);
  1021. }
  1022. }
  1023. if (r_completion_options) {
  1024. switch (pp_state.completion_type) {
  1025. case COMPLETION_TYPE_DIRECTIVE: {
  1026. List<String> options;
  1027. get_keyword_list(&options, true, true);
  1028. for (const String &E : options) {
  1029. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1030. r_completion_options->push_back(option);
  1031. }
  1032. } break;
  1033. case COMPLETION_TYPE_PRAGMA: {
  1034. List<String> options;
  1035. ShaderPreprocessor::get_pragma_list(&options);
  1036. for (const String &E : options) {
  1037. ScriptLanguage::CodeCompletionOption option(E, ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1038. r_completion_options->push_back(option);
  1039. }
  1040. } break;
  1041. case COMPLETION_TYPE_CONDITION: {
  1042. ScriptLanguage::CodeCompletionOption option("defined", ScriptLanguage::CODE_COMPLETION_KIND_PLAIN_TEXT);
  1043. r_completion_options->push_back(option);
  1044. } break;
  1045. case COMPLETION_TYPE_INCLUDE_PATH: {
  1046. if (p_include_completion_func && r_completion_options) {
  1047. p_include_completion_func(r_completion_options);
  1048. }
  1049. } break;
  1050. default: {
  1051. }
  1052. }
  1053. }
  1054. clear_state();
  1055. return err;
  1056. }
  1057. void ShaderPreprocessor::get_keyword_list(List<String> *r_keywords, bool p_include_shader_keywords, bool p_ignore_context_keywords) {
  1058. r_keywords->push_back("define");
  1059. if (!p_ignore_context_keywords) {
  1060. r_keywords->push_back("defined");
  1061. }
  1062. r_keywords->push_back("elif");
  1063. if (p_include_shader_keywords) {
  1064. r_keywords->push_back("else");
  1065. }
  1066. r_keywords->push_back("endif");
  1067. if (p_include_shader_keywords) {
  1068. r_keywords->push_back("if");
  1069. }
  1070. r_keywords->push_back("ifdef");
  1071. r_keywords->push_back("ifndef");
  1072. r_keywords->push_back("include");
  1073. r_keywords->push_back("pragma");
  1074. r_keywords->push_back("undef");
  1075. }
  1076. void ShaderPreprocessor::get_pragma_list(List<String> *r_pragmas) {
  1077. r_pragmas->push_back("disable_preprocessor");
  1078. }
  1079. ShaderPreprocessor::ShaderPreprocessor() {
  1080. }
  1081. ShaderPreprocessor::~ShaderPreprocessor() {
  1082. }